From 9308ad03be5f697a75d3d1872515ba06601538d8 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 12:59:35 -0800 Subject: [PATCH 1/9] test: remove 21 low-value CLI and GitHub tests (#39963) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/flaky-test-pattern-baseline.txt | 1 - ...automation-owner-conflict-recovery.test.ts | 23 -- src/cli/format.test.ts | 375 +----------------- ...hestration-dispatch-refusal-format.test.ts | 31 -- .../github/body-image-read-adapters.test.ts | 46 --- src/main/github/body-image-urls.test.ts | 93 +---- src/main/github/issue-comment-image.test.ts | 74 ---- .../project-view/body-image-mutations.test.ts | 61 --- .../pinned-runtime-host-target.test.ts | 29 -- .../worker/worker-start-budgets.test.ts | 13 - 10 files changed, 4 insertions(+), 742 deletions(-) delete mode 100644 src/cli/automation-owner-conflict-recovery.test.ts delete mode 100644 src/cli/orchestration-dispatch-refusal-format.test.ts delete mode 100644 src/main/github/issue-comment-image.test.ts delete mode 100644 src/main/managed-server/install/pinned-runtime-host-target.test.ts delete mode 100644 src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index fb539aa9486..4cfe7b8a073 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -464,7 +464,6 @@ 1 test-no-wall-clock:config/scripts/worktree-storage/reclaim-release-test-caches.test.ts 1 test-no-wall-clock:mobile/scripts/native-build-cache.test.ts 1 test-no-wall-clock:mobile/src/pairing/mobile-relay-invite-director.test.ts -1 test-no-wall-clock:src/cli/format.test.ts 2 test-no-wall-clock:src/cli/runtime/serve-appimage-update.test.ts 4 test-no-wall-clock:src/cli/runtime/serve-bundle-park.test.ts 5 test-no-wall-clock:src/cli/runtime/serve-pid1-init-reaper.test.ts diff --git a/src/cli/automation-owner-conflict-recovery.test.ts b/src/cli/automation-owner-conflict-recovery.test.ts deleted file mode 100644 index fd6e64ea080..00000000000 --- a/src/cli/automation-owner-conflict-recovery.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { formatCliError } from './format' -import { RuntimeRpcFailureError } from './runtime-client' - -function conflict(code: string, message: string): RuntimeRpcFailureError { - return new RuntimeRpcFailureError({ - id: 'request-1', - ok: false, - error: { code, message: `${message}: ${code}` }, - _meta: { runtimeId: 'runtime-1' } - }) -} - -afterEach(() => vi.restoreAllMocks()) - -describe('automation owner conflicts read as CLI outcomes', () => { - it('leaves unrelated failures untouched', () => { - const output = formatCliError(conflict('runtime_error', 'Something else')) - - expect(output).toBe('Something else: runtime_error') - }) -}) diff --git a/src/cli/format.test.ts b/src/cli/format.test.ts index f53b78fc4c5..7fba85f8000 100644 --- a/src/cli/format.test.ts +++ b/src/cli/format.test.ts @@ -1,17 +1,9 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { - formatAutomationShow, - formatComputerAction, - formatTerminalList, - formatWorktreeList, - printResult -} from './format' -import type { ComputerActionResult, RuntimeWorktreeRecord } from '../shared/runtime-types' -import type { Automation } from '../shared/automations/automation-definition' +import { printResult } from './format' let testScreenshotDir: string | null = null @@ -24,370 +16,7 @@ afterEach(() => { } }) -function worktree(overrides: Partial = {}): RuntimeWorktreeRecord { - const base: RuntimeWorktreeRecord = { - id: 'repo::/tmp/repo/child', - repoId: 'repo', - path: '/tmp/repo/child', - head: 'abc123', - branch: 'feature/child', - isBare: false, - isMainWorktree: false, - parentWorktreeId: null, - childWorktreeIds: [], - lineage: null, - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - git: { - path: '/tmp/repo/child', - head: 'abc123', - branch: 'feature/child', - isBare: false, - isMainWorktree: false - }, - displayName: '', - comment: '' - } - return { ...base, ...overrides } -} - -describe('formatWorktreeList', () => { - it('includes parent and child workspace relationships in text output', () => { - const output = formatWorktreeList({ - worktrees: [ - worktree({ - id: 'repo::/tmp/repo/parent', - path: '/tmp/repo/parent', - branch: 'feature/parent', - childWorktreeIds: ['repo::/tmp/repo/child'] - }), - worktree({ - parentWorktreeId: 'repo::/tmp/repo/parent' - }) - ], - totalCount: 2, - truncated: false - }) - - const [parent, child] = output.split('\n\n') - expect(parent).toContain('repo::/tmp/repo/parent feature/parent') - expect(parent).toContain('parentWorktreeId: null') - expect(parent).toContain('childWorktreeIds: repo::/tmp/repo/child') - expect(child).toContain('repo::/tmp/repo/child feature/child') - expect(child).toContain('parentWorktreeId: repo::/tmp/repo/parent') - expect(child).toContain('childWorktreeIds: []') - }) -}) - -describe('formatAutomationShow', () => { - function automation(overrides: Partial = {}): Automation { - return { - id: 'auto-1', - name: 'Nightly', - prompt: 'Run checks', - precheck: null, - agentId: 'codex', - projectId: 'repo-legacy', - executionTargetType: 'local', - executionTargetId: 'local', - schedulerOwner: 'local_host_service', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0', - dtstart: 0, - enabled: true, - nextRunAt: 0, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 720, - createdAt: 0, - updatedAt: 0, - ...overrides - } - } - - it('shows explicit run context before the legacy repo id', () => { - const output = formatAutomationShow({ - automation: automation({ - runContext: { - kind: 'workspace-run', - projectId: 'github:stablyai/orca', - hostId: 'runtime:gpu', - projectHostSetupId: 'setup-gpu', - repoId: 'repo-gpu', - path: '/srv/orca' - } - }) - }) - - expect(output).toContain('runProjectId: github:stablyai/orca') - expect(output).toContain('runHostId: runtime:gpu') - expect(output).toContain('projectHostSetupId: setup-gpu') - expect(output).toContain('runRepoId: repo-gpu') - expect(output).toContain('runPath: /srv/orca') - expect(output).toContain('legacyRepoId: repo-legacy') - expect(output).not.toContain('projectId: repo-legacy') - }) -}) - -describe('formatTerminalList', () => { - it('prints visual split groups and nested terminal panes', () => { - const output = formatTerminalList({ - terminals: [ - { - handle: 'term_left', - ptyId: 'pty-left', - worktreeId: 'wt-1', - worktreePath: '/repo', - branch: 'main', - tabId: 'tab-left', - leafId: 'leaf-left', - title: 'Left', - connected: true, - writable: true, - lastOutputAt: null, - preview: '' - }, - { - handle: 'term_top', - ptyId: 'pty-top', - worktreeId: 'wt-1', - worktreePath: '/repo', - branch: 'main', - tabId: 'tab-right', - leafId: 'leaf-top', - title: 'Right top', - connected: true, - writable: true, - lastOutputAt: null, - preview: '' - }, - { - handle: 'term_bottom', - ptyId: 'pty-bottom', - worktreeId: 'wt-1', - worktreePath: '/repo', - branch: 'main', - tabId: 'tab-right', - leafId: 'leaf-bottom', - title: 'Right bottom', - connected: true, - writable: true, - lastOutputAt: null, - preview: '' - } - ], - totalCount: 3, - truncated: false, - visualLayouts: [ - { - worktreeId: 'wt-1', - worktreePath: '/repo', - root: { - type: 'split', - direction: 'horizontal', - first: { - type: 'group', - groupId: 'group-left', - activeTabId: 'tab-left', - tabs: [ - { - tabId: 'tab-left', - title: 'Left', - activeLeafId: 'leaf-left', - panes: { - type: 'terminal', - handle: 'term_left', - tabId: 'tab-left', - leafId: 'leaf-left', - title: 'Left', - connected: true, - active: true - } - } - ] - }, - second: { - type: 'group', - groupId: 'group-right', - activeTabId: 'tab-right', - tabs: [ - { - tabId: 'tab-right', - title: 'Right', - activeLeafId: 'leaf-bottom', - panes: { - type: 'pane-split', - direction: 'vertical', - first: { - type: 'terminal', - handle: 'term_top', - tabId: 'tab-right', - leafId: 'leaf-top', - title: 'Right top', - connected: true, - active: false - }, - second: { - type: 'terminal', - handle: 'term_bottom', - tabId: 'tab-right', - leafId: 'leaf-bottom', - title: 'Right bottom', - connected: true, - active: true - } - } - } - ] - } - } - } - ] - } as never) - - expect(output).toContain('visual layout:') - expect(output).toContain('/repo') - expect(output).toContain('split horizontal') - expect(output).toContain('group group-left') - expect(output).toContain('tab tab-left Left') - expect(output).toContain('* term_left Left tab=tab-left leaf=leaf-left') - expect(output).toContain('group group-right') - expect(output).toContain('pane split vertical') - expect(output).toContain(' term_top Right top tab=tab-right leaf=leaf-top') - expect(output).toContain('* term_bottom Right bottom tab=tab-right leaf=leaf-bottom') - }) -}) - -describe('formatComputerAction', () => { - it('preserves explicit window-index targeting in the suggested follow-up command', () => { - const result: ComputerActionResult = { - snapshot: { - id: 'snap-1', - app: { name: 'Finder', bundleId: 'com.apple.finder', pid: 100 }, - window: { title: 'Document', id: 42, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 5, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' } - } - - const output = formatComputerAction('click', result, { - session: 'manual', - windowIndex: 1 - }) - - expect(output).toContain( - 'Use `orca computer get-app-state --app com.apple.finder --session manual --window-index 1`' - ) - }) - - it('uses snapshot window index for follow-up commands when the provider has no stable window id', () => { - const result: ComputerActionResult = { - snapshot: { - id: 'snap-1', - app: { name: 'Linux Browser', bundleId: null, pid: 100 }, - window: { title: 'Inbox', id: null, index: 2, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 5, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' }, - action: { - path: 'synthetic', - targetWindowId: null - } - } - - const output = formatComputerAction('click', result) - - const app = process.platform === 'win32' ? '"Linux Browser"' : "'Linux Browser'" - expect(output).toContain(`Use \`orca computer get-app-state --app ${app} --window-index 2\``) - expect(output).not.toContain('--window-id') - }) - - it('uses action target window index before snapshot fallback for ID-less providers', () => { - const result: ComputerActionResult = { - snapshot: { - id: 'snap-1', - app: { name: 'Linux Browser', bundleId: null, pid: 100 }, - window: { title: 'Inbox', id: null, index: 4, width: 800, height: 600 }, - coordinateSpace: 'window', - treeText: 'tree', - elementCount: 5, - focusedElementId: null - }, - screenshot: null, - screenshotStatus: { state: 'skipped', reason: 'no_screenshot_flag' }, - action: { - path: 'synthetic', - targetWindowId: null, - targetWindowIndex: 2 - } - } - - const output = formatComputerAction('click', result) - - const app = process.platform === 'win32' ? '"Linux Browser"' : "'Linux Browser'" - expect(output).toContain(`Use \`orca computer get-app-state --app ${app} --window-index 2\``) - expect(output).not.toContain('--window-index 4') - expect(output).not.toContain('--window-id') - }) -}) - describe('printResult computer screenshots', () => { - it('skips screenshot temp cleanup when the cleanup marker is fresh', () => { - testScreenshotDir = mkdtempSync(join(tmpdir(), 'orca-format-test-')) - const expiredPath = join(testScreenshotDir, 'old-screenshot.png') - writeFileSync(expiredPath, 'old') - const expired = new Date(Date.now() - 48 * 60 * 60 * 1000) - utimesSync(expiredPath, expired, expired) - writeFileSync(join(testScreenshotDir, '.last-cleanup'), 'recent\n') - process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR = testScreenshotDir - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined) - - printResult( - { - id: 'req/1', - ok: true, - result: { - screenshot: { - data: Buffer.from('png-data').toString('base64'), - format: 'png', - width: 1, - height: 1, - scale: 1 - }, - screenshotStatus: { state: 'captured' } - }, - _meta: { runtimeId: 'runtime-1' } - }, - true, - () => 'unused' - ) - - expect(existsSync(expiredPath)).toBe(true) - const output: { - result: { screenshot: { dataOmitted: boolean; path: string } } - } = JSON.parse(logSpy.mock.calls[0][0]) - expect(output.result.screenshot.dataOmitted).toBe(true) - expect(output.result.screenshot.path).toContain('req_1-screenshot.png') - expect(readFileSync(output.result.screenshot.path, 'utf8')).toBe('png-data') - }) - it('keeps inline screenshot data when temp export fails', () => { testScreenshotDir = join(tmpdir(), `orca-format-blocked-${Date.now()}`) writeFileSync(testScreenshotDir, 'not-a-directory') diff --git a/src/cli/orchestration-dispatch-refusal-format.test.ts b/src/cli/orchestration-dispatch-refusal-format.test.ts deleted file mode 100644 index df881ed4974..00000000000 --- a/src/cli/orchestration-dispatch-refusal-format.test.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' - -import { formatCliError, reportCliError } from './format' -import { RuntimeRpcFailureError, type RuntimeRpcFailure } from './runtime/types' - -afterEach(() => { - vi.restoreAllMocks() -}) - -// Runtime envelopes may contain codes introduced after this client; formatting must preserve them. - -it('prints an unknown code with its message and nextSteps unchanged', () => { - const failure: RuntimeRpcFailure = { - id: 'rpc_1', - ok: false, - error: { - code: 'code_from_a_newer_host', - message: 'Refused for a reason this CLI has never heard of.', - data: { nextSteps: ['Do the thing the newer host suggested.'] } - }, - _meta: { runtimeId: 'runtime_1' } - } - const error = new RuntimeRpcFailureError(failure) - - expect(formatCliError(error, { commandPath: ['orchestration', 'dispatch'] })).toBe( - 'Refused for a reason this CLI has never heard of.\nNext step: Do the thing the newer host suggested.' - ) - const log = vi.spyOn(console, 'log').mockImplementation(() => {}) - reportCliError(error, true, { commandPath: ['orchestration', 'dispatch'] }) - expect(JSON.parse(log.mock.calls[0]?.[0] as string)).toEqual(failure) -}) diff --git a/src/main/github/body-image-read-adapters.test.ts b/src/main/github/body-image-read-adapters.test.ts index 8dcd75701bc..45a2f92aca0 100644 --- a/src/main/github/body-image-read-adapters.test.ts +++ b/src/main/github/body-image-read-adapters.test.ts @@ -15,7 +15,6 @@ vi.mock('./project-view/internals', () => ({ projectGhExecOptions: () => ({}), runGraphql: mocks.graphql })) -import { getPRMetadata } from './pull-request-file-data' import { getWorkItemDetailsBySlug } from './project-view/work-item-details' const body = @@ -31,51 +30,6 @@ beforeEach(() => { mocks.graphql.mockReset() }) -it('gets PR metadata images in its existing uncached full-media read', async () => { - mocks.exec.mockResolvedValueOnce({ - stdout: JSON.stringify({ body, body_html: html, head: { sha: 'head' } }) - }) - const metadata = await getPRMetadata('/repo', 7, { owner: 'acme', repo: 'widgets' }) - expect(metadata).toMatchObject({ body, headSha: 'head', bodyImageUrls: expectedMap }) - expect(mocks.exec).toHaveBeenCalledTimes(1) - expect(mocks.exec.mock.calls[0][0]).toEqual([ - 'api', - '-H', - 'Accept: application/vnd.github.full+json', - 'repos/acme/widgets/pulls/7' - ]) -}) - -it.each(['issue', 'pr'] as const)( - 'gets slug %s body and comment images in one existing read', - async (type) => { - mocks.graphql.mockResolvedValueOnce({ - ok: true, - data: { - repository: { - [type === 'issue' ? 'issue' : 'pullRequest']: { - id: 'ITEM', - body, - bodyHTML: html, - comments: { nodes: [{ databaseId: 1, body, bodyHTML: html }] } - } - } - } - }) - const result = await getWorkItemDetailsBySlug({ - owner: 'acme', - repo: 'widgets', - number: 7, - type - }) - expect(result.ok && result.details.body).toBe(body) - expect(result.ok && result.details.bodyImageUrls).toEqual(expectedMap) - expect(result.ok && result.details.comments[0].bodyImageUrls).toEqual(expectedMap) - expect(mocks.graphql).toHaveBeenCalledTimes(1) - expect(mocks.exec).not.toHaveBeenCalled() - } -) - it.each(['issue', 'pr'] as const)( 'recovers available slug %s data without trusting failed HTML', async (type) => { diff --git a/src/main/github/body-image-urls.test.ts b/src/main/github/body-image-urls.test.ts index a9cb4b32f46..07ee91dac34 100644 --- a/src/main/github/body-image-urls.test.ts +++ b/src/main/github/body-image-urls.test.ts @@ -1,7 +1,6 @@ import type * as HtmlParser from 'hast-util-from-html-isomorphic' -import type { Root, RootContent } from 'hast' import { describe, expect, it, vi } from 'vitest' -const traversal = vi.hoisted(() => ({ enabled: false, parses: 0, children: 0, fail: false })) +const traversal = vi.hoisted(() => ({ fail: false })) vi.mock('hast-util-from-html-isomorphic', async (load) => { const actual = await load() return { @@ -10,27 +9,7 @@ vi.mock('hast-util-from-html-isomorphic', async (load) => { if (traversal.fail) { throw new Error('Optional image HTML could not be parsed') } - const tree = actual.fromHtmlIsomorphic(...args) - if (!traversal.enabled) { - return tree - } - traversal.parses++ - const pending: (Root | RootContent)[] = [tree] - while (pending.length) { - const node = pending.pop()! - if (!('children' in node)) { - continue - } - const children = node.children - pending.push(...children) - Object.defineProperty(node, 'children', { - get: () => { - traversal.children++ - return children - } - }) - } - return tree + return actual.fromHtmlIsomorphic(...args) } } }) @@ -41,24 +20,6 @@ const signed = 'https://private-user-images.githubusercontent.com/1/2-ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST&download=1' describe('GitHub body image sources', () => { - it.each([ - { body: `![shot](${original})`, html: true }, - { body: true, html: `` } - ])('ignores unusable optional representations ($body, $html)', ({ body, html }) => { - expect(githubBodyImageUrls(body, html)).toBeUndefined() - }) - - it('skips HTML parsing when the Markdown has no attachment candidates', () => { - traversal.enabled = true - traversal.parses = 0 - try { - expect(githubBodyImageUrls('A plain comment', ``)).toBeUndefined() - expect(traversal.parses).toBe(0) - } finally { - traversal.enabled = false - } - }) - it('leaves the optional map absent if HTML extraction fails', () => { traversal.fail = true try { @@ -85,54 +46,4 @@ describe('GitHub body image sources', () => { ) ).toBeUndefined() }) - - it('bounds candidate validation and indexed lookups at N and 10N', () => { - for (const n of [100, 1000]) { - const ids = Array.from( - { length: n }, - (_, i) => `ce11040a-fb66-4289-927f-${String(i).padStart(12, '0')}` - ) - const body = ids - .map((id) => `![shot](https://github.com/user-attachments/assets/${id})`) - .join('\n') - const html = ids - .map( - (id) => - `` - ) - .join('\n') - traversal.enabled = true - traversal.parses = 0 - traversal.children = 0 - const pathname = vi.spyOn(URL.prototype, 'pathname', 'get') - const originalGet = Map.prototype.get - let lookups = 0 - Map.prototype.get = function (this: Map, key: unknown) { - if (typeof key === 'string' && key.startsWith('ce11040a-')) { - lookups++ - } - return originalGet.call(this, key) - } - try { - const result = githubBodyImageUrls(body, html) - expect(Object.keys(result ?? {})).toHaveLength(n) - // Each candidate and original is checked once, then each original gets one indexed lookup. - expect(pathname.mock.calls.length).toBeLessThanOrEqual(3 * n) - expect(lookups).toBe(n) - expect(traversal.parses).toBe(1) - expect(traversal.children).toBeLessThanOrEqual(n + 1) - expect( - result?.[ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-000000000000' - ] - ).toBe( - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-000000000000.png?jwt=TEST' - ) - } finally { - traversal.enabled = false - Map.prototype.get = originalGet - pathname.mockRestore() - } - } - }) }) diff --git a/src/main/github/issue-comment-image.test.ts b/src/main/github/issue-comment-image.test.ts deleted file mode 100644 index c22f437bd88..00000000000 --- a/src/main/github/issue-comment-image.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { expect, it, vi } from 'vitest' -const mocks = vi.hoisted(() => ({ exec: vi.fn() })) -vi.mock('./gh-utils', () => ({ - ghExecFileAsync: mocks.exec, - acquire: async () => {}, - release: () => {}, - classifyGhError: () => ({ type: 'unknown' }) -})) -vi.mock('./github-api-repository', () => ({ - resolveGitHubRepoExecution: async () => ({ - ownerRepo: { owner: 'acme', repo: 'widgets' }, - ghOptions: {} - }) -})) -import { addIssueComment } from './issue-comment' -import { addPRReviewComment, addPRReviewCommentReply } from './client/create/add-pr-review-comment' - -it('returns signed display sources immediately after posting the original Markdown', async () => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - mocks.exec.mockResolvedValue({ - stdout: JSON.stringify({ - id: 1, - user: null, - body, - body_html: - '' - }) - }) - const result = await addIssueComment('/repo', 42, body) - expect(mocks.exec.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') - expect(mocks.exec.mock.calls[0][1].stdin).toBe(JSON.stringify({ body })) - expect(result.ok && result.comment.body).toBe(body) - expect(result.ok && result.comment.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) -}) - -it.each(['review', 'reply'])( - 'returns paired image sources immediately for %s posts', - async (kind) => { - mocks.exec.mockClear() - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - mocks.exec.mockResolvedValue({ - stdout: JSON.stringify({ - id: 1, - body, - user: null, - body_html: - '' - }) - }) - const result = - kind === 'review' - ? await addPRReviewComment({ - repoPath: '/repo', - prNumber: 7, - body, - commitId: 'head', - path: 'file.ts', - line: 1 - }) - : await addPRReviewCommentReply('/repo', 7, 1, body) - expect(result.ok && result.comment.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) - expect(mocks.exec.mock.calls[0][0]).toContain( - 'body=![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - ) - } -) diff --git a/src/main/github/project-view/body-image-mutations.test.ts b/src/main/github/project-view/body-image-mutations.test.ts index 53c0925b77f..2230f380082 100644 --- a/src/main/github/project-view/body-image-mutations.test.ts +++ b/src/main/github/project-view/body-image-mutations.test.ts @@ -47,8 +47,6 @@ vi.mock('./internals', () => ({ })) import { updateIssueBySlug } from './mutations' -import { updatePullRequestBySlug } from './pull-request-mutation' -import { addIssueCommentBySlug } from './issue-comment-mutations' describe('Project accepted body representations', () => { beforeEach(() => { @@ -61,51 +59,6 @@ describe('Project accepted body representations', () => { runRestMock.mockReset().mockResolvedValue({ ok: true, data: {} }) }) - it.each([updateIssueBySlug, updatePullRequestBySlug])( - 'returns paired image sources after a body edit', - async (update) => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - runRestMock.mockResolvedValueOnce({ - ok: true, - data: { - body, - body_html: - '' - } - }) - const result = await update({ owner: 'acme', repo: 'widgets', number: 12, updates: { body } }) - expect(result).toEqual({ - ok: true, - bodyImageUrls: { - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - } - }) - expect(runRestMock.mock.calls[0][0]).toContain(`body=${body}`) - expect(runRestMock.mock.calls[0][0]).toContain('Accept: application/vnd.github.full+json') - } - ) - - it('returns the paired source for a newly posted Project comment', async () => { - const body = - '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - runRestMock.mockResolvedValueOnce({ - ok: true, - data: { - id: 1, - body, - body_html: - '' - } - }) - const result = await addIssueCommentBySlug({ owner: 'acme', repo: 'widgets', number: 12, body }) - expect(result.ok && result.comment.bodyImageUrls).toEqual({ - 'https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488': - 'https://private-user-images.githubusercontent.com/1/ce11040a-fb66-4289-927f-547b16dfc488.png?jwt=TEST' - }) - }) - it('does not attach a Project issue map from a different accepted body snapshot', async () => { const body = '![shot](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' @@ -122,20 +75,6 @@ describe('Project accepted body representations', () => { ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) }) - it('keeps an accepted PR body save successful without an optional representation', async () => { - runRestMock.mockResolvedValueOnce({ ok: true, data: null }) - await expect( - updatePullRequestBySlug({ - owner: 'acme', - repo: 'widgets', - number: 12, - updates: { - body: '![new](https://github.com/user-attachments/assets/ce11040a-fb66-4289-927f-547b16dfc488)' - } - }) - ).resolves.toEqual({ ok: true, bodyImageUrls: undefined }) - }) - it.each([null, true])( 'finishes a Project compound save with unusable optional HTML (%s)', async (html) => { diff --git a/src/main/managed-server/install/pinned-runtime-host-target.test.ts b/src/main/managed-server/install/pinned-runtime-host-target.test.ts deleted file mode 100644 index c2f5b5c45ee..00000000000 --- a/src/main/managed-server/install/pinned-runtime-host-target.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { pinnedRuntimeTargetForHost } from './pinned-runtime-host-target' - -describe('pinned runtime host target', () => { - it('names the runtime a host can run by glibc alone', () => { - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 28 } }) - ).toBe('linux-x64-glibc') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 27 } }) - ).toBe('linux-x64-glibc217') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 17 } }) - ).toBe('linux-x64-glibc217') - expect( - pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: { major: 2, minor: 12 } }) - ).toBeNull() - expect( - pinnedRuntimeTargetForHost({ target: 'linux-arm64-glibc', glibc: { major: 2, minor: 17 } }) - ).toBeNull() - expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-glibc', glibc: null })).toBe( - 'linux-x64-glibc' - ) - expect(pinnedRuntimeTargetForHost({ target: 'linux-x64-musl', glibc: null })).toBe( - 'linux-x64-musl' - ) - }) -}) diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts deleted file mode 100644 index bbbd83ab00f..00000000000 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-start-budgets.test.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { MAX_TIMER_DELAY_MS } from '../../../../../../shared/timer-delay' -import { ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS } from '../../../../../../shared/orchestration/orchestration-timing-budgets' -import { resolveFederatedWorkerStartBudgets } from './worker-start-budgets' - -describe('worker-start transport budgets', () => { - it('does not silently shorten an overflowing request', () => { - const timeoutMs = MAX_TIMER_DELAY_MS - ORCHESTRATION_WORKER_START_CLIENT_GRACE_MS + 1 - expect(() => resolveFederatedWorkerStartBudgets(timeoutMs, 1_000)).toThrow( - 'derived timeout must fit' - ) - }) -}) From da8162e3b9179abbd08ed8a340656357b756338d Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Sun, 8 Nov 2026 21:03:11 +0000 Subject: [PATCH 2/9] fix(native-chat): send queued messages after resuming a chat interrupted by a restart (#39965) --- .../structured-agent-session-queued-pause.ts | 11 ++++++++++ ...ssion-restart-interruption-test-harness.ts | 3 ++- ...ured-agent-session-restart-continuation.ts | 22 +++++++++++++++++-- ...ructured-agent-session-restart-cap.test.ts | 1 + 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts index af255f5b5f1..b3f25e8c522 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-queued-pause.ts @@ -40,3 +40,14 @@ export async function resumeStructuredQueue( await journal.appendQueueResume(fence, receipt) return true } + +/** A person's chosen continuation is their recovery from a restart; other pauses keep their own lift. */ +export async function liftStructuredQueueRestartHold( + journal: Pick, + fence: number +): Promise { + const pauses = structuredQueuePauses(journal) + if (pauses.length > 0 && pauses.every((pause) => pause.reason === 'restarted')) { + await journal.appendQueueResume(fence) + } +} diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts index fbcbaffaf00..8e40358d691 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-restart-interruption-test-harness.ts @@ -134,7 +134,8 @@ export async function interruptedRestart( const fields = { body, delivery: 'queue-if-active' as const } const queued = await previous.host.send(CALLER, { envelope: envelope('agentSession.send', fields), - ...fields + ...fields, + userSend: true }) expect(queued).toMatchObject({ ok: true, value: { queued: expect.anything() } }) } diff --git a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts index 9075f8218cd..a4ff1c78c62 100644 --- a/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts +++ b/src/main/native-chat/agent-session-wire/recovery/structured-agent-session-restart-continuation.ts @@ -32,6 +32,7 @@ import { AgentSessionPreDispatchError } from '../operations/structured-agent-ses import { restartContinuationEnvelope } from './structured-agent-session-restart-continuation-envelope' import type { AgentSessionResumeMarker } from '../../../../shared/agent-session/lifecycle/agent-session-resume-marker' import type { StructuredAgentSessionLogger } from '../host/structured-agent-session-logger' +import { liftStructuredQueueRestartHold } from '../delivery/structured-agent-session-queued-pause' /** Envelope acceptance proves only host ownership; preserve provider pending/unknown/rejected outcomes. */ export type StructuredAgentSessionContinuationOutcome = { @@ -90,7 +91,14 @@ export function continuationDeps( (await host.awaitSendHandedOver(sessionId, clientMessageId))?.value ), logger: host.logger, - note: restartNoteWriter(host) + note: restartNoteWriter(host), + liftRestartHold: async (sessionId) => { + const session = host.sessions.get(sessionId) + const fence = host.conversationFence(sessionId) + if (session && fence !== null) { + await liftStructuredQueueRestartHold(session.journal, fence) + } + } } } @@ -154,6 +162,8 @@ export type StructuredAgentSessionContinuationDeps = { ) => Promise /** Attribute host continuation/failure; older clients render tone as plain text. */ note: (sessionId: string, text: string, tone?: 'error' | 'warning') => Promise + /** Release cards held only by the restart once the person's continuation is accepted. */ + liftRestartHold: (sessionId: string) => Promise /** Required to report best-effort note failures. */ logger: StructuredAgentSessionLogger /** Answer at acceptance; caller reports pre-acceptance refusal without duplicate retry notes. */ @@ -198,11 +208,19 @@ export async function startStructuredAgentSessionContinuation( } async function noteOutcome( - deps: Pick, + deps: Pick, sessionId: string, result: StructuredAgentSessionContinuationOutcome ): Promise { if (result.outcome === 'continued') { + try { + await deps.liftRestartHold(sessionId) + } catch { + deps.logger.warn('releasing queued messages after a restart continuation failed', { + scope: 'restart-continuation-queue', + sessionId + }) + } // Attribute only accepted dispatch; note failure must not turn delivered work into failure. try { await deps.note(sessionId, AGENT_SESSION_RESTART_CONTINUATION_NOTE) diff --git a/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts b/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts index 1e722273747..0863ed3c9af 100644 --- a/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts +++ b/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts @@ -34,6 +34,7 @@ it('holds each slot from accept until handover or rejection, and frees it when t }, awaitSettlement: async () => ({ dispatchState: 'accepted' }), note: async () => undefined, + liftRestartHold: async () => undefined, logger: createStructuredAgentSessionLogger() }) const sessions = Array.from({ length: 8 }, (_, index) => `session-${index}`) From 29c72956204e4d94a1f15f51234b92535b1acb82 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 13:14:55 -0800 Subject: [PATCH 3/9] test: remove 15 low-value SSH tests (#39968) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- .../ssh-connect-attempt-cancellation.test.ts | 27 ------- .../ssh/external-editors/zed-ssh-url.test.ts | 71 ------------------- .../ssh-host-server-telemetry.test.ts | 50 ------------- .../ssh-relay-endpoint-runtime.test.ts | 21 ------ .../ssh-relay-sentinel-copy-budget.test.ts | 41 ++++++----- ...-remote-windows-command-line-limit.test.ts | 11 --- .../remote-host/ssh-remote-platform.test.ts | 4 -- .../system-ssh-sftp-path.test.ts | 16 ----- 8 files changed, 20 insertions(+), 221 deletions(-) delete mode 100644 src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts delete mode 100644 src/main/ssh/external-editors/zed-ssh-url.test.ts delete mode 100644 src/main/ssh/host-server/ssh-host-server-telemetry.test.ts delete mode 100644 src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts diff --git a/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts b/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts deleted file mode 100644 index c2d40ae0c72..00000000000 --- a/src/main/ssh/connection/reconnect/ssh-connect-attempt-cancellation.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, it, expect } from 'vitest' -import { - createCancelledConnectAttemptError, - isCancelledConnectAttemptError -} from './ssh-connect-attempt-cancellation' -import { isAuthError, isTransientReconnectError } from './ssh-reconnect-error-classification' - -describe('createCancelledConnectAttemptError', () => { - it('is recognisable by identity, not just by message text', () => { - const error = createCancelledConnectAttemptError() - expect(isCancelledConnectAttemptError(error)).toBe(true) - // A cancelled attempt must never look like a permanent failure to the reconnect ladder. - expect(isTransientReconnectError(error)).toBe(false) - expect(isAuthError(error)).toBe(false) - }) - - it('does not classify unrelated errors as cancellations', () => { - expect(isCancelledConnectAttemptError(new Error('connect ETIMEDOUT'))).toBe(false) - }) - - it('ignores a lookalike message from a producer that skipped the factory', () => { - // Every real producer imports the factory, so message text alone must not qualify. - expect( - isCancelledConnectAttemptError(new Error(createCancelledConnectAttemptError().message)) - ).toBe(false) - }) -}) diff --git a/src/main/ssh/external-editors/zed-ssh-url.test.ts b/src/main/ssh/external-editors/zed-ssh-url.test.ts deleted file mode 100644 index 4be131c5727..00000000000 --- a/src/main/ssh/external-editors/zed-ssh-url.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { SshTarget } from '../../../shared/ssh-types' -import { resolveZedSshUrl } from './zed-ssh-url' - -function createTarget(overrides: Partial = {}): SshTarget { - return { - id: 'ssh-1', - label: 'Builder', - host: 'builder.example.com', - port: 22, - username: 'ada', - source: 'manual', - ...overrides - } -} - -describe('resolveZedSshUrl', () => { - it('keeps a custom port in the URL instead of requiring an SSH config alias', () => { - expect(resolveZedSshUrl(createTarget({ port: 2222 }), '/srv/project')).toEqual({ - ok: true, - url: 'ssh://ada@builder.example.com:2222/srv/project' - }) - }) - - it('uses only the alias for config-backed targets so local ssh config supplies user and port', () => { - expect( - resolveZedSshUrl( - createTarget({ source: 'ssh-config', configHost: ' devbox ', port: 2222 }), - '/srv/project' - ) - ).toEqual({ ok: true, url: 'ssh://devbox/srv/project' }) - }) - - it('percent-encodes user and path segments that would otherwise end the URL early', () => { - expect( - resolveZedSshUrl( - createTarget({ username: 'ada@corp', host: '2001:db8::1' }), - '/home/Ada Lovelace/a#b?c%d' - ) - ).toEqual({ - ok: true, - url: 'ssh://ada%40corp@[2001:db8::1]:22/home/Ada%20Lovelace/a%23b%3Fc%25d' - }) - }) - - it('asks for an ssh config alias when a manual host needs settings the URL cannot carry', () => { - expect( - resolveZedSshUrl(createTarget({ identityFile: '~/.ssh/builder', port: 2222 }), '/srv') - ).toEqual({ ok: false, reason: 'ssh-alias-required', host: 'builder.example.com', port: 2222 }) - expect(resolveZedSshUrl(createTarget({ jumpHost: 'bastion' }), '/srv')).toMatchObject({ - reason: 'ssh-alias-required' - }) - }) - - it('refuses hosts and paths Zed cannot round-trip', () => { - expect( - resolveZedSshUrl(createTarget({ source: 'ssh-config', configHost: 'team devbox' }), '/srv') - ).toEqual({ ok: false, reason: 'remote-editor-unsupported' }) - expect(resolveZedSshUrl(createTarget({ host: '-oProxyCommand=x' }), '/srv')).toMatchObject({ - reason: 'ssh-alias-required' - }) - expect(resolveZedSshUrl(createTarget(), 'C:\\Users\\ada\\project')).toEqual({ - ok: false, - reason: 'remote-editor-unsupported' - }) - expect(resolveZedSshUrl(createTarget({ host: 'bad\nhost' }), '/srv')).toEqual({ - ok: false, - reason: 'ssh-target-invalid' - }) - }) -}) diff --git a/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts b/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts deleted file mode 100644 index a3f2e379c2b..00000000000 --- a/src/main/ssh/host-server/ssh-host-server-telemetry.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { eventSchemas } from '../../../shared/telemetry-event-registry' - -vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) - -const { track } = await import('../../telemetry/client') -const { hostServerFailure, hostServerRefusal, trackSshHostServerEvent } = - await import('./ssh-host-server-telemetry') - -const linuxGlibc = { os: 'linux', arch: 'x64', libc: 'glibc' } as const - -function tracked() { - const call = vi.mocked(track).mock.calls.at(-1) - if (!call) { - throw new Error('nothing was tracked') - } - return call -} - -function expectSchemaValid(): unknown { - const [name, props] = tracked() - expect(eventSchemas[name].safeParse(props).success).toBe(true) - return props -} - -describe('ssh host server telemetry', () => { - beforeEach(() => { - vi.mocked(track).mockReset() - }) - - it('narrows any unrecognised code, so free text never reaches an event', () => { - expect(hostServerRefusal('orcad_migration_/home/me/secret')).toBe('other') - expect(hostServerFailure('Error: ssh me@host.example failed')).toBe('other') - expect(hostServerFailure('orcad_activation_no_readiness')).toBe('activation_no_readiness') - expect(hostServerFailure('unsupported_host')).toBe('unsupported_host') - - trackSshHostServerEvent( - { - kind: 'decided', - outcome: 'relay', - reason: 'host.example.com', - refusal: null, - recorded: false, - durationMs: 0 - }, - linuxGlibc - ) - expect(expectSchemaValid()).toMatchObject({ reason: 'other' }) - }) -}) diff --git a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts b/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts deleted file mode 100644 index fd22247584a..00000000000 --- a/src/main/ssh/legacy-relay/endpoints/ssh-relay-endpoint-runtime.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseRelayDaemonRuntimes } from './ssh-relay-endpoint-runtime' - -describe('the runtime each relay daemon runs on', () => { - it('reads a pinned and a legacy host-Node daemon from their argv', () => { - const pinned = '/home/dev/.orca-remote/node-runtimes/v24/bin/node' - const runtimes = parseRelayDaemonRuntimes( - [ - `${pinned} relay.js --detached --grace-time 0 --sock-path /home/dev/.orca-remote/relay-2/relay-a.sock --credential-file x`, - '/usr/local/bin/node relay.js --detached --grace-time 300 --sock-path /home/dev/.orca-remote/relay-1/relay-b.sock --log-file y', - // A bridge client is not a daemon, and a line without a socket is skipped. - '/usr/bin/node relay.js --connect --sock-path /home/dev/.orca-remote/relay-1/relay-b.sock', - 'grep -F relay.js --detached' - ].join('\n') - ) - expect([...runtimes]).toEqual([ - ['/home/dev/.orca-remote/relay-2/relay-a.sock', pinned], - ['/home/dev/.orca-remote/relay-1/relay-b.sock', '/usr/local/bin/node'] - ]) - }) -}) diff --git a/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts index 5d6552b4ae4..7d4f44b9cfc 100644 --- a/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts +++ b/src/main/ssh/legacy-relay/handshake/ssh-relay-sentinel-copy-budget.test.ts @@ -4,24 +4,23 @@ import { expect, it, vi } from 'vitest' import { RELAY_SENTINEL } from '../../protocol/relay-handshake' import { waitForSentinel } from './ssh-relay-sentinel' -it.each(Array.from({ length: RELAY_SENTINEL.length + 1 }, (_, i) => i))( - 'preserves the marker and binary payload when split at byte %i', - async (split) => { - const channel = Object.assign(new EventEmitter(), { - stderr: new EventEmitter(), - stdin: { write: vi.fn(() => true) }, - close: vi.fn() - }) - const pending = waitForSentinel(channel as unknown as ClientChannel) - const marker = Buffer.from(RELAY_SENTINEL) - const payload = Buffer.from([0, 255, 128, 10, 13, 1]) - channel.emit('data', Buffer.alloc(63 * 1024, 120)) - channel.emit('data', marker.subarray(0, split)) - channel.emit('data', Buffer.concat([marker.subarray(split), payload])) - const transport = await pending - const received: Buffer[] = [] - transport.onData((bytes) => received.push(bytes)) - expect(Buffer.concat(received)).toEqual(payload) - expect(channel.close).not.toHaveBeenCalled() - } -) +it('preserves binary payload across a split ready marker', async () => { + const split = 12 + const channel = Object.assign(new EventEmitter(), { + stderr: new EventEmitter(), + stdin: { write: vi.fn(() => true) }, + close: vi.fn() + }) + // SAFETY: This fake implements the channel members used during this handshake and subscription. + const pending = waitForSentinel(channel as unknown as ClientChannel) + const marker = Buffer.from(RELAY_SENTINEL) + const payload = Buffer.from([0, 255, 128, 10, 13, 1]) + channel.emit('data', Buffer.alloc(63 * 1024, 120)) + channel.emit('data', marker.subarray(0, split)) + channel.emit('data', Buffer.concat([marker.subarray(split), payload])) + const transport = await pending + const received: Buffer[] = [] + transport.onData((bytes) => received.push(bytes)) + expect(Buffer.concat(received)).toEqual(payload) + expect(channel.close).not.toHaveBeenCalled() +}) diff --git a/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts b/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts index 36edace9928..d72e4dbc362 100644 --- a/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts +++ b/src/main/ssh/remote-exec/ssh-remote-windows-command-line-limit.test.ts @@ -21,15 +21,4 @@ describe('Windows remote command line limit', () => { expect(gunzipSync(Buffer.from(payload, 'base64')).toString('utf-8')).toBe(script) expect(bootstrap).toContain('Invoke-Expression $OrcaScriptText') }) - - it('refuses a script no encoding can fit instead of letting cmd.exe reject it', () => { - let seed = 12345 - const incompressible = Array.from({ length: 60_000 }, () => { - seed = (seed * 1103515245 + 12345) % 2147483648 - return String.fromCharCode(97 + (seed % 26)) - }).join('') - expect(() => powerShellCommand(`Write-Output '${incompressible}'`)).toThrow( - /Orca budgets 8000 for a line sshd hands to cmd\.exe/u - ) - }) }) diff --git a/src/main/ssh/remote-host/ssh-remote-platform.test.ts b/src/main/ssh/remote-host/ssh-remote-platform.test.ts index b55b6138f88..1012133be81 100644 --- a/src/main/ssh/remote-host/ssh-remote-platform.test.ts +++ b/src/main/ssh/remote-host/ssh-remote-platform.test.ts @@ -25,10 +25,6 @@ describe('assertSafeRemotePathSegment', () => { 'trailing.', 'trailing ', 'NUL', - 'con.txt', - 'CONIN$', - 'CLOCK$.log', - 'COM1.log', 'LPT¹' ])('rejects Win32-special segment %j', (segment) => { expect(() => assertSafeRemotePathSegment(segment, 'windows')).toThrow( diff --git a/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts index c0cb84358c0..6eaa56a3050 100644 --- a/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts +++ b/src/main/ssh/system-transport/file-transfer/system-ssh-sftp-path.test.ts @@ -12,18 +12,10 @@ describe('toSftpRemotePath', () => { expect(toSftpRemotePath('C:/Users/dev/f.bin')).toBe('/C:/Users/dev/f.bin') }) - it('converts the separators Orca stores paths with', () => { - expect(toSftpRemotePath('C:\\Users\\dev\\f.bin')).toBe('/C:/Users/dev/f.bin') - }) - it('declines a UNC path rather than guessing where it lands', () => { // A guess here writes real bytes to the wrong place; declining falls back to another transport. expect(() => toSftpRemotePath('//server/share/f.bin')).toThrow(UnsupportedSftpPathError) }) - - it('declines a relative path, which would resolve against the session start directory', () => { - expect(() => toSftpRemotePath('Users/dev/f.bin')).toThrow(UnsupportedSftpPathError) - }) }) describe('quoteSftpBatchArgument', () => { @@ -32,10 +24,6 @@ describe('quoteSftpBatchArgument', () => { expect(quoteSftpBatchArgument('C:\\src\\f.bin')).toBe('"C:\\\\src\\\\f.bin"') }) - it('keeps a path with spaces as one argument', () => { - expect(quoteSftpBatchArgument('/tmp/two words.bin')).toBe('"/tmp/two words.bin"') - }) - it('escapes an embedded quote, which would otherwise end the argument early', () => { expect(quoteSftpBatchArgument('/tmp/dq".bin')).toBe('"/tmp/dq\\".bin"') }) @@ -43,8 +31,4 @@ describe('quoteSftpBatchArgument', () => { it('refuses a line break, which would split one batch command into two', () => { expect(() => quoteSftpBatchArgument('/tmp/a\nrm -rf b')).toThrow(UnsupportedSftpPathError) }) - - it('refuses a NUL, which truncates the argument', () => { - expect(() => quoteSftpBatchArgument('/tmp/a\0b')).toThrow(UnsupportedSftpPathError) - }) }) From b5e38ad9c6fd7595e40e9af1ef58ee25db99614a Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:23:03 -0800 Subject: [PATCH 4/9] refactor: organize agent hook installation and server owners (#39969) * refactor: organize agent hook installation and server owners * refactor: align hook mock registries and packaged entries --- config/build-plugins/cli-main-entry-names.ts | 2 +- config/flaky-test-pattern-baseline.txt | 36 +- config/knip.json | 2 +- config/main-sync-spawn-baseline.txt | 2 +- config/packaged-runtime-node-modules.cjs | 2 +- .../process-host-direct-import-baseline.txt | 8 +- config/reliability-gates.jsonc | 10 +- .../scripts/ci/sharding/ci-shard-timings.json | 248 ++++++------ ...lectron-builder-runtime-resources.test.mjs | 16 +- .../wsl-hook-relay-reattach-benchmark.mjs | 4 +- .../vitest-node-runtime-files.mjs | 2 +- .../source-routing/pr-code-change-scope.mjs | 4 +- .../source-routing/pr-package-test-paths.mjs | 12 +- src/cli/handlers/agent-hooks.test.ts | 2 +- src/cli/handlers/agent-hooks.ts | 4 +- src/cli/runtime-client-deferral.test.ts | 2 +- .../offline-admission-commands.test.ts | 2 +- ...cp-structured-background-task-stop.test.ts | 2 +- .../acp-structured-child-work.test.ts | 2 +- .../acp-structured-child-work.test-support.ts | 2 +- src/main/agent-hooks/README.md | 10 +- .../branch-rename-failure-output.ts | 2 +- .../first-work-branch-rename-wsl-move.test.ts | 20 +- .../first-work-branch-rename.test.ts | 28 +- .../first-work-branch-rename.ts | 38 +- .../first-work-folder-rename.ts | 12 +- .../first-work-generation-backoff.ts | 2 +- .../first-work-generation-target.ts | 4 +- .../first-work-rename-runtime.ts | 18 +- .../first-work-structured-session-rename.ts | 2 +- .../first-work-workspace-title-rename.ts | 4 +- .../first-work-branch-rename-test-harness.ts | 10 +- .../agent-home-login-shell.ts | 0 .../commands/managed-hook-command-matching.ts | 119 ++++++ .../commands}/posix-hook-command.ts | 4 +- .../commands}/runtime-home-hook-command.ts | 4 +- .../managed-hook-command-env.test-fixture.ts | 0 .../windows-git-bash-path.test-fixture.ts | 0 .../windows-native-hook-exe.test-fixture.ts | 2 +- ...windows-powershell-warm-up.test-fixture.ts | 2 +- .../windows-agent-hook-post-command.ts | 42 ++ .../windows-batch-hook-launcher.test.ts | 6 +- .../windows-cmd-hook-command-unicode.test.ts | 18 +- .../windows-direct-cmd-hook-command.ts | 0 .../commands}/windows-hook-command.ts | 4 +- .../windows-hook-payload-delivery.test.ts | 39 +- .../windows-native-hook-exe-hosts.test.ts | 14 +- .../windows-native-hook-executable.ts | 0 .../windows-powershell-hook-launcher.test.ts | 0 .../windows-powershell-hook-launcher.ts | 0 .../configuration/hook-config-schema.ts | 40 ++ .../configuration}/hook-config-write-path.ts | 0 .../configuration}/hooks-json-read.ts | 4 +- .../configuration/hooks-json-remote.ts | 69 ++++ .../configuration}/hooks-json-write-async.ts | 0 .../configuration/hooks-json-write.ts | 71 ++++ .../managed-hooks-json-events.ts | 2 +- .../managed-toml-ownership.test.ts | 0 .../configuration}/managed-toml-ownership.ts | 0 .../{ => installation}/install-telemetry.ts | 6 +- .../local-agent-cli-presence.test.ts | 4 +- .../local-agent-cli-presence.ts | 18 +- .../managed-hook-install-lock.test.ts | 0 .../locking}/managed-hook-install-lock.ts | 0 .../locking}/managed-hook-lock-claims.ts | 0 .../locking}/managed-hook-lock-records.ts | 0 .../locking}/managed-hook-owner-identity.ts | 0 .../managed-agent-hook-controls.test.ts | 2 +- .../managed-agent-hook-controls.ts | 12 +- .../managed-agent-hook-registry.ts | 48 +-- .../managed-agent-hook-startup.ts | 0 .../managed-hook-detection-commands.ts | 14 +- .../opencode-plugin-settings.ts | 4 +- .../remote-managed-hook-installers.ts | 46 +-- .../remote/hook-sftp-operations.ts} | 176 +-------- .../remote/hook-text-files-remote.ts | 75 ++++ .../agent-hook-memory-sftp.test-fixture.ts | 0 ...aged-hook-local-filesystem.test-fixture.ts | 0 .../scripts}/claude-background-job-guard.ts | 0 .../scripts}/cursor-replay-guard.test.ts | 6 +- .../scripts}/cursor-replay-guard.ts | 0 .../scripts}/grok-replay-guard.test.ts | 6 +- .../scripts}/grok-replay-guard.ts | 0 .../scripts}/hook-post-command.ts | 6 +- .../scripts}/hook-process-capture.test.ts | 6 +- .../scripts}/hook-process-capture.ts | 0 .../scripts}/hook-script-outside-orca.test.ts | 2 +- .../scripts}/hook-stdin-contract.ts | 0 .../scripts}/locked-executable-rename.test.ts | 0 .../scripts}/locked-executable-rename.ts | 2 +- .../scripts/managed-hook-script-path.ts | 7 + ...ed-hook-script-refresh-main-thread.test.ts | 4 +- .../managed-hook-script-refresh.test.ts | 8 +- .../scripts}/managed-hook-script-refresh.ts | 4 +- .../scripts/managed-hook-script-write.ts | 67 ++++ .../managed-hook-stdin-lifecycle.test.ts | 50 +-- .../scripts}/managed-hook-timeout.test.ts | 6 +- .../scripts/managed-script-write-remote.ts | 44 +++ .../posix-hook-json-stdin-reader.test.ts | 0 .../vendor-hook-delivery.test-fixture.ts | 0 .../testing/installer-contract.test.ts} | 14 +- src/main/agent-hooks/installer-utils.ts | 359 ------------------ .../agent-transition-detector.test.ts | 8 +- .../agent-transition-detector.ts | 12 +- .../local-hook-root-evidence.ts | 8 +- .../local-tmux-managed-pty.test.ts | 2 +- .../local-tmux-managed-pty.ts | 6 +- .../migration-unsupported-pty-state.ts | 2 +- .../restored-status-dead-terminal-sweep.ts | 14 +- .../{ => runtime}/agent-hook-runtime-deps.ts | 8 +- .../{ => runtime}/agent-status-pane-index.ts | 2 +- .../hook-status-session-tabs-republish.ts | 2 +- src/main/agent-hooks/server.ts | 29 -- ...agent-presence.ts => agent-hook-server.ts} | 28 +- .../agent-hooks/server/server-lifecycle.ts | 2 +- .../server-accepted-reply.test.ts | 14 +- .../server-closed-tab-suppression.test.ts | 12 +- .../server-omp-retired-ingress.test.ts | 8 +- .../server-omp-retirement-ack.test.ts | 8 +- .../authority}/server-pane-authority.test.ts | 6 +- .../server-reminted-pane-key.test.ts | 8 +- ...removed-worktree-foreign-authority.test.ts | 6 +- .../server-removed-worktree-status.test.ts | 6 +- .../server-retired-pane-new-turn.test.ts | 10 +- .../http}/server-claude-statusline.test.ts | 4 +- .../server-endpoint-file-lifecycle.test.ts | 6 +- .../http}/server-hook-http-ingest.test.ts | 8 +- .../http}/server-startup-lifecycle.test.ts | 21 +- .../server-startup-prompt-control.test.ts | 8 +- .../server-transport-interference.test.ts | 8 +- .../server-ai-vault-liveness.test.ts | 4 +- ...er-claude-resume-record-continuity.test.ts | 6 +- ...server-claude-session-continuation.test.ts | 12 +- .../server-copilot-resume-identity.test.ts | 12 +- .../server-hermes-resume-identity.test.ts | 16 +- .../server-hook-session-binding.test.ts | 40 +- .../server-launch-resume-identity.test.ts | 8 +- .../server-nested-agent-boundaries.test.ts | 10 +- .../server-nested-agent-consumers.test.ts | 10 +- .../server-nested-agent-model.test.ts | 8 +- .../server-nested-same-provider-owner.test.ts | 12 +- ...server-opencode-writer-observation.test.ts | 18 +- .../terminal-handle-row-identity.test.ts | 8 +- .../claude-cancel-capture.test-fixture.ts | 4 +- ...terminal-interrupt-capture.test-fixture.ts | 4 +- .../server-claude-helper-kill.test.ts | 18 +- .../server-claude-helper-recovery.test.ts | 20 +- .../server-claude-terminal-interrupt.test.ts | 10 +- .../server-interrupt-inference-guards.test.ts | 8 +- ...r-interrupt-inference-resurrection.test.ts | 8 +- .../server-relayed-claude-cancel.test.ts | 10 +- .../server-main-agent-turn-verdicts.test.ts | 8 +- .../main-agent}/server-turn-ended-at.test.ts | 8 +- .../server-turn-started-at.test.ts | 8 +- .../server-provider-normalization.test.ts} | 8 +- ...-claude-child-permission-lifecycle.test.ts | 8 +- ...er-claude-permission-batch-release.test.ts | 8 +- ...ver-claude-permission-tool-failure.test.ts | 8 +- ...erver-claude-permission-visibility.test.ts | 8 +- ...-last-status-child-held-main-agent.test.ts | 8 +- ...r-last-status-hydrate-confirmation.test.ts | 8 +- ...ver-last-status-hydrate-validation.test.ts | 10 +- .../server-last-status-lead-boundary.test.ts | 8 +- ...server-last-status-main-agent-fact.test.ts | 8 +- ...rver-last-status-restored-children.test.ts | 8 +- .../server-last-status-write.test.ts | 8 +- .../server-observation-provenance.test.ts | 8 +- .../server-restored-agent-status.test.ts | 4 +- .../server-status-persist-nonblocking.test.ts | 10 +- .../server-status-persist-throttle.test.ts | 12 +- .../presence}/server-agent-presence.test.ts | 10 +- .../server-hook-root-acquisition.test.ts | 12 +- .../server-hook-root-provenance.test.ts | 16 +- .../presence}/server-hook-root-replay.test.ts | 18 +- .../server-hook-root.test-fixtures.ts | 12 +- .../server-http-owner-probe-lifecycle.test.ts | 12 +- .../server-idle-process-owner.test.ts | 16 +- .../amp}/server-amp-normalization.test.ts | 8 +- ...ntigravity-background-command-hold.test.ts | 8 +- ...server-antigravity-resume-identity.test.ts | 14 +- .../server-claude-blocked-prompt.test.ts | 10 +- ...rver-claude-config-dir-observation.test.ts | 14 +- .../server-claude-normalization.test.ts | 8 +- .../codex}/server-codex-capacity.test.ts | 6 +- .../server-codex-interrupt-hook.test.ts | 8 +- .../server-codex-review-turn-end.test.ts | 8 +- .../codex}/server-codex-side-thread.test.ts | 4 +- .../server-codex-subagent-transcript.test.ts | 4 +- .../server-codex-turn-interruption.test.ts | 4 +- .../server-cursor-normalization.test.ts | 8 +- .../server-grok-background-status.test.ts | 12 +- .../grok}/server-grok-cancel.test.ts | 12 +- .../grok}/server-grok-discovery.test.ts | 6 +- .../server-muse-session-log-poll.test.ts | 6 +- .../server-opencode-tui-identity.test.ts | 6 +- .../server-status-listener-fanout.test.ts | 8 +- .../ended-process-reconciliation.test.ts | 6 +- ...erver-ingest-remote-codex-question.test.ts | 14 +- ...ver-ingest-remote-codex-transcript.test.ts | 20 +- .../server-ingest-remote.test.ts | 10 +- ...r-relayed-claude-permission-replay.test.ts | 16 +- .../server-replay-evidence-clock.test.ts | 14 +- .../{ => server/testing/replay}/spool.test.ts | 12 +- .../testing}/server.test-fixtures.ts | 4 +- ...rver-ingest-structured-state-clock.test.ts | 8 +- .../server-ingest-structured-status.test.ts | 18 +- ...server-structured-canonical-status.test.ts | 14 +- ...er-claude-owed-notification-expiry.test.ts | 12 +- ...erver-claude-task-wakeup-lifecycle.test.ts | 21 +- .../server-prompt-sent-telemetry.test.ts | 8 +- .../server-ingest-terminal-status.test.ts | 8 +- .../server-process-lifetime-status.test.ts | 4 +- .../tmux}/server-tmux-canonical.test.ts | 14 +- .../testing/tmux}/server-tmux-wire.test.ts | 10 +- .../server-agent-tool-plugin-hooks.test.ts | 14 +- .../server-transcript-result-retry.test.ts} | 8 +- .../agent-tool-call-reader.ts | 14 +- .../agent-tool-plugin-hooks.test.ts | 6 +- .../agent-tool-plugin-hooks.ts | 6 +- ...ssh-agent-hook-interrupt-reconciliation.ts | 6 +- .../wsl-hook-relay-live.integration.test.ts | 8 +- .../wsl-agent-plugin-readiness.ts | 12 +- .../wsl-bridge-daemon-sessions.ts | 6 +- .../wsl-bridge-pty-presence.ts | 0 .../wsl-guest-plugin-install.test.ts | 2 +- .../wsl-guest-plugin-install.ts | 12 +- .../{ => wsl-relay}/wsl-hook-fs-adapter.ts | 10 +- .../{ => wsl-relay}/wsl-hook-relay-deps.ts | 38 +- .../wsl-hook-relay-guest-install.ts | 12 +- .../wsl-hook-relay-idle-stop.test.ts | 0 .../wsl-hook-relay-idle-stop.ts | 0 .../{ => wsl-relay}/wsl-hook-relay-launch.ts | 20 +- .../{ => wsl-relay}/wsl-hook-relay-link.ts | 8 +- .../wsl-hook-relay-manager.test.ts | 14 +- .../{ => wsl-relay}/wsl-hook-relay-manager.ts | 10 +- .../wsl-hook-relay-reattach.test.ts | 0 .../wsl-hook-relay-reattach.ts | 2 +- .../wsl-hook-relay-recovery.test.ts | 4 +- .../wsl-hook-relay-recovery.ts | 0 .../wsl-hook-relay-sentinel.test.ts | 2 +- .../wsl-hook-relay-sentinel.ts | 4 +- .../wsl-hook-relay-state-key.ts | 0 .../wsl-hook-relay-state-machine.ts | 6 +- .../{ => wsl-relay}/wsl-hook-relay-state.ts | 2 +- .../wsl-opencode-settings-lifetime.test.ts | 14 +- .../wsl-opencode-settings.test.ts | 12 +- src/main/amp/hook-service.ts | 2 +- src/main/antigravity/hook-script.ts | 6 +- src/main/antigravity/hook-service.test.ts | 2 +- src/main/antigravity/hook-service.ts | 26 +- src/main/antigravity/hooks-json-bundle.ts | 10 +- .../antigravity/posix-hook-invocation.test.ts | 2 +- .../antigravity/windows-hook-json-post.ts | 2 +- .../agent-view/agent-view-binding-plan.ts | 4 +- .../claude/agent-view/agent-view-config.ts | 4 +- .../claude/agent-view/agent-view-install.ts | 15 +- .../agent-view/agent-view-keybindings.ts | 4 +- .../claude/agent-view/agent-view-plugin.ts | 5 +- .../claude-background-wake-retention.test.ts | 2 +- ...hild-work-producer-harness.test-fixture.ts | 2 +- .../claude/claude-hook-decision-script.ts | 2 +- .../claude/claude-hook-event-versions.test.ts | 2 +- src/main/claude/claude-managed-hook-events.ts | 2 +- .../claude/claude-status-line-windows.test.ts | 2 +- ...claude-subagent-permission-request.test.ts | 2 +- src/main/claude/hook-script.ts | 14 +- src/main/claude/hook-service.test.ts | 3 +- src/main/claude/hook-service.ts | 18 +- src/main/claude/hook-settings.ts | 24 +- src/main/claude/statusline-install.ts | 3 +- src/main/claude/statusline-script.ts | 8 +- .../theme-sync/claude-code-theme-ownership.ts | 9 +- .../theme-sync/claude-code-theme-sync.ts | 4 +- src/main/claude/windows-hook-files.test.ts | 5 +- src/main/claude/windows-hook-files.ts | 12 +- .../windows-native-hook-registration.test.ts | 25 +- src/main/cli/appimage-generation-lease.ts | 5 +- .../service-hook-trust-test-fixtures.ts | 3 +- ...hared-state-survives-a-failed-read.test.ts | 2 +- .../index/codex-state-db-backfill-recovery.ts | 4 +- .../definitions/codex-hook-definition.ts | 8 +- .../hooks/definitions/codex-hook-identity.ts | 5 +- .../hooks/definitions/codex-hook-script.ts | 8 +- .../installation/codex-hook-local-install.ts | 10 +- .../codex-hook-local-maintenance.ts | 4 +- .../installation/codex-hook-remote-install.ts | 16 +- .../codex-hook-service-implementation.ts | 4 +- .../installation/codex-hook-wsl-runtime.ts | 17 +- .../hook-service-legacy-cleanup.test.ts | 4 +- .../hook-service-managed-codex-hashes.test.ts | 21 +- .../installation/hook-service-test-harness.ts | 2 +- .../hook-service-wsl-runtime.test.ts | 4 +- .../codex-account-home-hook.test.ts | 2 +- .../codex-hook-legacy-cleanup.ts | 12 +- .../codex-hook-reconcile.test.ts | 4 +- .../hooks/reconciliation/codex-hook-status.ts | 4 +- ...codex-hook-sweep-per-agent-opt-out.test.ts | 4 +- .../codex-hook-toggle-off-wins.test.ts | 2 +- .../codex-real-home-hook-entries.test.ts | 25 +- .../codex-real-home-hook-entry-plan.ts | 10 +- .../codex-real-home-hook-install.ts | 14 +- .../codex-real-home-hook-sweep.ts | 12 +- .../codex-real-home-hooks-json.ts | 9 +- .../hooks/codex-hook-approval-first-write.ts | 3 +- .../trust/hooks/codex-hook-orca-approvals.ts | 4 +- .../trust/hooks/codex-hook-system-trust.ts | 2 +- .../trust/hooks/codex-hook-trust-cleanup.ts | 2 +- .../trust/hooks/codex-hook-trust-memo.ts | 2 +- .../trust/hooks/codex-hook-user-mirroring.ts | 5 +- .../hooks/codex-user-hook-trust-moves.test.ts | 5 +- .../hooks/codex-user-hook-trust-moves.ts | 5 +- .../codex/trust/hooks/hook-trust-promotion.ts | 8 +- .../trust/toml/config-toml-hook-trust-read.ts | 2 +- .../config-toml-trust-loadability.test.ts | 57 ++- .../command-code-managed-script.ts | 6 +- src/main/command-code/hook-service.ts | 28 +- .../copilot-managed-hook-definitions.ts | 12 +- src/main/copilot/copilot-managed-script.ts | 10 +- .../copilot/copilot-remote-hook-install.ts | 14 +- src/main/copilot/hook-service.test.ts | 3 +- src/main/copilot/hook-service.ts | 12 +- src/main/cursor/hook-script.ts | 16 +- src/main/cursor/hook-service.test.ts | 2 +- src/main/cursor/hook-service.ts | 24 +- .../identity/daemon-incarnation-evidence.ts | 2 +- .../identity/daemon-ready-identity.ts | 2 +- .../linux/daemon-host-image.ts | 2 +- .../daemon/health/daemon-liveness-report.ts | 2 +- src/main/devin/hook-config-json.ts | 3 +- src/main/devin/hook-service.ts | 22 +- src/main/devin/hook-settings.ts | 14 +- src/main/droid/hook-service.ts | 34 +- src/main/dsh/hook-service.ts | 18 +- src/main/dsh/hook-settings.ts | 12 +- .../external-conversation-cancel.test.ts | 2 +- .../external-conversation-events.ts | 2 +- .../external-conversation-links.ts | 2 +- .../external-conversation-prompts.test.ts | 2 +- ...external-conversation-seam.test-fixture.ts | 2 +- .../external-conversation-seam.ts | 2 +- .../external-conversation-start.ts | 2 +- .../external-conversation.test-fixture.ts | 2 +- .../external-conversations-install.ts | 2 +- src/main/gemini/hook-service.ts | 34 +- src/main/grok/grok-hook-backup-cleanup.ts | 3 +- src/main/grok/grok-hook-config-cleanup.ts | 6 +- src/main/grok/grok-hook-config-file.ts | 4 +- src/main/grok/grok-hook-config.ts | 8 +- src/main/grok/grok-hook-remote-install.ts | 8 +- src/main/grok/grok-hook-script.ts | 9 +- src/main/grok/hook-service.ts | 10 +- src/main/grok/windows-grok-hook-script.ts | 4 +- .../grok/windows-hook-launcher-chain.test.ts | 3 +- .../hermes-config-comment-boundaries.test.ts | 2 +- .../hermes-config-remote-adapter.test.ts | 2 +- src/main/hermes/hermes-home-filesystem.ts | 7 +- src/main/hermes/hook-service.ts | 5 +- src/main/ipc/agent-hooks.test.ts | 10 +- src/main/ipc/agent-hooks.ts | 4 +- src/main/ipc/agent-pane-authority-ipc.ts | 4 +- .../ipc/agent-pane-retirement-ipc.test.ts | 4 +- src/main/ipc/agent-status-row-teardown-ipc.ts | 4 +- .../pty-claude-agent-view-readiness.test.ts | 4 +- ...ty-degraded-fallback-single-ingest.test.ts | 4 +- .../pty-spawn-saved-resume-admission.test.ts | 4 +- src/main/ipc/pty/host-env/assembly.ts | 4 +- .../opencode-hook-installation.test.ts | 4 +- .../pty/host-env/saved-resume-admission.ts | 2 +- .../ipc/pty/pane/complete-pane-adoption.ts | 4 +- .../ipc/pty/pane/resume-launch-identity.ts | 2 +- src/main/ipc/pty/provider/bind-listeners.ts | 2 +- src/main/ipc/pty/provider/local-configure.ts | 2 +- src/main/ipc/pty/provider/state-cleanup.ts | 4 +- .../pty/pty-closed-pane-spawn-refusal.test.ts | 4 +- .../pty-controller-ownership-routing.test.ts | 4 +- .../pty-controller-spawn-admission.test.ts | 4 +- .../pty-daemon-spawn-session-identity.test.ts | 6 +- .../pty-pane-reservation-settlement.test.ts | 4 +- .../ipc/pty/pty-pane-restart-replace.test.ts | 4 +- .../ipc/pty/pty-runtime-kill-and-exit.test.ts | 4 +- ...ty-runtime-ssh-binding-persistence.test.ts | 4 +- ...pty-session-liveness-and-ownership.test.ts | 4 +- .../ipc/pty/pty-spawn-cwd-fallback.test.ts | 4 +- src/main/ipc/pty/pty-ssh-stop-verdict.test.ts | 4 +- .../ipc/pty/pty-write-ipc-validation.test.ts | 4 +- src/main/ipc/pty/spawn-begin.ts | 2 +- src/main/ipc/pty/spawn-commit-publication.ts | 4 +- src/main/ipc/pty/spawn-execute.ts | 4 +- src/main/ipc/pty/spawn-host-env.ts | 2 +- .../ipc/settings-delayed-response.test.ts | 2 +- src/main/ipc/settings-ipc-test-fixture.ts | 2 +- src/main/ipc/settings.ts | 4 +- ...itative-local-worktree-metadata-pruning.ts | 2 +- .../listing/register-host-catalog-handlers.ts | 2 +- .../register-worktree-metadata-handlers.ts | 2 +- .../removal/worktree-removal-ownership.ts | 6 +- src/main/ipc/wsl/wsl-move-driver-wiring.ts | 2 +- src/main/jcode/hook-config.ts | 2 +- src/main/jcode/hook-service.ts | 18 +- src/main/kimi/hook-service.ts | 24 +- src/main/kimi/kimi-hook-config-toml.ts | 4 +- src/main/kiro/hook-service.test.ts | 4 +- src/main/kiro/hook-service.ts | 20 +- src/main/kiro/hook-settings.ts | 14 +- src/main/kiro/standalone-hook-settings.ts | 2 +- src/main/kiro/standalone-hooks.ts | 10 +- src/main/muse/hook-config-json.ts | 2 +- src/main/muse/hook-service.ts | 18 +- src/main/muse/hook-settings.ts | 14 +- ...ssion-claude-stop-contract-test-fixture.ts | 2 +- ...tured-agent-session-status-reentry.test.ts | 2 +- src/main/native-chat/native-chat-open-wake.ts | 2 +- src/main/opencode/opencode-pty-launch.ts | 2 +- .../opencode-startup-prompt-owner.test.ts | 2 +- .../opencode/opencode-startup-prompt-owner.ts | 2 +- .../opencode-status-plugin-startup-refresh.ts | 2 +- .../opencode-wsl-probe-environment.test.ts | 4 +- .../orcad/orcad-daemon-teardown-fixture.ts | 2 +- src/main/orcad/orcad-entry.ts | 8 +- src/main/orcad/orcad-managed-agent-hooks.ts | 10 +- src/main/orcad/orcad-process-start-time.ts | 2 +- .../profile-state-caller-cancellation.spec.ts | 4 +- src/main/persistence/loading-store/store.ts | 4 +- .../workspace-session-snapshot-publication.ts | 2 +- .../wsl-move-gate-stub-agent-hooks.test.ts | 2 +- ...rsistence-loading-store-extraction.test.ts | 2 +- .../pane-alias-normalization.ts | 2 +- ...workspace-pane-normalization-index.test.ts | 2 +- .../workspace-pane-normalization.ts | 2 +- .../duplicate-pty-pane-repair.test.ts | 2 +- ...istence-pane-alias-selective-saves.test.ts | 4 +- ...ersistence-pane-identity-migration.test.ts | 4 +- .../plugins/hooks/plugin-hook-participants.ts | 2 +- src/main/qoder/real-cli.test.ts | 2 +- src/main/qoder/workspace-trust.ts | 6 +- ...tructured-codex-child-work-runtime.test.ts | 2 +- .../structured-chat-naming-runtime.test.ts | 2 +- .../naming/structured-chat-naming-runtime.ts | 2 +- ...agent-session-saved-roster.test-support.ts | 4 +- .../structured-child-records-switch.test.ts | 2 +- ...ntime-client-agent-launch-rollback.test.ts | 2 +- ...t-agent-launch-settings-durability.test.ts | 2 +- .../settings/runtime-client-settings.ts | 4 +- .../orca-runtime-agent-transitions.ts | 2 +- .../orca-runtime-test-mocks/setup.spec.ts | 2 +- .../worktree-ps-agent-wait.spec.ts | 2 +- .../worktree-ps-structured-host.spec.ts | 2 +- ...tration-codex-real-pty.integration.test.ts | 2 +- ...pencode-finished-session-authority.test.ts | 2 +- .../release/worker-auto-release-activity.ts | 2 +- .../turn-stops/terminal-worker-turn-stops.ts | 2 +- .../turn-stops/worker-turn-stops.test.ts | 2 +- .../terminal-agent-phone-push.ts | 2 +- .../notifications/terminal-agent-turn-news.ts | 2 +- .../fleet-status-observed-identity.test.ts | 2 +- .../terminal-claude-agent-view-method.ts | 2 +- .../terminal-send-question-answered.ts | 2 +- ...-legacy-takeover-current-authority.test.ts | 2 +- .../rpc/terminal-claude-agent-view.test.ts | 2 +- .../runtime-mobile-session-projection.ts | 2 +- .../orca-runtime-sidebar-temporal.ts | 2 +- .../orca-runtime-sort-stamps.test.ts | 2 +- ...ca-runtime-windowless-terminal-activity.ts | 2 +- ...a-runtime-workspace-activity-facts.test.ts | 2 +- .../orca-runtime-workspace-unread.test.ts | 2 +- .../sidebar-inputs/sort-stamp-records.ts | 2 +- .../sort-stamps-producer.test.ts | 4 +- .../sidebar-inputs/sort-stamps-producer.ts | 2 +- .../sidebar-inputs/terminal-use-producer.ts | 2 +- .../workspace-activity-facts-producer.test.ts | 2 +- .../workspace-activity-facts-producer.ts | 2 +- .../agent-status-store-wiring.test-fixture.ts | 6 +- .../identity/exported-pane-key-follow.test.ts | 2 +- .../identity/exported-pane-key-follow.ts | 2 +- .../identity/moved-pane-owner-rekey.ts | 2 +- .../input/terminal-agent-prompt-submit.ts | 2 +- .../output/terminal-buffer-operations.ts | 2 +- .../persisted-surfaces/crew-operations.ts | 2 +- ...untime-worktree-agent-rows-verdict.test.ts | 2 +- ...ree-structured-agent-rows-liveness.test.ts | 2 +- .../workspace-process-listing.ts | 4 +- .../agent-hooks-uninstall-preflight.ts | 3 +- src/main/startup/branch-rename-hook.ts | 6 +- .../startup/main-process-account-services.ts | 2 +- src/main/startup/main-process-observers.ts | 4 +- src/main/startup/main-process-plugins.ts | 2 +- src/main/startup/main-process-pty-startup.ts | 8 +- .../main-process-quit-pending-writer.test.ts | 8 +- .../main-process-quit-update-veto.test.ts | 6 +- src/main/startup/main-process-quit.ts | 6 +- .../startup/main-process-ready-foundation.ts | 4 +- .../main-process-ready-identity-write.test.ts | 2 +- .../startup/main-process-ready-runtime.ts | 4 +- .../startup/main-process-runtime-service.ts | 4 +- src/main/startup/main-window-agent-status.ts | 4 +- src/main/startup/synthetic-title-runtime.ts | 2 +- .../agent-session-transition-recorder.test.ts | 16 +- ...worktree-create-first-work-test-harness.ts | 9 +- src/main/zcode/hook-config-json.ts | 2 +- src/main/zcode/hook-service.ts | 22 +- src/main/zcode/hook-settings.ts | 18 +- src/wsl-guest/agent-hook-integration.test.ts | 2 +- ...gent-hook-server-codex-side-thread.test.ts | 2 +- ...ook-server-codex-turn-interruption.test.ts | 2 +- ...agent-launch-preferences-work.unit.test.ts | 2 +- ...nch-settings-hook-bookkeeping.unit.test.ts | 2 +- .../e2e/nested-agent-idle-owner.unit.test.ts | 8 +- .../omp-retired-host-renderer.unit.test.ts | 2 +- ...lder-project-runtime-contract.unit.test.ts | 4 +- .../pty-spawn-cwd-folder-owner.unit.test.ts | 4 +- .../terminal-agent-pane-launch.unit.test.ts | 4 +- 511 files changed, 2482 insertions(+), 2359 deletions(-) rename src/main/agent-hooks/{ => first-work}/branch-rename-failure-output.ts (95%) rename src/main/agent-hooks/{ => first-work}/first-work-branch-rename-wsl-move.test.ts (89%) rename src/main/agent-hooks/{ => first-work}/first-work-branch-rename.test.ts (93%) rename src/main/agent-hooks/{ => first-work}/first-work-branch-rename.ts (90%) rename src/main/agent-hooks/{ => first-work}/first-work-folder-rename.ts (84%) rename src/main/agent-hooks/{ => first-work}/first-work-generation-backoff.ts (94%) rename src/main/agent-hooks/{ => first-work}/first-work-generation-target.ts (76%) rename src/main/agent-hooks/{ => first-work}/first-work-rename-runtime.ts (88%) rename src/main/agent-hooks/{ => first-work}/first-work-structured-session-rename.ts (88%) rename src/main/agent-hooks/{ => first-work}/first-work-workspace-title-rename.ts (94%) rename src/main/agent-hooks/{ => first-work/testing}/first-work-branch-rename-test-harness.ts (89%) rename src/main/agent-hooks/{ => installation}/agent-home-login-shell.ts (100%) create mode 100644 src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts rename src/main/agent-hooks/{ => installation/commands}/posix-hook-command.ts (87%) rename src/main/agent-hooks/{ => installation/commands}/runtime-home-hook-command.ts (97%) rename src/main/agent-hooks/{ => installation/commands/testing}/managed-hook-command-env.test-fixture.ts (100%) rename src/main/agent-hooks/{ => installation/commands/testing}/windows-git-bash-path.test-fixture.ts (100%) rename src/main/agent-hooks/{ => installation/commands/testing}/windows-native-hook-exe.test-fixture.ts (93%) rename src/main/agent-hooks/{ => installation/commands/testing}/windows-powershell-warm-up.test-fixture.ts (90%) create mode 100644 src/main/agent-hooks/installation/commands/windows-agent-hook-post-command.ts rename src/main/agent-hooks/{ => installation/commands}/windows-batch-hook-launcher.test.ts (93%) rename src/main/agent-hooks/{ => installation/commands}/windows-cmd-hook-command-unicode.test.ts (93%) rename src/main/agent-hooks/{ => installation/commands}/windows-direct-cmd-hook-command.ts (100%) rename src/main/agent-hooks/{ => installation/commands}/windows-hook-command.ts (90%) rename src/main/agent-hooks/{ => installation/commands}/windows-hook-payload-delivery.test.ts (93%) rename src/main/agent-hooks/{ => installation/commands}/windows-native-hook-exe-hosts.test.ts (95%) rename src/main/agent-hooks/{ => installation/commands}/windows-native-hook-executable.ts (100%) rename src/main/agent-hooks/{ => installation/commands}/windows-powershell-hook-launcher.test.ts (100%) rename src/main/agent-hooks/{ => installation/commands}/windows-powershell-hook-launcher.ts (100%) create mode 100644 src/main/agent-hooks/installation/configuration/hook-config-schema.ts rename src/main/agent-hooks/{ => installation/configuration}/hook-config-write-path.ts (100%) rename src/main/agent-hooks/{ => installation/configuration}/hooks-json-read.ts (90%) create mode 100644 src/main/agent-hooks/installation/configuration/hooks-json-remote.ts rename src/main/agent-hooks/{ => installation/configuration}/hooks-json-write-async.ts (100%) create mode 100644 src/main/agent-hooks/installation/configuration/hooks-json-write.ts rename src/main/agent-hooks/{ => installation/configuration}/managed-hooks-json-events.ts (94%) rename src/main/agent-hooks/{ => installation/configuration}/managed-toml-ownership.test.ts (100%) rename src/main/agent-hooks/{ => installation/configuration}/managed-toml-ownership.ts (100%) rename src/main/agent-hooks/{ => installation}/install-telemetry.ts (63%) rename src/main/agent-hooks/{ => installation}/local-agent-cli-presence.test.ts (94%) rename src/main/agent-hooks/{ => installation}/local-agent-cli-presence.ts (91%) rename src/main/agent-hooks/{ => installation/locking}/managed-hook-install-lock.test.ts (100%) rename src/main/agent-hooks/{ => installation/locking}/managed-hook-install-lock.ts (100%) rename src/main/agent-hooks/{ => installation/locking}/managed-hook-lock-claims.ts (100%) rename src/main/agent-hooks/{ => installation/locking}/managed-hook-lock-records.ts (100%) rename src/main/agent-hooks/{ => installation/locking}/managed-hook-owner-identity.ts (100%) rename src/main/agent-hooks/{ => installation}/managed-agent-hook-controls.test.ts (99%) rename src/main/agent-hooks/{ => installation}/managed-agent-hook-controls.ts (94%) rename src/main/agent-hooks/{ => installation}/managed-agent-hook-registry.ts (79%) rename src/main/agent-hooks/{ => installation}/managed-agent-hook-startup.ts (100%) rename src/main/agent-hooks/{ => installation}/managed-hook-detection-commands.ts (77%) rename src/main/agent-hooks/{ => installation}/opencode-plugin-settings.ts (85%) rename src/main/agent-hooks/{ => installation}/remote-managed-hook-installers.ts (77%) rename src/main/agent-hooks/{installer-utils-remote.ts => installation/remote/hook-sftp-operations.ts} (51%) create mode 100644 src/main/agent-hooks/installation/remote/hook-text-files-remote.ts rename src/main/agent-hooks/{ => installation/remote/testing}/agent-hook-memory-sftp.test-fixture.ts (100%) rename src/main/agent-hooks/{ => installation/remote/testing}/managed-hook-local-filesystem.test-fixture.ts (100%) rename src/main/agent-hooks/{ => installation/scripts}/claude-background-job-guard.ts (100%) rename src/main/agent-hooks/{ => installation/scripts}/cursor-replay-guard.test.ts (77%) rename src/main/agent-hooks/{ => installation/scripts}/cursor-replay-guard.ts (100%) rename src/main/agent-hooks/{ => installation/scripts}/grok-replay-guard.test.ts (85%) rename src/main/agent-hooks/{ => installation/scripts}/grok-replay-guard.ts (100%) rename src/main/agent-hooks/{ => installation/scripts}/hook-post-command.ts (94%) rename src/main/agent-hooks/{ => installation/scripts}/hook-process-capture.test.ts (85%) rename src/main/agent-hooks/{ => installation/scripts}/hook-process-capture.ts (100%) rename src/main/agent-hooks/{ => installation/scripts}/hook-script-outside-orca.test.ts (98%) rename src/main/agent-hooks/{ => installation/scripts}/hook-stdin-contract.ts (100%) rename src/main/agent-hooks/{ => installation/scripts}/locked-executable-rename.test.ts (100%) rename src/main/agent-hooks/{ => installation/scripts}/locked-executable-rename.ts (96%) create mode 100644 src/main/agent-hooks/installation/scripts/managed-hook-script-path.ts rename src/main/agent-hooks/{ => installation/scripts}/managed-hook-script-refresh-main-thread.test.ts (96%) rename src/main/agent-hooks/{ => installation/scripts}/managed-hook-script-refresh.test.ts (94%) rename src/main/agent-hooks/{ => installation/scripts}/managed-hook-script-refresh.ts (95%) create mode 100644 src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts rename src/main/agent-hooks/{ => installation/scripts}/managed-hook-stdin-lifecycle.test.ts (86%) rename src/main/agent-hooks/{ => installation/scripts}/managed-hook-timeout.test.ts (95%) create mode 100644 src/main/agent-hooks/installation/scripts/managed-script-write-remote.ts rename src/main/agent-hooks/{ => installation/scripts}/posix-hook-json-stdin-reader.test.ts (100%) rename src/main/agent-hooks/{ => installation/scripts/testing}/vendor-hook-delivery.test-fixture.ts (100%) rename src/main/agent-hooks/{installer-utils.test.ts => installation/testing/installer-contract.test.ts} (95%) delete mode 100644 src/main/agent-hooks/installer-utils.ts rename src/main/agent-hooks/{ => observations}/agent-transition-detector.test.ts (94%) rename src/main/agent-hooks/{ => observations}/agent-transition-detector.ts (94%) rename src/main/agent-hooks/{ => observations}/local-hook-root-evidence.ts (69%) rename src/main/agent-hooks/{ => observations}/local-tmux-managed-pty.test.ts (96%) rename src/main/agent-hooks/{ => observations}/local-tmux-managed-pty.ts (94%) rename src/main/agent-hooks/{ => observations}/migration-unsupported-pty-state.ts (95%) rename src/main/agent-hooks/{ => observations}/restored-status-dead-terminal-sweep.ts (90%) rename src/main/agent-hooks/{ => runtime}/agent-hook-runtime-deps.ts (89%) rename src/main/agent-hooks/{ => runtime}/agent-status-pane-index.ts (82%) rename src/main/agent-hooks/{ => runtime}/hook-status-session-tabs-republish.ts (96%) delete mode 100644 src/main/agent-hooks/server.ts rename src/main/agent-hooks/server/{server-agent-presence.ts => agent-hook-server.ts} (88%) rename src/main/agent-hooks/{ => server/testing/accepted-replies}/server-accepted-reply.test.ts (88%) rename src/main/agent-hooks/{ => server/testing/authority}/server-closed-tab-suppression.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/authority}/server-omp-retired-ingress.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/authority}/server-omp-retirement-ack.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/authority}/server-pane-authority.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/authority}/server-reminted-pane-key.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/authority}/server-removed-worktree-foreign-authority.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/authority}/server-removed-worktree-status.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/authority}/server-retired-pane-new-turn.test.ts (91%) rename src/main/agent-hooks/{ => server/testing/http}/server-claude-statusline.test.ts (93%) rename src/main/agent-hooks/{ => server/testing/http}/server-endpoint-file-lifecycle.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/http}/server-hook-http-ingest.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/http}/server-startup-lifecycle.test.ts (85%) rename src/main/agent-hooks/{ => server/testing/http}/server-startup-prompt-control.test.ts (91%) rename src/main/agent-hooks/{ => server/testing/http}/server-transport-interference.test.ts (93%) rename src/main/agent-hooks/{ => server/testing/identity}/server-ai-vault-liveness.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/identity}/server-claude-resume-record-continuity.test.ts (93%) rename src/main/agent-hooks/{ => server/testing/identity}/server-claude-session-continuation.test.ts (88%) rename src/main/agent-hooks/{ => server/testing/identity}/server-copilot-resume-identity.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/identity}/server-hermes-resume-identity.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/identity}/server-hook-session-binding.test.ts (88%) rename src/main/agent-hooks/{ => server/testing/identity}/server-launch-resume-identity.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/identity}/server-nested-agent-boundaries.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/identity}/server-nested-agent-consumers.test.ts (83%) rename src/main/agent-hooks/{ => server/testing/identity}/server-nested-agent-model.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/identity}/server-nested-same-provider-owner.test.ts (83%) rename src/main/agent-hooks/{ => server/testing/identity}/server-opencode-writer-observation.test.ts (86%) rename src/main/agent-hooks/{ => server/testing/identity}/terminal-handle-row-identity.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/interruptions}/claude-cancel-capture.test-fixture.ts (91%) rename src/main/agent-hooks/{ => server/testing/interruptions}/claude-terminal-interrupt-capture.test-fixture.ts (86%) rename src/main/agent-hooks/{ => server/testing/interruptions}/server-claude-helper-kill.test.ts (91%) rename src/main/agent-hooks/{ => server/testing/interruptions}/server-claude-helper-recovery.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/interruptions}/server-claude-terminal-interrupt.test.ts (94%) rename src/main/agent-hooks/{ => server/testing/interruptions}/server-interrupt-inference-guards.test.ts (98%) rename src/main/agent-hooks/{ => server/testing/interruptions}/server-interrupt-inference-resurrection.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/interruptions}/server-relayed-claude-cancel.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/main-agent}/server-main-agent-turn-verdicts.test.ts (94%) rename src/main/agent-hooks/{ => server/testing/main-agent}/server-turn-ended-at.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/main-agent}/server-turn-started-at.test.ts (94%) rename src/main/agent-hooks/{server-codex-normalization.test.ts => server/testing/normalization/server-provider-normalization.test.ts} (96%) rename src/main/agent-hooks/{ => server/testing/permissions}/server-claude-child-permission-lifecycle.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/permissions}/server-claude-permission-batch-release.test.ts (98%) rename src/main/agent-hooks/{ => server/testing/permissions}/server-claude-permission-tool-failure.test.ts (93%) rename src/main/agent-hooks/{ => server/testing/permissions}/server-claude-permission-visibility.test.ts (98%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-last-status-child-held-main-agent.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-last-status-hydrate-confirmation.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-last-status-hydrate-validation.test.ts (94%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-last-status-lead-boundary.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-last-status-main-agent-fact.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-last-status-restored-children.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-last-status-write.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-observation-provenance.test.ts (86%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-restored-agent-status.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-status-persist-nonblocking.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/persistence}/server-status-persist-throttle.test.ts (93%) rename src/main/agent-hooks/{ => server/testing/presence}/server-agent-presence.test.ts (91%) rename src/main/agent-hooks/{ => server/testing/presence}/server-hook-root-acquisition.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/presence}/server-hook-root-provenance.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/presence}/server-hook-root-replay.test.ts (94%) rename src/main/agent-hooks/{ => server/testing/presence}/server-hook-root.test-fixtures.ts (93%) rename src/main/agent-hooks/{ => server/testing/presence}/server-http-owner-probe-lifecycle.test.ts (88%) rename src/main/agent-hooks/{ => server/testing/presence}/server-idle-process-owner.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/providers/amp}/server-amp-normalization.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/providers/antigravity}/server-antigravity-background-command-hold.test.ts (87%) rename src/main/agent-hooks/{ => server/testing/providers/antigravity}/server-antigravity-resume-identity.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/providers/claude}/server-claude-blocked-prompt.test.ts (88%) rename src/main/agent-hooks/{ => server/testing/providers/claude}/server-claude-config-dir-observation.test.ts (74%) rename src/main/agent-hooks/{ => server/testing/providers/claude}/server-claude-normalization.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/providers/codex}/server-codex-capacity.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/providers/codex}/server-codex-interrupt-hook.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/providers/codex}/server-codex-review-turn-end.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/providers/codex}/server-codex-side-thread.test.ts (98%) rename src/main/agent-hooks/{ => server/testing/providers/codex}/server-codex-subagent-transcript.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/providers/codex}/server-codex-turn-interruption.test.ts (97%) rename src/main/agent-hooks/{ => server/testing/providers/cursor}/server-cursor-normalization.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/providers/grok}/server-grok-background-status.test.ts (94%) rename src/main/agent-hooks/{ => server/testing/providers/grok}/server-grok-cancel.test.ts (83%) rename src/main/agent-hooks/{ => server/testing/providers/grok}/server-grok-discovery.test.ts (94%) rename src/main/agent-hooks/{ => server/testing/providers/muse}/server-muse-session-log-poll.test.ts (95%) rename src/main/agent-hooks/{ => server/testing/providers/opencode}/server-opencode-tui-identity.test.ts (88%) rename src/main/agent-hooks/{ => server/testing/publication}/server-status-listener-fanout.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/reconciliation}/ended-process-reconciliation.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/remote-ingress}/server-ingest-remote-codex-question.test.ts (87%) rename src/main/agent-hooks/{ => server/testing/remote-ingress}/server-ingest-remote-codex-transcript.test.ts (89%) rename src/main/agent-hooks/{ => server/testing/remote-ingress}/server-ingest-remote.test.ts (79%) rename src/main/agent-hooks/{ => server/testing/replay}/server-relayed-claude-permission-replay.test.ts (90%) rename src/main/agent-hooks/{ => server/testing/replay}/server-replay-evidence-clock.test.ts (86%) rename src/main/agent-hooks/{ => server/testing/replay}/spool.test.ts (96%) rename src/main/agent-hooks/{ => server/testing}/server.test-fixtures.ts (93%) rename src/main/agent-hooks/{ => server/testing/structured-ingress}/server-ingest-structured-state-clock.test.ts (89%) rename src/main/agent-hooks/{ => server/testing/structured-ingress}/server-ingest-structured-status.test.ts (92%) rename src/main/agent-hooks/{ => server/testing/structured-ingress}/server-structured-canonical-status.test.ts (89%) rename src/main/agent-hooks/{ => server/testing/task-wakeup}/server-claude-owed-notification-expiry.test.ts (89%) rename src/main/agent-hooks/{ => server/testing/task-wakeup}/server-claude-task-wakeup-lifecycle.test.ts (94%) rename src/main/agent-hooks/{ => server/testing/telemetry}/server-prompt-sent-telemetry.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/terminal-ingress}/server-ingest-terminal-status.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/terminal-ingress}/server-process-lifetime-status.test.ts (96%) rename src/main/agent-hooks/{ => server/testing/tmux}/server-tmux-canonical.test.ts (86%) rename src/main/agent-hooks/{ => server/testing/tmux}/server-tmux-wire.test.ts (89%) rename src/main/agent-hooks/{ => server/testing/tool-events}/server-agent-tool-plugin-hooks.test.ts (78%) rename src/main/agent-hooks/{server-copilot-normalization.test.ts => server/testing/transcripts/server-transcript-result-retry.test.ts} (96%) rename src/main/agent-hooks/{ => tool-events}/agent-tool-call-reader.ts (88%) rename src/main/agent-hooks/{ => tool-events}/agent-tool-plugin-hooks.test.ts (90%) rename src/main/agent-hooks/{ => tool-events}/agent-tool-plugin-hooks.ts (94%) rename src/main/agent-hooks/{ => transport}/ssh-agent-hook-interrupt-reconciliation.ts (72%) rename src/main/agent-hooks/{ => wsl-relay/testing}/wsl-hook-relay-live.integration.test.ts (95%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-agent-plugin-readiness.ts (82%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-bridge-daemon-sessions.ts (89%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-bridge-pty-presence.ts (100%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-guest-plugin-install.test.ts (94%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-guest-plugin-install.ts (83%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-fs-adapter.ts (92%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-deps.ts (82%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-guest-install.ts (92%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-idle-stop.test.ts (100%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-idle-stop.ts (100%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-launch.ts (91%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-link.ts (88%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-manager.test.ts (97%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-manager.ts (95%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-reattach.test.ts (100%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-reattach.ts (89%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-recovery.test.ts (95%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-recovery.ts (100%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-sentinel.test.ts (98%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-sentinel.ts (96%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-state-key.ts (100%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-state-machine.ts (95%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-hook-relay-state.ts (93%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-opencode-settings-lifetime.test.ts (94%) rename src/main/agent-hooks/{ => wsl-relay}/wsl-opencode-settings.test.ts (90%) diff --git a/config/build-plugins/cli-main-entry-names.ts b/config/build-plugins/cli-main-entry-names.ts index d0b3c431611..2668645fa61 100644 --- a/config/build-plugins/cli-main-entry-names.ts +++ b/config/build-plugins/cli-main-entry-names.ts @@ -1,6 +1,6 @@ // The CLI loads these paths after electron-vite replaces out/main. export const CLI_MAIN_ENTRY_NAMES = [ - 'agent-hooks/managed-agent-hook-controls', + 'agent-hooks/installation/managed-agent-hook-controls', 'gitlab/project-ref-parser', 'orca-profiles/profile-index-store', 'claude-accounts/keychain', diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 4cfe7b8a073..c39dde57a3f 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -2,7 +2,7 @@ # This is a RATCHET: counts may only go DOWN. Run `pnpm lint:ast-grep:flaky-tests` to list them. # Prune after a fix: pnpm check:flaky-test-pattern-ratchet --prune 1 test-no-in-test-import-actual:src/cli/runtime/launch-serve-replaced-app-restart.test.ts -1 test-no-in-test-import-actual:src/main/agent-hooks/server-status-persist-nonblocking.test.ts +1 test-no-in-test-import-actual:src/main/agent-hooks/server/testing/persistence/server-status-persist-nonblocking.test.ts 1 test-no-in-test-import-actual:src/main/bitbucket/credential-connection.test.ts 4 test-no-in-test-import-actual:src/main/bitbucket/credential-store.test.ts 1 test-no-in-test-import-actual:src/main/bitbucket/status-no-decrypt.test.ts @@ -148,12 +148,12 @@ 1 test-no-polling-loop:tests/e2e/workspace-sleep-in-main.spec.ts 2 test-no-polling-loop:tests/e2e/worktree-card-downward-drag.spec.ts 1 test-no-real-time-wait:mobile/src/terminal/terminal-webview-tap-routing.test.ts -1 test-no-real-time-wait:src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts -3 test-no-real-time-wait:src/main/agent-hooks/server-copilot-normalization.test.ts -2 test-no-real-time-wait:src/main/agent-hooks/server-transport-interference.test.ts -1 test-no-real-time-wait:src/main/agent-hooks/server-turn-ended-at.test.ts -1 test-no-real-time-wait:src/main/agent-hooks/server-turn-started-at.test.ts -5 test-no-real-time-wait:src/main/agent-hooks/wsl-hook-relay-manager.test.ts +1 test-no-real-time-wait:src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts +3 test-no-real-time-wait:src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts +2 test-no-real-time-wait:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts +1 test-no-real-time-wait:src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts +1 test-no-real-time-wait:src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts +5 test-no-real-time-wait:src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts 1 test-no-real-time-wait:src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process.test.ts 2 test-no-real-time-wait:src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-scan-scope.test.ts 1 test-no-real-time-wait:src/main/antigravity/windows-hook-json-post.test.ts @@ -468,14 +468,14 @@ 4 test-no-wall-clock:src/cli/runtime/serve-bundle-park.test.ts 5 test-no-wall-clock:src/cli/runtime/serve-pid1-init-reaper.test.ts 1 test-no-wall-clock:src/cli/runtime/status-caller.test.ts -2 test-no-wall-clock:src/main/agent-hooks/managed-hook-timeout.test.ts -2 test-no-wall-clock:src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts -1 test-no-wall-clock:src/main/agent-hooks/server-codex-capacity.test.ts -1 test-no-wall-clock:src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts -3 test-no-wall-clock:src/main/agent-hooks/server-ingest-structured-status.test.ts -4 test-no-wall-clock:src/main/agent-hooks/server-launch-resume-identity.test.ts -5 test-no-wall-clock:src/main/agent-hooks/spool.test.ts -2 test-no-wall-clock:src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts +2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts +2 test-no-wall-clock:src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts +1 test-no-wall-clock:src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts +1 test-no-wall-clock:src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts +3 test-no-wall-clock:src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts +4 test-no-wall-clock:src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts +5 test-no-wall-clock:src/main/agent-hooks/server/testing/replay/spool.test.ts +2 test-no-wall-clock:src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts 2 test-no-wall-clock:src/main/ai-vault-search/session-search-indexer.test.ts 1 test-no-wall-clock:src/main/ai-vault/parse-cache/session-parse-cache-preview-upgrade.test.ts 1 test-no-wall-clock:src/main/ai-vault/scanners/copilot/session-scanner-copilot-cache-upgrade.test.ts @@ -704,9 +704,9 @@ 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 2 test-timeout-needs-reason:src/main/acp/journal/acp-structured-broken-stream.test.ts -4 test-timeout-needs-reason:src/main/agent-hooks/server-transport-interference.test.ts -1 test-timeout-needs-reason:src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts -1 test-timeout-needs-reason:src/main/agent-hooks/wsl-hook-relay-manager.test.ts +4 test-timeout-needs-reason:src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts +1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts +1 test-timeout-needs-reason:src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts 1 test-timeout-needs-reason:src/main/ai-vault/parse-cache/session-parse-cache-large-scan.test.ts 1 test-timeout-needs-reason:src/main/antigravity/native-macos-credentials.real.test.ts 1 test-timeout-needs-reason:src/main/antigravity/posix-hook-invocation.test.ts diff --git a/config/knip.json b/config/knip.json index 516010bb4d9..c9fe794f998 100644 --- a/config/knip.json +++ b/config/knip.json @@ -15,7 +15,7 @@ "src/main/worker-thread-child-process/worker-thread-child-process-entry.ts", "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/managed-agent-hook-controls.ts", + "src/main/agent-hooks/installation/managed-agent-hook-controls.ts", "src/main/claude-accounts/keychain.ts", "src/renderer/src/main.tsx", "src/renderer/src/popout.tsx", diff --git a/config/main-sync-spawn-baseline.txt b/config/main-sync-spawn-baseline.txt index e18069dc0c4..c9d69eefb60 100644 --- a/config/main-sync-spawn-baseline.txt +++ b/config/main-sync-spawn-baseline.txt @@ -5,7 +5,7 @@ # Some entries run in the daemon or orcad process, or are test harnesses outside the test-path # conventions. This is a RATCHET: counts may only go DOWN. # Prune after removing launches: pnpm check:main-sync-spawn-ratchet --prune -1 src/main/agent-hooks/installer-utils.ts +1 src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts 1 src/main/browser/network/egress/browser-route-egress-electron-launch.ts 1 src/main/browser/routing/partitions/browser-route-partition-binding-store.ts 1 src/main/claude-accounts/runtime-auth-service.ts diff --git a/config/packaged-runtime-node-modules.cjs b/config/packaged-runtime-node-modules.cjs index 34fa9e68a09..a5a9ed3bb33 100644 --- a/config/packaged-runtime-node-modules.cjs +++ b/config/packaged-runtime-node-modules.cjs @@ -76,7 +76,7 @@ const ELECTRON_ARCHITECTURE_BY_ENUM = { const PACKAGED_NATIVE_ARCHITECTURES = new Set(['ia32', 'x64', 'arm', 'arm64']) const PACKAGED_MAIN_REQUIRED_FILES = [ 'out/main/index.js', - 'out/main/agent-hooks/managed-agent-hook-controls.js' + 'out/main/agent-hooks/installation/managed-agent-hook-controls.js' ] const PACKAGED_MAIN_SOURCE_RE = /^out\/main\/.+\.js$/ const TYPE_DECLARATION_ARTIFACT_RE = /\.d\.(?:c|m)?ts(?:\.map)?$/ diff --git a/config/process-host-direct-import-baseline.txt b/config/process-host-direct-import-baseline.txt index 1ef89fe5148..1799f04c983 100644 --- a/config/process-host-direct-import-baseline.txt +++ b/config/process-host-direct-import-baseline.txt @@ -4,10 +4,10 @@ src/cli/handlers/core.ts src/cli/handlers/interactive-login-interruption.ts src/cli/runtime/launch.ts -src/main/agent-hooks/managed-hook-owner-identity.ts -src/main/agent-hooks/wsl-hook-relay-link.ts -src/main/agent-hooks/wsl-hook-relay-manager.ts -src/main/agent-hooks/wsl-hook-relay-sentinel.ts +src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts +src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts +src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts +src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts src/main/ai-vault/scan-service/session-scanner-service-client-state.ts src/main/ai-vault/scan-service/session-scanner-service-client.ts src/main/ai-vault/scan-service/session-scanner-service-spawn.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 46dcb8613d5..0f0ddbb7a88 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -6389,7 +6389,7 @@ "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", + "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks.test.ts src/main/ipc/agent-pane-authority-ownership.test.ts src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts src/main/persistence/terminal-topology/persistence-pty-binding-reconciliation.test.ts src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts src/renderer/src/store/terminals/terminal-pane-detach-agent-identity.test.ts src/renderer/src/store/terminals/terminal-tab-retirement-store.test.ts tests/e2e/completed-worker-retirement-resume.unit.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/sessions/testing/session.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts", "pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1", "pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1", @@ -6400,7 +6400,7 @@ "testFiles": [ "src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", - "src/main/agent-hooks/server-pane-authority.test.ts", + "src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts", "src/main/ipc/agent-hooks.test.ts", "src/main/ipc/agent-pane-authority-ownership.test.ts", "src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts", @@ -9253,7 +9253,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts src/wsl-guest/dispatcher-client-writer.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/protocol/ssh-multiplexer-transport-writer.test.ts src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts --reporter=dot" + "pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts --reporter=dot" ], "testFiles": [ "src/main/runtime/construction/orca-runtime.test.ts", @@ -9263,7 +9263,7 @@ "src/main/ssh/protocol/ssh-channel-multiplexer.test.ts", "src/main/ssh/protocol/ssh-channel-multiplexer-backpressure.test.ts", "src/wsl-guest/dispatcher-client-writer.test.ts", - "src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts" + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts" ], "assertionRefs": [ { @@ -9304,7 +9304,7 @@ ] }, { - "file": "src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts", + "file": "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts", "assertions": [ "WSL stdin forwards write(false), callback settlement, and drain without claiming a live WSL topology" ] diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 3e115b3f7cd..9c25664e63d 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -529,131 +529,131 @@ "src/main/persistence/preferences/active-view-preference.test.ts": 61, "src/main/providers/accounts/agent-auth-restart-preservation.test.ts": 55, "src/main/agent-launch/preflight/agent-cli-version-probe.test.ts": 72, - "src/main/agent-hooks/agent-tool-plugin-hooks.test.ts": 202, - "src/main/agent-hooks/agent-transition-detector.test.ts": 666, - "src/main/agent-hooks/cursor-replay-guard.test.ts": 403, - "src/main/agent-hooks/ended-process-reconciliation.test.ts": 775, - "src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts": 831, - "src/main/agent-hooks/first-work-branch-rename.test.ts": 857, - "src/main/agent-hooks/grok-replay-guard.test.ts": 533, - "src/main/agent-hooks/hook-process-capture.test.ts": 118, - "src/main/agent-hooks/hook-script-outside-orca.test.ts": 171, - "src/main/agent-hooks/installer-utils.test.ts": 264, - "src/main/agent-hooks/local-agent-cli-presence.test.ts": 153, - "src/main/agent-hooks/local-tmux-managed-pty.test.ts": 50, - "src/main/agent-hooks/locked-executable-rename.test.ts": 69, - "src/main/agent-hooks/managed-agent-hook-controls.test.ts": 250, - "src/main/agent-hooks/managed-hook-install-lock.test.ts": 226, - "src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts": 567, - "src/main/agent-hooks/managed-hook-script-refresh.test.ts": 1637, - "src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts": 1989, - "src/main/agent-hooks/managed-hook-timeout.test.ts": 2987, - "src/main/agent-hooks/managed-toml-ownership.test.ts": 52, - "src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts": 3479, - "src/main/agent-hooks/server-agent-presence.test.ts": 1257, - "src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts": 717, - "src/main/agent-hooks/server-ai-vault-liveness.test.ts": 643, - "src/main/agent-hooks/server-amp-normalization.test.ts": 607, - "src/main/agent-hooks/server-antigravity-resume-identity.test.ts": 820, - "src/main/agent-hooks/server-claude-blocked-prompt.test.ts": 681, - "src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts": 681, - "src/main/agent-hooks/server-claude-config-dir-observation.test.ts": 696, - "src/main/agent-hooks/server-claude-helper-kill.test.ts": 10279, - "src/main/agent-hooks/server-claude-helper-recovery.test.ts": 34523, - "src/main/agent-hooks/server-claude-normalization.test.ts": 683, - "src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts": 877, - "src/main/agent-hooks/server-claude-permission-tool-failure.test.ts": 674, - "src/main/agent-hooks/server-claude-permission-visibility.test.ts": 765, - "src/main/agent-hooks/server-claude-session-continuation.test.ts": 675, - "src/main/agent-hooks/server-claude-statusline.test.ts": 679, - "src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts": 5451, - "src/main/agent-hooks/server-claude-terminal-interrupt.test.ts": 802, - "src/main/agent-hooks/server-closed-tab-suppression.test.ts": 895, - "src/main/agent-hooks/server-codex-capacity.test.ts": 671, - "src/main/agent-hooks/server-codex-interrupt-hook.test.ts": 679, - "src/main/agent-hooks/server-codex-normalization.test.ts": 741, - "src/main/agent-hooks/server-codex-review-turn-end.test.ts": 860, - "src/main/agent-hooks/server-codex-side-thread.test.ts": 847, - "src/main/agent-hooks/server-codex-subagent-transcript.test.ts": 706, - "src/main/agent-hooks/server-codex-turn-interruption.test.ts": 716, - "src/main/agent-hooks/server-copilot-normalization.test.ts": 1125, - "src/main/agent-hooks/server-copilot-resume-identity.test.ts": 729, - "src/main/agent-hooks/server-cursor-normalization.test.ts": 645, - "src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts": 801, - "src/main/agent-hooks/server-grok-background-status.test.ts": 723, - "src/main/agent-hooks/server-grok-cancel.test.ts": 692, - "src/main/agent-hooks/server-grok-discovery.test.ts": 723, - "src/main/agent-hooks/server-hermes-resume-identity.test.ts": 941, - "src/main/agent-hooks/server-hook-http-ingest.test.ts": 719, - "src/main/agent-hooks/server-hook-session-binding.test.ts": 2674, - "src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts": 1088, - "src/main/agent-hooks/server-idle-process-owner.test.ts": 1014, - "src/main/agent-hooks/server-ingest-remote-codex-question.test.ts": 656, - "src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts": 647, - "src/main/agent-hooks/server-ingest-remote.test.ts": 653, - "src/main/agent-hooks/server-ingest-structured-state-clock.test.ts": 723, - "src/main/agent-hooks/server-ingest-structured-status.test.ts": 697, - "src/main/agent-hooks/server-ingest-terminal-status.test.ts": 673, - "src/main/agent-hooks/server-interrupt-inference-guards.test.ts": 685, - "src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts": 759, - "src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts": 937, - "src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts": 713, - "src/main/agent-hooks/server-last-status-hydrate-validation.test.ts": 737, - "src/main/agent-hooks/server-last-status-lead-boundary.test.ts": 768, - "src/main/agent-hooks/server-last-status-main-agent-fact.test.ts": 813, - "src/main/agent-hooks/server-last-status-restored-children.test.ts": 818, - "src/main/agent-hooks/server-last-status-write.test.ts": 745, - "src/main/agent-hooks/server-launch-resume-identity.test.ts": 735, - "src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts": 1716, - "src/main/agent-hooks/server-muse-session-log-poll.test.ts": 2772, - "src/main/agent-hooks/server-nested-agent-boundaries.test.ts": 657, - "src/main/agent-hooks/server-nested-agent-consumers.test.ts": 660, - "src/main/agent-hooks/server-nested-agent-model.test.ts": 665, - "src/main/agent-hooks/server-nested-same-provider-owner.test.ts": 708, - "src/main/agent-hooks/server-observation-provenance.test.ts": 672, - "src/main/agent-hooks/server-omp-retired-ingress.test.ts": 641, - "src/main/agent-hooks/server-omp-retirement-ack.test.ts": 676, - "src/main/agent-hooks/server-opencode-tui-identity.test.ts": 843, - "src/main/agent-hooks/server-opencode-writer-observation.test.ts": 681, - "src/main/agent-hooks/server-pane-authority.test.ts": 762, - "src/main/agent-hooks/server-process-lifetime-status.test.ts": 852, - "src/main/agent-hooks/server-prompt-sent-telemetry.test.ts": 701, - "src/main/agent-hooks/server-relayed-claude-cancel.test.ts": 901, - "src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts": 758, - "src/main/agent-hooks/server-reminted-pane-key.test.ts": 688, - "src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts": 764, - "src/main/agent-hooks/server-removed-worktree-status.test.ts": 687, - "src/main/agent-hooks/server-replay-evidence-clock.test.ts": 643, - "src/main/agent-hooks/server-restored-agent-status.test.ts": 694, - "src/main/agent-hooks/server-retired-pane-new-turn.test.ts": 666, - "src/main/agent-hooks/server-startup-lifecycle.test.ts": 718, - "src/main/agent-hooks/server-startup-prompt-control.test.ts": 697, - "src/main/agent-hooks/server-status-listener-fanout.test.ts": 783, - "src/main/agent-hooks/server-status-persist-nonblocking.test.ts": 697, - "src/main/agent-hooks/server-status-persist-throttle.test.ts": 860, - "src/main/agent-hooks/server-structured-canonical-status.test.ts": 765, - "src/main/agent-hooks/server-tmux-canonical.test.ts": 739, - "src/main/agent-hooks/server-tmux-wire.test.ts": 564, - "src/main/agent-hooks/server-transport-interference.test.ts": 1814, - "src/main/agent-hooks/server-turn-ended-at.test.ts": 990, - "src/main/agent-hooks/server-turn-started-at.test.ts": 898, + "src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts": 202, + "src/main/agent-hooks/observations/agent-transition-detector.test.ts": 666, + "src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts": 403, + "src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts": 775, + "src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts": 831, + "src/main/agent-hooks/first-work/first-work-branch-rename.test.ts": 857, + "src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts": 533, + "src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts": 118, + "src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts": 171, + "src/main/agent-hooks/installation/testing/installer-contract.test.ts": 264, + "src/main/agent-hooks/installation/local-agent-cli-presence.test.ts": 153, + "src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts": 50, + "src/main/agent-hooks/installation/scripts/locked-executable-rename.test.ts": 69, + "src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts": 250, + "src/main/agent-hooks/installation/locking/managed-hook-install-lock.test.ts": 226, + "src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts": 567, + "src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts": 1637, + "src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts": 1989, + "src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts": 2987, + "src/main/agent-hooks/installation/configuration/managed-toml-ownership.test.ts": 52, + "src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts": 3479, + "src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts": 1257, + "src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts": 717, + "src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts": 643, + "src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts": 607, + "src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts": 820, + "src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts": 681, + "src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts": 681, + "src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts": 696, + "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts": 10279, + "src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts": 34523, + "src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts": 683, + "src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts": 877, + "src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts": 674, + "src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts": 765, + "src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts": 675, + "src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts": 679, + "src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts": 5451, + "src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts": 802, + "src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts": 895, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts": 671, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts": 679, + "src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts": 741, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts": 860, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts": 847, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts": 706, + "src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts": 716, + "src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts": 1125, + "src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts": 729, + "src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts": 645, + "src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts": 801, + "src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts": 723, + "src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts": 692, + "src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts": 723, + "src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts": 941, + "src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts": 719, + "src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts": 2674, + "src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts": 1088, + "src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts": 1014, + "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts": 656, + "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts": 647, + "src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts": 653, + "src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts": 723, + "src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts": 697, + "src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts": 673, + "src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts": 685, + "src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts": 759, + "src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts": 937, + "src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts": 713, + "src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts": 737, + "src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts": 768, + "src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts": 813, + "src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts": 818, + "src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts": 745, + "src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts": 735, + "src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts": 1716, + "src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts": 2772, + "src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts": 657, + "src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts": 660, + "src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts": 665, + "src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts": 708, + "src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts": 672, + "src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts": 641, + "src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts": 676, + "src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts": 843, + "src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts": 681, + "src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts": 762, + "src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts": 852, + "src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts": 701, + "src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts": 901, + "src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts": 758, + "src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts": 688, + "src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts": 764, + "src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts": 687, + "src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts": 643, + "src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts": 694, + "src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts": 666, + "src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts": 718, + "src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts": 697, + "src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts": 783, + "src/main/agent-hooks/server/testing/persistence/server-status-persist-nonblocking.test.ts": 697, + "src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts": 860, + "src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts": 765, + "src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts": 739, + "src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts": 564, + "src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts": 1814, + "src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts": 990, + "src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts": 898, "src/main/agent-hooks/server/program-status/hook-precedence.test.ts": 45, - "src/main/agent-hooks/spool.test.ts": 999, - "src/main/agent-hooks/terminal-handle-row-identity.test.ts": 669, - "src/main/agent-hooks/windows-batch-hook-launcher.test.ts": 108, - "src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts": 141, - "src/main/agent-hooks/windows-hook-payload-delivery.test.ts": 345, - "src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts": 262, - "src/main/agent-hooks/windows-powershell-hook-launcher.test.ts": 44, - "src/main/agent-hooks/wsl-guest-plugin-install.test.ts": 64, - "src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts": 1235, - "src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts": 2231, - "src/main/agent-hooks/wsl-hook-relay-manager.test.ts": 3176, - "src/main/agent-hooks/wsl-hook-relay-reattach.test.ts": 1280, - "src/main/agent-hooks/wsl-hook-relay-recovery.test.ts": 1529, - "src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts": 62, - "src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts": 1951, - "src/main/agent-hooks/wsl-opencode-settings.test.ts": 1364, + "src/main/agent-hooks/server/testing/replay/spool.test.ts": 999, + "src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts": 669, + "src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts": 108, + "src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts": 141, + "src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts": 345, + "src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts": 262, + "src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts": 44, + "src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts": 64, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.test.ts": 1235, + "src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts": 2231, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts": 3176, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.test.ts": 1280, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts": 1529, + "src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts": 62, + "src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts": 1951, + "src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts": 1364, "src/main/agent-launch/agent-launch-account-env.test.ts": 958, "src/main/agent-launch/agent-launch-executor-cancel.test.ts": 1455, "src/main/agent-launch/agent-launch-mode-settings.test.ts": 4041, diff --git a/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs b/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs index 792e33eea61..f693ed3997d 100644 --- a/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs +++ b/config/scripts/desktop-distribution/runtime-verification/electron-builder-runtime-resources.test.mjs @@ -23,7 +23,10 @@ describe('packaged runtime resources', () => { const sources = new Map([ ['out\\main\\index.js', 'const z = require("zod")'], - ['out\\main\\agent-hooks\\managed-agent-hook-controls.js', 'const YAML = require("yaml")'] + [ + 'out\\main\\agent-hooks\\installation\\managed-agent-hook-controls.js', + 'const YAML = require("yaml")' + ] ]) const asar = { listPackage: () => [...sources.keys()].map((entry) => `\\${entry}`), @@ -48,7 +51,7 @@ describe('packaged runtime resources', () => { 'let p=null;function q(){return p??=import(`@anthropic-ai/claude-agent-sdk`),p}' ], [ - 'out/main/agent-hooks/managed-agent-hook-controls.js', + 'out/main/agent-hooks/installation/managed-agent-hook-controls.js', 'import (`@anthropic-ai/claude-agent-sdk`)' ] ]) @@ -96,7 +99,7 @@ describe('packaged runtime resources', () => { // The entry points themselves carry no specifier; only the shared chunk does. const sources = new Map([ ['out/main/index.js', ''], - ['out/main/agent-hooks/managed-agent-hook-controls.js', ''], + ['out/main/agent-hooks/installation/managed-agent-hook-controls.js', ''], ['out/main/chunks/managed-agent-hook-controls-CWf8D-KR.js', 'require(`jsonc-parser`)'] ]) // listPackage includes directories that extractFile rejects; mock them to enforce the .js anchor. @@ -128,7 +131,7 @@ describe('packaged runtime resources', () => { const sources = new Map([ ['out/main/index.js', 'const all=[...require("jsonc-parser")]'], - ['out/main/agent-hooks/managed-agent-hook-controls.js', ''] + ['out/main/agent-hooks/installation/managed-agent-hook-controls.js', ''] ]) const asar = { listPackage: () => [...sources.keys()].map((entry) => `/${entry}`), @@ -149,7 +152,10 @@ describe('packaged runtime resources', () => { // Registry require(key) members are not packaged bare-module imports, even with literal keys. const sources = new Map([ ['out/main/index.js', 'registry.require("public-a");grants.require(`host-key`)'], - ['out/main/agent-hooks/managed-agent-hook-controls.js', 'state.import("android-sdk")'] + [ + 'out/main/agent-hooks/installation/managed-agent-hook-controls.js', + 'state.import("android-sdk")' + ] ]) const asar = { listPackage: () => [...sources.keys()].map((entry) => `/${entry}`), diff --git a/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs b/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs index 4ded5ca11fe..74dbf9cd52b 100644 --- a/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs +++ b/config/scripts/performance/wsl-hooks/wsl-hook-relay-reattach-benchmark.mjs @@ -310,10 +310,10 @@ async function main() { )) ;({ killAllPty } = await jiti.import('../../../../src/main/ipc/pty/kill-all.ts')) const { WslHookRelayManager, wslHookRelayManager } = await jiti.import( - '../../../../src/main/agent-hooks/wsl-hook-relay-manager.ts' + '../../../../src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts' ) const { ensureWslHookRelayForReattach } = await jiti.import( - '../../../../src/main/agent-hooks/wsl-hook-relay-reattach.ts' + '../../../../src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts' ) const { codexHookService } = await jiti.import( '../../../../src/main/codex/hooks/installation/hook-service.ts' 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 ab708cb3808..85b55c113ff 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 @@ -92,7 +92,7 @@ const NODE_RUNTIME_INCLUDE = [ 'src/**/*allocation*.test.ts', 'src/**/*expiry*.test.ts', 'src/shared/own-retained-string.test.ts', - 'src/main/agent-hooks/server-transport-interference.test.ts', + 'src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts', 'src/main/plugins/workers/plugin-worker-supervision.integration.test.ts', 'src/main/plugins/workers/plugin-worker-dev-restart-storage.integration.test.ts', // Worker TypeScript loads through node:module registerHooks, which Bun lacks. diff --git a/config/scripts/workflow/source-routing/pr-code-change-scope.mjs b/config/scripts/workflow/source-routing/pr-code-change-scope.mjs index bb2fb961100..c6c1856325e 100644 --- a/config/scripts/workflow/source-routing/pr-code-change-scope.mjs +++ b/config/scripts/workflow/source-routing/pr-code-change-scope.mjs @@ -102,8 +102,8 @@ const CODEX_INDEX_HEAL_CONTRACT_PREFIXES = [ 'src/main/codex/trust/identity/codex-trust-identity', 'src/main/codex/trust/toml/config-toml-hook-trust-', 'src/main/codex/configuration/toml/config-toml-key-path', - 'src/main/agent-hooks/posix-hook-command', - 'src/main/agent-hooks/hook-post-command', + 'src/main/agent-hooks/installation/commands/posix-hook-command', + 'src/main/agent-hooks/installation/scripts/hook-post-command', 'src/main/codex-cli/codex-read-only-app-server-args', 'src/main/agent-launch/trust/agent-trust-presets', 'src/main/codex/trust/toml/config-toml-trust', 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 29530b99e35..2e17a2ce5e2 100644 --- a/config/scripts/workflow/source-routing/pr-package-test-paths.mjs +++ b/config/scripts/workflow/source-routing/pr-package-test-paths.mjs @@ -173,14 +173,14 @@ export const WINDOWS_BOUNDARY_TESTS = [ 'src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts', 'src/shared/agent-launch/startup/omp-fresh-launch-cmd.win32.test.ts', 'src/shared/windows-batch-spawn.win32.test.ts', - 'src/main/agent-hooks/windows-hook-payload-delivery.test.ts', - 'src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts', + 'src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts', + 'src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts', 'src/main/jcode/hook-gate-script.test.ts', - 'src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts', + 'src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts', 'src/main/claude/windows-native-hook-registration.test.ts', - 'src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts', - 'src/main/agent-hooks/windows-batch-hook-launcher.test.ts', - 'src/main/agent-hooks/windows-powershell-hook-launcher.test.ts', + 'src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts', + 'src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts', + 'src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts', 'src/main/claude/claude-status-line-windows.test.ts', 'src/main/codex/hooks/installation/windows-hook-command.test.ts', 'src/main/codex/hooks/installation/hook-service-managed-install.test.ts', diff --git a/src/cli/handlers/agent-hooks.test.ts b/src/cli/handlers/agent-hooks.test.ts index ae7dba93bdd..bff357168f7 100644 --- a/src/cli/handlers/agent-hooks.test.ts +++ b/src/cli/handlers/agent-hooks.test.ts @@ -83,7 +83,7 @@ vi.mock('../runtime-client', () => { } }) -vi.mock('../../main/agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock, getManagedAgentHookStatuses: getManagedAgentHookStatusesMock })) diff --git a/src/cli/handlers/agent-hooks.ts b/src/cli/handlers/agent-hooks.ts index 6689e9f86bb..522fa9d485c 100644 --- a/src/cli/handlers/agent-hooks.ts +++ b/src/cli/handlers/agent-hooks.ts @@ -163,7 +163,7 @@ async function setAgentHooksEnabled( enabled: boolean ): Promise { const { applyAgentStatusHooksEnabled, getManagedAgentHookStatuses } = - await import('../../main/agent-hooks/managed-agent-hook-controls.js') + await import('../../main/agent-hooks/installation/managed-agent-hook-controls.js') const updatedRuntime = await updateRunningRuntime(client, enabled) const offlineUpdate = updatedRuntime ? null : await updateEnabledOnDisk(enabled) const settingsPath = offlineUpdate?.settingsPath ?? (await getDataPath()) @@ -202,7 +202,7 @@ export const AGENT_HOOK_HANDLERS: Record = { 'agent hooks status': async ({ json, flags }) => { rejectRemoteHookSelection(flags) const { getManagedAgentHookStatuses } = - await import('../../main/agent-hooks/managed-agent-hook-controls.js') + await import('../../main/agent-hooks/installation/managed-agent-hook-controls.js') const result: AgentHookCommandResult = { enabled: (await readHookSettingsFromDisk()).agentStatusHooksEnabled, settingsPath: await getDataPath(), diff --git a/src/cli/runtime-client-deferral.test.ts b/src/cli/runtime-client-deferral.test.ts index 8e78d6cae9f..ef6908fe9a7 100644 --- a/src/cli/runtime-client-deferral.test.ts +++ b/src/cli/runtime-client-deferral.test.ts @@ -37,7 +37,7 @@ vi.mock( ) // Stub hook writes: this suite runs real handlers that would otherwise edit the developer's agent configs. -vi.mock('../main/agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../main/agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock, getManagedAgentHookStatuses: vi.fn(() => []) })) diff --git a/src/cli/runtime/offline-admission-commands.test.ts b/src/cli/runtime/offline-admission-commands.test.ts index 45527e3df55..bb6a0bdbbd7 100644 --- a/src/cli/runtime/offline-admission-commands.test.ts +++ b/src/cli/runtime/offline-admission-commands.test.ts @@ -26,7 +26,7 @@ vi.mock('@orca/process-host', async (original) => ({ })) // Exercise the existing hook installer on one isolated target; do not discover installed agents. -vi.mock('../../main/agent-hooks/managed-agent-hook-controls', async () => { +vi.mock('../../main/agent-hooks/installation/managed-agent-hook-controls', async () => { const { claudeHookService } = await import('../../main/claude/hook-service.js') return { applyAgentStatusHooksEnabled: vi.fn(async (enabled: boolean) => [ diff --git a/src/main/acp/session/children/acp-structured-background-task-stop.test.ts b/src/main/acp/session/children/acp-structured-background-task-stop.test.ts index ec8d0bd65a8..e703a43caef 100644 --- a/src/main/acp/session/children/acp-structured-background-task-stop.test.ts +++ b/src/main/acp/session/children/acp-structured-background-task-stop.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _internals } from '../../../agent-hooks/server' +import { _internals } from '../../../agent-hooks/server/agent-hook-server' import { closeProviderTimelineRigs, SESSION as ADAPTER_SESSION diff --git a/src/main/acp/session/children/acp-structured-child-work.test.ts b/src/main/acp/session/children/acp-structured-child-work.test.ts index fed21606981..e223bf0130f 100644 --- a/src/main/acp/session/children/acp-structured-child-work.test.ts +++ b/src/main/acp/session/children/acp-structured-child-work.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { _internals } from '../../../agent-hooks/server' +import { _internals } from '../../../agent-hooks/server/agent-hook-server' import { closeProviderTimelineRigs } from '../../../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' import { CALLER } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' import { HOST_TEST_SESSION as SESSION } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-data' diff --git a/src/main/acp/session/testing/acp-structured-child-work.test-support.ts b/src/main/acp/session/testing/acp-structured-child-work.test-support.ts index c66bc99e2c7..7332c22fcd7 100644 --- a/src/main/acp/session/testing/acp-structured-child-work.test-support.ts +++ b/src/main/acp/session/testing/acp-structured-child-work.test-support.ts @@ -1,4 +1,4 @@ -import { AgentHookServer } from '../../../agent-hooks/server' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { AgentChildWorkEvidence } from '../../../../shared/agent-status/child-work/agent-status-child-work-evidence' import { makeStructuredAgentStatusSubject, diff --git a/src/main/agent-hooks/README.md b/src/main/agent-hooks/README.md index 033dfd26332..3ed3b46dc06 100644 --- a/src/main/agent-hooks/README.md +++ b/src/main/agent-hooks/README.md @@ -3,10 +3,10 @@ Orca learns what each agent is doing through two channels. Both write into the hook server's status store. -| Channel | How | What it carries | -| ---------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | -| **Managed integrations** (this folder) | Per-agent hooks, plugins and extensions that POST to the loopback hook server. Installers are listed in `managed-agent-hook-registry.ts`; each agent's code lives in `src/main//`. | State, prompt, tool name and input, assistant reply, provider session id (resume and native chat), model, subagents | -| **OSC 7501** (Program Status Protocol, [spec](https://www.superlogical.com/rex/docs/build/program-status)) | The agent writes its own status into the terminal stream. Orca reads it from PTY output and answers the protocol's `?` probe. | State, blocked `kind`, one free-text line (`msg`), child records | +| Channel | How | What it carries | +| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | +| **Managed integrations** (this folder) | Per-agent hooks, plugins and extensions that POST to the loopback hook server. Installers are listed in `installation/managed-agent-hook-registry.ts`; each agent's code lives in `src/main//`. | State, prompt, tool name and input, assistant reply, provider session id (resume and native chat), model, subagents | +| **OSC 7501** (Program Status Protocol, [spec](https://www.superlogical.com/rex/docs/build/program-status)) | The agent writes its own status into the terminal stream. Orca reads it from PTY output and answers the protocol's `?` probe. | State, blocked `kind`, one free-text line (`msg`), child records | **Precedence:** hooks win, and OSC 7501 fills in wherever they don't speak. That covers: @@ -90,7 +90,7 @@ When an agent ships OSC 7501 support, or changes what it reports: ## Plugin tool hooks (`agent.tool.before` / `.after`) The hook server runs plugins' `agent.tool.before` and `.after` on each tool event it receives, after -it records status (`agent-tool-plugin-hooks.ts`). Only Claude Code's POSIX script waits for the +it records status (`tool-events/agent-tool-plugin-hooks.ts`). Only Claude Code's POSIX script waits for the answer: it sends `X-Orca-Hook-Decision: claude-pre-tool-use-v1` on PreToolUse, waits at most 8 s (Orca answers within 6 s), and prints Orca's `hookSpecificOutput` (a `deny`, or `updatedInput` without an approval) or `{}`. A timeout, an error or Orca being down prints `{}`, so the call diff --git a/src/main/agent-hooks/branch-rename-failure-output.ts b/src/main/agent-hooks/first-work/branch-rename-failure-output.ts similarity index 95% rename from src/main/agent-hooks/branch-rename-failure-output.ts rename to src/main/agent-hooks/first-work/branch-rename-failure-output.ts index 1534c120b72..6bf1648d4e8 100644 --- a/src/main/agent-hooks/branch-rename-failure-output.ts +++ b/src/main/agent-hooks/first-work/branch-rename-failure-output.ts @@ -1,7 +1,7 @@ import { formatAgentGenerationFailureOutputForDisplay, type AgentGenerationFailureOutput -} from '../text-generation/agent-failure-output' +} from '../../text-generation/agent-failure-output' // Keep full CLI diagnostics local and ephemeral; persist only the sanitized failure badge. const MAX_ENTRIES = 32 diff --git a/src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts b/src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts similarity index 89% rename from src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts rename to src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts index e18044fd9c7..a2efb8ae1a8 100644 --- a/src/main/agent-hooks/first-work-branch-rename-wsl-move.test.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-rename-wsl-move.test.ts @@ -2,13 +2,13 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../shared/repo-types' -import { wslMoveCutoverFixture as cutover } from '../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { seedWslMoveCutover } from '../persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' +import type { Repo } from '../../../shared/repo-types' +import { wslMoveCutoverFixture as cutover } from '../../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' +import { seedWslMoveCutover } from '../../persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' import { loadWslMoveFence, resetWslMoveFenceForTests -} from '../persistence/moving-wsl-projects/wsl-move-scope-guard' +} from '../../persistence/moving-wsl-projects/wsl-move-scope-guard' const { gitExecFileAsyncMock, generateBranchNameMock, resolveTextGenerationParamsMock } = vi.hoisted(() => ({ @@ -17,19 +17,19 @@ const { gitExecFileAsyncMock, generateBranchNameMock, resolveTextGenerationParam resolveTextGenerationParamsMock: vi.fn() })) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/git-username', () => ({ resolveLocalGitUsername: vi.fn(async () => 'you') })) -vi.mock('../text-generation/commit-message-text-generation', () => ({ +vi.mock('../../git/git-username', () => ({ resolveLocalGitUsername: vi.fn(async () => 'you') })) +vi.mock('../../text-generation/commit-message-text-generation', () => ({ generateBranchNameFromContext: generateBranchNameMock, resolveTextGenerationParams: resolveTextGenerationParamsMock })) -vi.mock('../text-generation/commit-message-agent-environment', () => ({ +vi.mock('../../text-generation/commit-message-agent-environment', () => ({ prepareLocalCommitMessageAgentEnv: vi.fn(async () => ({ ok: true })) })) -vi.mock('../ipc/worktree-branch-name', () => ({ +vi.mock('../../ipc/worktree-branch-name', () => ({ computeBranchName: vi.fn((leaf: string) => `you/${leaf}`), getConfiguredBranchPrefix: vi.fn(() => 'you') })) @@ -45,7 +45,7 @@ import { gitResponder, makeBranchRenameDeps, workingEvent -} from './first-work-branch-rename-test-harness' +} from './testing/first-work-branch-rename-test-harness' const LOCAL_REPO: Repo = { id: REPO_ID, diff --git a/src/main/agent-hooks/first-work-branch-rename.test.ts b/src/main/agent-hooks/first-work/first-work-branch-rename.test.ts similarity index 93% rename from src/main/agent-hooks/first-work-branch-rename.test.ts rename to src/main/agent-hooks/first-work/first-work-branch-rename.test.ts index 0e4243ad92c..a2e08567087 100644 --- a/src/main/agent-hooks/first-work-branch-rename.test.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-rename.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../shared/repo-types' -import type * as CommitMessageTextGenerationModule from '../text-generation/commit-message-text-generation' -import type { AgentJournalRenderItem } from '../../shared/agent-session/journal/agent-session-journal-types' -import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' -import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' +import type { Repo } from '../../../shared/repo-types' +import type * as CommitMessageTextGenerationModule from '../../text-generation/commit-message-text-generation' +import type { AgentJournalRenderItem } from '../../../shared/agent-session/journal/agent-session-journal-types' +import type { AgentSessionJournal } from '../../native-chat/agent-session-journal/journal-store' +import { StructuredAgentSessionStatusFeed } from '../../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' import { maybeAutoRenameWorkspaceOnFirstStructuredTurn } from './first-work-structured-session-rename' -import '../../shared/worktree/id' +import '../../../shared/worktree/id' const { gitExecFileAsyncMock, @@ -25,22 +25,22 @@ const { getConfiguredBranchPrefixMock: vi.fn((_settings: unknown, username: string | null) => username) })) -vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({ +vi.mock('../../git/command-runner/git-exec-file', async (importOriginal) => ({ ...(await importOriginal>()), gitExecFileAsync: gitExecFileAsyncMock })) -vi.mock('../git/git-username', () => ({ resolveLocalGitUsername: resolveLocalGitUsernameMock })) -vi.mock('../text-generation/commit-message-text-generation', () => ({ +vi.mock('../../git/git-username', () => ({ resolveLocalGitUsername: resolveLocalGitUsernameMock })) +vi.mock('../../text-generation/commit-message-text-generation', () => ({ generateBranchNameFromContext: generateBranchNameMock, resolveTextGenerationParams: resolveTextGenerationParamsMock })) await vi.importActual( - '../text-generation/commit-message-text-generation' + '../../text-generation/commit-message-text-generation' ) -vi.mock('../text-generation/commit-message-agent-environment', () => ({ +vi.mock('../../text-generation/commit-message-agent-environment', () => ({ prepareLocalCommitMessageAgentEnv: prepareLocalEnvMock })) -vi.mock('../ipc/worktree-branch-name', () => ({ +vi.mock('../../ipc/worktree-branch-name', () => ({ computeBranchName: computeBranchNameMock, getConfiguredBranchPrefix: getConfiguredBranchPrefixMock })) @@ -57,9 +57,9 @@ import { makeBranchRenameDeps, noUpstreamError, workingEvent -} from './first-work-branch-rename-test-harness' +} from './testing/first-work-branch-rename-test-harness' import { FIRST_WORK_GENERATION_RETRY_DELAYS_MS } from './first-work-generation-backoff' -import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/host/structured-agent-session-logger' +import { createStructuredAgentSessionLogger } from '../../native-chat/agent-session-wire/host/structured-agent-session-logger' const REMOTE_REPO_BASE: Repo = { id: REPO_ID, diff --git a/src/main/agent-hooks/first-work-branch-rename.ts b/src/main/agent-hooks/first-work/first-work-branch-rename.ts similarity index 90% rename from src/main/agent-hooks/first-work-branch-rename.ts rename to src/main/agent-hooks/first-work/first-work-branch-rename.ts index f68b94e2c3e..b0be745b23a 100644 --- a/src/main/agent-hooks/first-work-branch-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-branch-rename.ts @@ -1,36 +1,36 @@ -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { Repo } from '../../shared/repo-types' -import { isFolderRepo } from '../../shared/repo-kind' -import { getRepoIdFromWorktreeId, splitWorktreeIdForFilesystem } from '../../shared/worktree/id' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { parsePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { Repo } from '../../../shared/repo-types' +import { isFolderRepo } from '../../../shared/repo-kind' +import { getRepoIdFromWorktreeId, splitWorktreeIdForFilesystem } from '../../../shared/worktree/id' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { humanizeBranchSlug, isAutoGeneratedCreatureBranchName, stripConfiguredBranchPrefix -} from '../../shared/source-control/ai/naming/branch-name-from-work' -import { getCommitMessageModelDiscoveryHostKey } from '../../shared/source-control/ai/generation/commit-message-host-key' -import { computeBranchName, getConfiguredBranchPrefix } from '../ipc/worktree-branch-name' -import { gitExecFileAsync } from '../git/runner' -import { resolveLocalGitUsername } from '../git/git-username' -import { resolveGitRouteForHost } from '../providers/execution-host-provider-dispatch' -import { getRepoExecutionHostId } from '../../shared/execution-host' -import { withCheckoutLock } from '../git/branch-switch' +} from '../../../shared/source-control/ai/naming/branch-name-from-work' +import { getCommitMessageModelDiscoveryHostKey } from '../../../shared/source-control/ai/generation/commit-message-host-key' +import { computeBranchName, getConfiguredBranchPrefix } from '../../ipc/worktree-branch-name' +import { gitExecFileAsync } from '../../git/command-runner/git-exec-file' +import { resolveLocalGitUsername } from '../../git/git-username' +import { resolveGitRouteForHost } from '../../providers/execution-host-provider-dispatch' +import { getRepoExecutionHostId } from '../../../shared/execution-host' +import { withCheckoutLock } from '../../git/branch-switch' import { probeBranchUpstream, renameCurrentBranch, resolveUniqueBranchName, type GitExec -} from '../git/branch-rename' +} from '../../git/branch-rename' import { generateBranchNameFromContext, resolveTextGenerationParams -} from '../text-generation/commit-message-text-generation' -import type { CommitMessageAgentEnvironmentResolvers } from '../text-generation/commit-message-agent-environment' -import type { AgentGenerationFailureOutput } from '../text-generation/agent-failure-output' +} from '../../text-generation/commit-message-text-generation' +import type { CommitMessageAgentEnvironmentResolvers } from '../../text-generation/commit-message-agent-environment' +import type { AgentGenerationFailureOutput } from '../../text-generation/agent-failure-output' import { resolveGenerationTarget } from './first-work-generation-target' import { runFolderWorkspaceTitleAutoRename } from './first-work-workspace-title-rename' -import { isWslMoveRepoBlocked } from '../persistence/moving-wsl-projects/wsl-move-background-backoff' +import { isWslMoveRepoBlocked } from '../../persistence/moving-wsl-projects/wsl-move-background-backoff' import { clearFirstWorkGenerationFailures, isFirstWorkGenerationBackingOff, diff --git a/src/main/agent-hooks/first-work-folder-rename.ts b/src/main/agent-hooks/first-work/first-work-folder-rename.ts similarity index 84% rename from src/main/agent-hooks/first-work-folder-rename.ts rename to src/main/agent-hooks/first-work/first-work-folder-rename.ts index c0266646b97..e28630215d9 100644 --- a/src/main/agent-hooks/first-work-folder-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-folder-rename.ts @@ -1,13 +1,13 @@ -import type { Repo } from '../../shared/repo-types' +import type { Repo } from '../../../shared/repo-types' import { FOLDER_WORKSPACE_INSTANCE_SEPARATOR, getRepoIdFromWorktreeId, splitWorktreeIdForFilesystem -} from '../../shared/worktree/id' -import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import { planWorktreeFolderRename } from '../ipc/worktree-folder-rename-target' -import { hostWorktreeTargetForRepo } from '../persistence/host-qualified-worktree-meta' -import type { HostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' +} from '../../../shared/worktree/id' +import { getRepoExecutionHostId, LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import { planWorktreeFolderRename } from '../../ipc/worktree-folder-rename-target' +import { hostWorktreeTargetForRepo } from '../../persistence/host-qualified-worktree-meta' +import type { HostWorktreeTarget } from '../../../shared/worktree/host-qualified-identity' export type FirstWorkFolderRenameDeps = { getRepo: (repoId: string) => Repo | undefined diff --git a/src/main/agent-hooks/first-work-generation-backoff.ts b/src/main/agent-hooks/first-work/first-work-generation-backoff.ts similarity index 94% rename from src/main/agent-hooks/first-work-generation-backoff.ts rename to src/main/agent-hooks/first-work/first-work-generation-backoff.ts index a3a0affccf2..76074de126c 100644 --- a/src/main/agent-hooks/first-work-generation-backoff.ts +++ b/src/main/agent-hooks/first-work/first-work-generation-backoff.ts @@ -1,4 +1,4 @@ -import type { AgentGenerationFailureOutput } from '../text-generation/agent-failure-output' +import type { AgentGenerationFailureOutput } from '../../text-generation/agent-failure-output' // Usage-limit failures spawned hundreds of sessions on repeated working events (#9705); back off until recovery. export const FIRST_WORK_GENERATION_RETRY_DELAYS_MS: readonly number[] = [30_000, 120_000, 1_800_000] diff --git a/src/main/agent-hooks/first-work-generation-target.ts b/src/main/agent-hooks/first-work/first-work-generation-target.ts similarity index 76% rename from src/main/agent-hooks/first-work-generation-target.ts rename to src/main/agent-hooks/first-work/first-work-generation-target.ts index 0409165fda2..a7cd93095dd 100644 --- a/src/main/agent-hooks/first-work-generation-target.ts +++ b/src/main/agent-hooks/first-work/first-work-generation-target.ts @@ -1,8 +1,8 @@ -import type { CommitMessageGenerationTarget } from '../text-generation/commit-message-text-generation' +import type { CommitMessageGenerationTarget } from '../../text-generation/commit-message-text-generation' import { prepareLocalCommitMessageAgentEnv, type CommitMessageAgentEnvironmentResolvers -} from '../text-generation/commit-message-agent-environment' +} from '../../text-generation/commit-message-agent-environment' export async function resolveGenerationTarget( worktreePath: string, diff --git a/src/main/agent-hooks/first-work-rename-runtime.ts b/src/main/agent-hooks/first-work/first-work-rename-runtime.ts similarity index 88% rename from src/main/agent-hooks/first-work-rename-runtime.ts rename to src/main/agent-hooks/first-work/first-work-rename-runtime.ts index ef5ee766811..42152d68a16 100644 --- a/src/main/agent-hooks/first-work-rename-runtime.ts +++ b/src/main/agent-hooks/first-work/first-work-rename-runtime.ts @@ -1,16 +1,16 @@ import { existsSync } from 'node:fs' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { LOCAL_EXECUTION_HOST_ID } from '../../shared/execution-host' -import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import type { FirstWorkBranchRenameDeps } from './first-work-branch-rename' import { rememberBranchRenameFailureOutput } from './branch-rename-failure-output' import { renameWorktreeFolderOnFirstWork } from './first-work-folder-rename' -import { moveWorktree } from '../git/worktrees/movement/worktree-move' -import { isWslMoveFolderWorkspaceBlocked } from '../persistence/moving-wsl-projects/wsl-move-background-backoff' -import type { Store } from '../persistence/loading-store/store' -import type { RuntimeStore } from '../runtime/construction/runtime-store-contract' -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import { resolveWorktreeMetaOwner } from '../persistence/host-qualified-worktree-meta' +import { moveWorktree } from '../../git/worktrees/movement/worktree-move' +import { isWslMoveFolderWorkspaceBlocked } from '../../persistence/moving-wsl-projects/wsl-move-background-backoff' +import type { Store } from '../../persistence/loading-store/store' +import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import { resolveWorktreeMetaOwner } from '../../persistence/host-qualified-worktree-meta' const ENABLE_FIRST_WORK_FOLDER_RENAME = false diff --git a/src/main/agent-hooks/first-work-structured-session-rename.ts b/src/main/agent-hooks/first-work/first-work-structured-session-rename.ts similarity index 88% rename from src/main/agent-hooks/first-work-structured-session-rename.ts rename to src/main/agent-hooks/first-work/first-work-structured-session-rename.ts index 6b15d1f9acd..eac832483f2 100644 --- a/src/main/agent-hooks/first-work-structured-session-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-structured-session-rename.ts @@ -1,4 +1,4 @@ -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' +import type { AgentSessionStatusSummary } from '../../../shared/agent-session/agent-session-wire' import { maybeAutoRenameBranchOnFirstWork, type FirstWorkBranchRenameDeps diff --git a/src/main/agent-hooks/first-work-workspace-title-rename.ts b/src/main/agent-hooks/first-work/first-work-workspace-title-rename.ts similarity index 94% rename from src/main/agent-hooks/first-work-workspace-title-rename.ts rename to src/main/agent-hooks/first-work/first-work-workspace-title-rename.ts index d075d39c219..d7d98c4a678 100644 --- a/src/main/agent-hooks/first-work-workspace-title-rename.ts +++ b/src/main/agent-hooks/first-work/first-work-workspace-title-rename.ts @@ -1,8 +1,8 @@ -import { humanizeBranchSlug } from '../../shared/source-control/ai/naming/branch-name-from-work' +import { humanizeBranchSlug } from '../../../shared/source-control/ai/naming/branch-name-from-work' import { generateBranchNameFromContext, resolveTextGenerationParams -} from '../text-generation/commit-message-text-generation' +} from '../../text-generation/commit-message-text-generation' import { resolveGenerationTarget } from './first-work-generation-target' import type { FirstWorkBranchRenameDeps } from './first-work-branch-rename' import { retryFailedGeneration } from './first-work-generation-backoff' diff --git a/src/main/agent-hooks/first-work-branch-rename-test-harness.ts b/src/main/agent-hooks/first-work/testing/first-work-branch-rename-test-harness.ts similarity index 89% rename from src/main/agent-hooks/first-work-branch-rename-test-harness.ts rename to src/main/agent-hooks/first-work/testing/first-work-branch-rename-test-harness.ts index 2627651dec2..b2c48c53ce9 100644 --- a/src/main/agent-hooks/first-work-branch-rename-test-harness.ts +++ b/src/main/agent-hooks/first-work/testing/first-work-branch-rename-test-harness.ts @@ -1,12 +1,12 @@ import type { vi } from 'vitest' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { Repo } from '../../shared/repo-types' -import '../../shared/worktree/id' -import { WORKTREE_ID_SEPARATOR } from '../../shared/terminal/pty/lifecycle/pty-session-id-format' +import type { GlobalSettings } from '../../../../shared/global-settings-types' +import type { Repo } from '../../../../shared/repo-types' +import '../../../../shared/worktree/id' +import { WORKTREE_ID_SEPARATOR } from '../../../../shared/terminal/pty/lifecycle/pty-session-id-format' import type { FirstWorkBranchRenameDeps, FirstWorkBranchRenameEvent -} from './first-work-branch-rename' +} from '../first-work-branch-rename' export const REPO_ID = 'repo1' export const WORKTREE_ID = `${REPO_ID}${WORKTREE_ID_SEPARATOR}/repo/wt` diff --git a/src/main/agent-hooks/agent-home-login-shell.ts b/src/main/agent-hooks/installation/agent-home-login-shell.ts similarity index 100% rename from src/main/agent-hooks/agent-home-login-shell.ts rename to src/main/agent-hooks/installation/agent-home-login-shell.ts diff --git a/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts b/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts new file mode 100644 index 00000000000..82b599b4a5e --- /dev/null +++ b/src/main/agent-hooks/installation/commands/managed-hook-command-matching.ts @@ -0,0 +1,119 @@ +import { + getWindowsNativeHookAgent, + WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME +} from './windows-native-hook-executable' + +import type { HookCommandConfig, HookDefinition } from '../configuration/hook-config-schema' + +// Match script names so reinstalls sweep entries from old and parallel installations. +export function createManagedCommandMatcher( + scriptFileName: string +): (command: string | undefined) => boolean { + const scriptStem = scriptFileName.replace(/\.(?:cmd|ps1|sh)$/, '') + // Sweep every platform suffix after a platform switch. + const needles = [ + `agent-hooks/${scriptFileName}`, + `agent-hooks/${scriptStem}.cmd`, + `agent-hooks/${scriptStem}.ps1`, + `agent-hooks/${scriptStem}.sh` + ] + // The native executable selects its provider through argv[1]. + const nativeHook = `agent-hooks/${WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME} ${getWindowsNativeHookAgent(scriptFileName)} ` + return (command) => { + if (!command) { + return false + } + const decodedCommand = decodePowerShellEncodedCommand(command) + const searchText = decodedCommand ? `${command}\n${decodedCommand}` : command + const normalizedCommand = searchText.replaceAll('\\', '/') + return ( + needles.some((needle) => normalizedCommand.includes(needle)) || + normalizedCommand.split('\n').some((line) => `${line} `.includes(nativeHook)) + ) + } +} + +function decodePowerShellEncodedCommand(command: string): string | null { + const match = command.match(/\s-EncodedCommand\s+(\S+)/i) + if (!match) { + return null + } + try { + return Buffer.from(match[1], 'base64').toString('utf16le') + } catch { + return null + } +} + +export function removeManagedCommands( + definitions: HookDefinition[], + isManagedCommand: (command: string | undefined) => boolean +): HookDefinition[] { + return definitions.flatMap((definition) => { + const directCommandKeys = ['command', 'bash', 'powershell'] as const + const directManagedKeys = directCommandKeys.filter((key) => isManagedCommand(definition[key])) + const hasNestedHooks = Array.isArray(definition.hooks) + const hasManagedNestedHook = + hasNestedHooks && + definition.hooks!.some((hook) => hookHasManagedCommand(hook, isManagedCommand)) + + if (directManagedKeys.length === 0 && !hasManagedNestedHook) { + return [definition] + } + + const nextDefinition: HookDefinition = { ...definition } + for (const key of directManagedKeys) { + delete nextDefinition[key] + } + + if (hasManagedNestedHook) { + const filteredHooks = definition.hooks!.filter( + (hook) => !hookHasManagedCommand(hook, isManagedCommand) + ) + if (filteredHooks.length > 0) { + nextDefinition.hooks = filteredHooks + } else { + delete nextDefinition.hooks + } + } + + const hasCommandAfterCleanup = + directCommandKeys.some((key) => typeof nextDefinition[key] === 'string') || + (Array.isArray(nextDefinition.hooks) && nextDefinition.hooks.length > 0) + if (!hasCommandAfterCleanup) { + return [] + } + + return [nextDefinition] + }) +} + +function hookHasManagedCommand(hook: HookCommandConfig, matches: (value?: string) => boolean) { + const args = Array.isArray(hook.args) ? hook.args : [] + return matches(hook.command) || args.some((arg) => typeof arg === 'string' && matches(arg)) +} + +// Users may opt a managed hook into async; keep that choice when the hook is rewritten. +export function withPreviousManagedAsync( + hook: HookCommandConfig, + definitions: HookDefinition[], + matches: (command: string | undefined) => boolean +): HookCommandConfig { + const async = definitions + .flatMap((definition) => (Array.isArray(definition.hooks) ? definition.hooks : [])) + .find((prev) => typeof prev.async === 'boolean' && hookHasManagedCommand(prev, matches))?.async + return async === undefined ? hook : { ...hook, async } +} + +export function hookDefinitionHasManagedCommand( + definition: HookDefinition, + isManagedCommand: (command: string | undefined) => boolean +): boolean { + return ( + isManagedCommand(definition.command) || + isManagedCommand(definition.bash) || + isManagedCommand(definition.powershell) || + (Array.isArray(definition.hooks) && + definition.hooks.some((hook) => hookHasManagedCommand(hook, isManagedCommand))) + ) +} diff --git a/src/main/agent-hooks/posix-hook-command.ts b/src/main/agent-hooks/installation/commands/posix-hook-command.ts similarity index 87% rename from src/main/agent-hooks/posix-hook-command.ts rename to src/main/agent-hooks/installation/commands/posix-hook-command.ts index 4b5b6a27651..8413c466d1e 100644 --- a/src/main/agent-hooks/posix-hook-command.ts +++ b/src/main/agent-hooks/installation/commands/posix-hook-command.ts @@ -1,5 +1,5 @@ -import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from './hook-stdin-contract' +import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting' +import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../scripts/hook-stdin-contract' // Missing scripts must become silent no-ops rather than fail every tool call. export function wrapPosixHookCommand( diff --git a/src/main/agent-hooks/runtime-home-hook-command.ts b/src/main/agent-hooks/installation/commands/runtime-home-hook-command.ts similarity index 97% rename from src/main/agent-hooks/runtime-home-hook-command.ts rename to src/main/agent-hooks/installation/commands/runtime-home-hook-command.ts index 30b446ca652..bccb999d740 100644 --- a/src/main/agent-hooks/runtime-home-hook-command.ts +++ b/src/main/agent-hooks/installation/commands/runtime-home-hook-command.ts @@ -1,9 +1,9 @@ -import { HOOK_PARENT_CAPTURE } from './hook-process-capture' +import { HOOK_PARENT_CAPTURE } from '../scripts/hook-process-capture' import { POSIX_HOOK_STDIN_DRAIN_COMMAND, WINDOWS_GIT_BASH_HOOK_ENVIRONMENT_GUARD, WINDOWS_POWERSHELL_HOOK_ENVIRONMENT_GUARD -} from './hook-stdin-contract' +} from '../scripts/hook-stdin-contract' import { encodeWindowsPowerShellHookCommand, WINDOWS_POWERSHELL_HOOK_SWITCHES diff --git a/src/main/agent-hooks/managed-hook-command-env.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/managed-hook-command-env.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-command-env.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/managed-hook-command-env.test-fixture.ts diff --git a/src/main/agent-hooks/windows-git-bash-path.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/windows-git-bash-path.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture.ts diff --git a/src/main/agent-hooks/windows-native-hook-exe.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture.ts similarity index 93% rename from src/main/agent-hooks/windows-native-hook-exe.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture.ts index 627344e1d8d..ce599a059dd 100644 --- a/src/main/agent-hooks/windows-native-hook-exe.test-fixture.ts +++ b/src/main/agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture.ts @@ -1,7 +1,7 @@ import { runProcessSync } from '@orca/process-host' import { join, resolve } from 'node:path' -const REPO_ROOT = resolve(import.meta.dirname, '../../..') +const REPO_ROOT = resolve(import.meta.dirname, '../../../../../..') const BUILD_OUTPUT = join( REPO_ROOT, 'native', diff --git a/src/main/agent-hooks/windows-powershell-warm-up.test-fixture.ts b/src/main/agent-hooks/installation/commands/testing/windows-powershell-warm-up.test-fixture.ts similarity index 90% rename from src/main/agent-hooks/windows-powershell-warm-up.test-fixture.ts rename to src/main/agent-hooks/installation/commands/testing/windows-powershell-warm-up.test-fixture.ts index 8a71bf49c09..646af426d11 100644 --- a/src/main/agent-hooks/windows-powershell-warm-up.test-fixture.ts +++ b/src/main/agent-hooks/installation/commands/testing/windows-powershell-warm-up.test-fixture.ts @@ -1,6 +1,6 @@ import { runProcess } from '@orca/process-host' import { expect } from 'vitest' -import { wrapWindowsHookCommand } from './installer-utils' +import { wrapWindowsHookCommand } from '../windows-hook-command' // A fresh runner's first encoded-PowerShell launch took 5-40s; per-hook bounds detect stdin hangs, not cold start. export const WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS = 90_000 diff --git a/src/main/agent-hooks/installation/commands/windows-agent-hook-post-command.ts b/src/main/agent-hooks/installation/commands/windows-agent-hook-post-command.ts new file mode 100644 index 00000000000..27063100583 --- /dev/null +++ b/src/main/agent-hooks/installation/commands/windows-agent-hook-post-command.ts @@ -0,0 +1,42 @@ +import type { AgentHookSource } from '../../../../shared/agent-hook-listener/transport/agent-hook-relay' + +/** Extra form lines precede payload@- and must end with ` ^`. */ +export function buildWindowsAgentHookPostCommand( + source: AgentHookSource, + extraFormLines: readonly string[] = [] +): string { + // Avoid PowerShell startup; qualify curl to prevent repo-local payload interception. + return [ + `"%SystemRoot%\\System32\\curl.exe" -sS -X POST "http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}" ^`, + ' --connect-timeout 0.5 --max-time 1.5 ^', + ' -H "Content-Type: application/x-www-form-urlencoded" ^', + ' -H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%" ^', + ' --data-urlencode "paneKey=%ORCA_PANE_KEY%" ^', + ' --data-urlencode "tabId=%ORCA_TAB_ID%" ^', + ' --data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%" ^', + ' --data-urlencode "worktreeId=%ORCA_WORKTREE_ID%" ^', + ' --data-urlencode "env=%ORCA_AGENT_HOOK_ENV%" ^', + ' --data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%" ^', + ...extraFormLines, + ' --data-urlencode "payload@-" >nul 2>nul' + ].join('\r\n') +} + +// curl.exe avoids PowerShell startup and code-page corruption of UTF-8 payloads. +export function buildWindowsAgentHookCurlPostCommand(source: AgentHookSource): string { + return [ + '"%SystemRoot%\\System32\\curl.exe" -sS -X POST', + `"http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}"`, + '--connect-timeout 0.5 --max-time 1.5', + '-H "Content-Type: application/x-www-form-urlencoded"', + '-H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%"', + '--data-urlencode "paneKey=%ORCA_PANE_KEY%"', + '--data-urlencode "tabId=%ORCA_TAB_ID%"', + '--data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%"', + '--data-urlencode "worktreeId=%ORCA_WORKTREE_ID%"', + '--data-urlencode "env=%ORCA_AGENT_HOOK_ENV%"', + '--data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%"', + '--data-urlencode "payload@-"', + '>nul 2>&1' + ].join(' ') +} diff --git a/src/main/agent-hooks/windows-batch-hook-launcher.test.ts b/src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts similarity index 93% rename from src/main/agent-hooks/windows-batch-hook-launcher.test.ts rename to src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts index a2ba64ac858..11dd2824b3f 100644 --- a/src/main/agent-hooks/windows-batch-hook-launcher.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-batch-hook-launcher.test.ts @@ -3,10 +3,10 @@ import { mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcess } from '@orca/process-host' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import '../claude/hook-settings' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import '../../../claude/hook-settings' import { wrapWindowsBatchHookCommand } from './windows-direct-cmd-hook-command' -import './windows-git-bash-path.test-fixture' +import './testing/windows-git-bash-path.test-fixture' import { getWindowsPowerShellExecutablePath } from './windows-powershell-hook-launcher' describe.skipIf(process.platform !== 'win32')('guarded Windows batch hook commands', () => { diff --git a/src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts b/src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts similarity index 93% rename from src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts rename to src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts index c00ddf9e26b..54a4d77aa41 100644 --- a/src/main/agent-hooks/windows-cmd-hook-command-unicode.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-cmd-hook-command-unicode.test.ts @@ -5,22 +5,18 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as osModule from 'node:os' import { runProcess } from '@orca/process-host' -import { removeTree } from '../../shared/windows-transient-lock-removal' -import { - isPlainObject, - readHooksJson, - WINDOWS_CMD_SAFE_PATH, - wrapWindowsHookCommand, - writeHooksJson -} from './installer-utils' +import { removeTree } from '../../../../shared/windows-transient-lock-removal' +import { isPlainObject, readHooksJson } from '../configuration/hooks-json-read' +import { WINDOWS_CMD_SAFE_PATH, wrapWindowsHookCommand } from './windows-hook-command' +import { writeHooksJson } from '../configuration/hooks-json-write' import { wrapWindowsBatchHookCommand, wrapWindowsDirectCmdHookCommand } from './windows-direct-cmd-hook-command' -import { AntigravityHookService } from '../antigravity/hook-service' -import { ANTIGRAVITY_EVENTS } from '../antigravity/hook-events' +import { AntigravityHookService } from '../../../antigravity/hook-service' +import { ANTIGRAVITY_EVENTS } from '../../../antigravity/hook-events' import { getWindowsPowerShellExecutablePath } from './windows-powershell-hook-launcher' -import { findGitBash } from './windows-git-bash-path.test-fixture' +import { findGitBash } from './testing/windows-git-bash-path.test-fixture' const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) vi.mock('electron', () => ({ app: { getPath: () => process.cwd() } })) diff --git a/src/main/agent-hooks/windows-direct-cmd-hook-command.ts b/src/main/agent-hooks/installation/commands/windows-direct-cmd-hook-command.ts similarity index 100% rename from src/main/agent-hooks/windows-direct-cmd-hook-command.ts rename to src/main/agent-hooks/installation/commands/windows-direct-cmd-hook-command.ts diff --git a/src/main/agent-hooks/windows-hook-command.ts b/src/main/agent-hooks/installation/commands/windows-hook-command.ts similarity index 90% rename from src/main/agent-hooks/windows-hook-command.ts rename to src/main/agent-hooks/installation/commands/windows-hook-command.ts index ed6a5d6797c..99bd67a669e 100644 --- a/src/main/agent-hooks/windows-hook-command.ts +++ b/src/main/agent-hooks/installation/commands/windows-hook-command.ts @@ -1,5 +1,5 @@ -import { quotePowerShellLiteral } from '../../shared/powershell-native-argument' -import { WINDOWS_POWERSHELL_HOOK_ENVIRONMENT_GUARD } from './hook-stdin-contract' +import { quotePowerShellLiteral } from '../../../../shared/powershell-native-argument' +import { WINDOWS_POWERSHELL_HOOK_ENVIRONMENT_GUARD } from '../scripts/hook-stdin-contract' import { wrapWindowsPowerShellEncodedCommand, type WindowsPowerShellHookOptions diff --git a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts b/src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts similarity index 93% rename from src/main/agent-hooks/windows-hook-payload-delivery.test.ts rename to src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts index 424d4d95549..f2da1c10215 100644 --- a/src/main/agent-hooks/windows-hook-payload-delivery.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-hook-payload-delivery.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' import { createServer, type Server } from 'node:http' import { lstatSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' +import { removeTreeSync } from '../../../../shared/windows-transient-lock-removal' import { tmpdir } from 'node:os' import { basename, dirname, join } from 'node:path' import type * as osModule from 'node:os' @@ -34,30 +34,31 @@ vi.mock('os', async (importOriginal) => { } }) -import { ClaudeHookService } from '../claude/hook-service' -import { CommandCodeHookService } from '../command-code/hook-service' -import { CopilotHookService } from '../copilot/hook-service' -import { DroidHookService } from '../droid/hook-service' -import { DevinHookService } from '../devin/hook-service' -import { DshHookService } from '../dsh/hook-service' -import { GeminiHookService } from '../gemini/hook-service' -import { GrokHookService } from '../grok/hook-service' -import { KimiHookService } from '../kimi/hook-service' -import { KiroHookService } from '../kiro/hook-service' -import { MuseHookService } from '../muse/hook-service' -import { getMuseManagedHooksPath } from '../muse/hook-settings' -import { zcodeHookService } from '../zcode/hook-service' -import { readHooksJson, WINDOWS_CMD_SAFE_PATH, wrapWindowsHookCommand } from './installer-utils' -import { getConfigPath } from '../claude/hook-settings' -import { findGitBash } from './windows-git-bash-path.test-fixture' +import { ClaudeHookService } from '../../../claude/hook-service' +import { CommandCodeHookService } from '../../../command-code/hook-service' +import { CopilotHookService } from '../../../copilot/hook-service' +import { DroidHookService } from '../../../droid/hook-service' +import { DevinHookService } from '../../../devin/hook-service' +import { DshHookService } from '../../../dsh/hook-service' +import { GeminiHookService } from '../../../gemini/hook-service' +import { GrokHookService } from '../../../grok/hook-service' +import { KimiHookService } from '../../../kimi/hook-service' +import { KiroHookService } from '../../../kiro/hook-service' +import { MuseHookService } from '../../../muse/hook-service' +import { getMuseManagedHooksPath } from '../../../muse/hook-settings' +import { zcodeHookService } from '../../../zcode/hook-service' +import { readHooksJson } from '../configuration/hooks-json-read' +import { WINDOWS_CMD_SAFE_PATH, wrapWindowsHookCommand } from './windows-hook-command' +import { getConfigPath } from '../../../claude/hook-settings' +import { findGitBash } from './testing/windows-git-bash-path.test-fixture' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from './windows-native-hook-exe.test-fixture' +} from './testing/windows-native-hook-exe.test-fixture' import { WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS, warmWindowsEncodedPowerShell -} from './windows-powershell-warm-up.test-fixture' +} from './testing/windows-powershell-warm-up.test-fixture' const PANE_KEY = 'tab-1:leaf-1' const HOOK_TOKEN = 'payload-delivery-token' diff --git a/src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts b/src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts similarity index 95% rename from src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts rename to src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts index ea65d89829b..61448369a28 100644 --- a/src/main/agent-hooks/windows-native-hook-exe-hosts.test.ts +++ b/src/main/agent-hooks/installation/commands/windows-native-hook-exe-hosts.test.ts @@ -4,16 +4,16 @@ import { createServer, type IncomingMessage, type Server } from 'node:http' import { copyFileSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import { getManagedScript } from '../claude/hook-script' -import { CLAUDE_HOOK_SETTINGS, getManagedLifecycleHook } from '../claude/hook-settings' -import { getWindowsClaudeHookEntry } from '../claude/windows-hook-files' -import { WINDOWS_CMD_SAFE_PATH } from './installer-utils' +import { removeTreeSync } from '../../../../shared/windows-transient-lock-removal' +import { getManagedScript } from '../../../claude/hook-script' +import { CLAUDE_HOOK_SETTINGS, getManagedLifecycleHook } from '../../../claude/hook-settings' +import { getWindowsClaudeHookEntry } from '../../../claude/windows-hook-files' +import { WINDOWS_CMD_SAFE_PATH } from './windows-hook-command' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from './windows-native-hook-exe.test-fixture' -import { findGitBash } from './windows-git-bash-path.test-fixture' +} from './testing/windows-native-hook-exe.test-fixture' +import { findGitBash } from './testing/windows-git-bash-path.test-fixture' import { getWindowsPowerShellExecutablePath } from './windows-powershell-hook-launcher' const PAYLOAD = JSON.stringify({ diff --git a/src/main/agent-hooks/windows-native-hook-executable.ts b/src/main/agent-hooks/installation/commands/windows-native-hook-executable.ts similarity index 100% rename from src/main/agent-hooks/windows-native-hook-executable.ts rename to src/main/agent-hooks/installation/commands/windows-native-hook-executable.ts diff --git a/src/main/agent-hooks/windows-powershell-hook-launcher.test.ts b/src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts similarity index 100% rename from src/main/agent-hooks/windows-powershell-hook-launcher.test.ts rename to src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.test.ts diff --git a/src/main/agent-hooks/windows-powershell-hook-launcher.ts b/src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.ts similarity index 100% rename from src/main/agent-hooks/windows-powershell-hook-launcher.ts rename to src/main/agent-hooks/installation/commands/windows-powershell-hook-launcher.ts diff --git a/src/main/agent-hooks/installation/configuration/hook-config-schema.ts b/src/main/agent-hooks/installation/configuration/hook-config-schema.ts new file mode 100644 index 00000000000..34d6b679b71 --- /dev/null +++ b/src/main/agent-hooks/installation/configuration/hook-config-schema.ts @@ -0,0 +1,40 @@ +export type HookCommandConfig = { + type: 'command' + command: string + args?: string[] + timeout?: number + async?: boolean + statusMessage?: string + [key: string]: unknown +} + +export type HookDefinition = { + matcher?: string + command?: string + bash?: string + powershell?: string + hooks?: HookCommandConfig[] + [key: string]: unknown +} + +export type HooksConfig = { + hooks?: Record + [key: string]: unknown +} + +// Host-level backstop independent of curl and provider-specific timeouts. +export const MANAGED_HOOK_TIMEOUT_SECONDS = 10 + +export const MANAGED_HOOK_TIMEOUT_MILLISECONDS = MANAGED_HOOK_TIMEOUT_SECONDS * 1000 + +// Claude-shaped schemas nest command hooks; Cursor puts command on the definition itself. +export function buildManagedCommandHook( + command: string, + timeout = MANAGED_HOOK_TIMEOUT_SECONDS +): HookCommandConfig { + return { type: 'command', command, timeout } +} + +export function buildManagedCommandDefinition(command: string): HookDefinition { + return { command, timeout: MANAGED_HOOK_TIMEOUT_SECONDS } +} diff --git a/src/main/agent-hooks/hook-config-write-path.ts b/src/main/agent-hooks/installation/configuration/hook-config-write-path.ts similarity index 100% rename from src/main/agent-hooks/hook-config-write-path.ts rename to src/main/agent-hooks/installation/configuration/hook-config-write-path.ts diff --git a/src/main/agent-hooks/hooks-json-read.ts b/src/main/agent-hooks/installation/configuration/hooks-json-read.ts similarity index 90% rename from src/main/agent-hooks/hooks-json-read.ts rename to src/main/agent-hooks/installation/configuration/hooks-json-read.ts index 066dbe53f3e..42c125c00f6 100644 --- a/src/main/agent-hooks/hooks-json-read.ts +++ b/src/main/agent-hooks/installation/configuration/hooks-json-read.ts @@ -1,6 +1,6 @@ import { readFileSync } from 'node:fs' -import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import type { HooksConfig } from './installer-utils' +import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' +import type { HooksConfig } from './hook-config-schema' export function isPlainObject(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) diff --git a/src/main/agent-hooks/installation/configuration/hooks-json-remote.ts b/src/main/agent-hooks/installation/configuration/hooks-json-remote.ts new file mode 100644 index 00000000000..3861f7898e1 --- /dev/null +++ b/src/main/agent-hooks/installation/configuration/hooks-json-remote.ts @@ -0,0 +1,69 @@ +import { randomUUID } from 'node:crypto' +import type { SFTPWrapper } from 'ssh2' +import type { HooksConfig } from './hook-config-schema' +import { parseHooksJsonText } from './hooks-json-read' +import { + DEFAULT_REMOTE_CONFIG_MODE, + readFile, + writeFile, + getRemoteFileModeOrDefault, + rename, + unlink, + chmod, + mkdirpRemote, + dirnamePosix, + isNoEntryError +} from '../remote/hook-sftp-operations' + +/** Null means invalid JSON, {} means missing; propagate other I/O failures. */ +export async function readHooksJsonRemote( + sftp: SFTPWrapper, + remotePath: string +): Promise { + let body: string + try { + body = await readFile(sftp, remotePath) + } catch (err) { + if (isNoEntryError(err)) { + return {} + } + throw err + } + return parseHooksJsonText(body) +} + +/** Atomically replace the remote config without rotating local-style backups. */ +export async function writeHooksJsonRemote( + sftp: SFTPWrapper, + remotePath: string, + config: Record, + // JSONC callers can supply text edited in place. + options?: { serialized?: string } +): Promise { + const dir = dirnamePosix(remotePath) + await mkdirpRemote(sftp, dir) + const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` + // Preserve mtime and inode on repeated installs. + try { + const existing = await readFile(sftp, remotePath) + if (existing === serialized) { + return + } + } catch { + // Retry through the write path after a failed read. + } + // Atomic replacement prevents interrupted writes from truncating live settings. + const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` + try { + const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) + await writeFile(sftp, tmp, serialized, mode) + await chmod(sftp, tmp, mode) + await rename(sftp, tmp, remotePath) + } finally { + try { + await unlink(sftp, tmp) + } catch { + // Cleanup is best effort. + } + } +} diff --git a/src/main/agent-hooks/hooks-json-write-async.ts b/src/main/agent-hooks/installation/configuration/hooks-json-write-async.ts similarity index 100% rename from src/main/agent-hooks/hooks-json-write-async.ts rename to src/main/agent-hooks/installation/configuration/hooks-json-write-async.ts diff --git a/src/main/agent-hooks/installation/configuration/hooks-json-write.ts b/src/main/agent-hooks/installation/configuration/hooks-json-write.ts new file mode 100644 index 00000000000..caee6ca49eb --- /dev/null +++ b/src/main/agent-hooks/installation/configuration/hooks-json-write.ts @@ -0,0 +1,71 @@ +import { + existsSync, + mkdirSync, + readFileSync, + statSync, + writeFileSync, + chmodSync, + renameSync, + unlinkSync +} from 'node:fs' + +import { dirname, join } from 'node:path' + +import { randomUUID } from 'node:crypto' +import { resolveHooksJsonWritePath } from './hook-config-write-path' +import { writeRollingFileBackup } from '../../../filesystem/rolling-file-backup' + +export function writeHooksJson( + configPath: string, + // Fallback serialization accepts provider-specific JSON shapes, including nested hooks.events. + config: Record, + // JSONC callers supply edited text while retaining atomic writes and backups. + options?: { preserveMode?: boolean; defaultMode?: number; serialized?: string } +): void { + const writePath = resolveHooksJsonWritePath(configPath) + const dir = dirname(writePath) + mkdirSync(dir, { recursive: true }) + + // Unique temp paths isolate concurrent writers and preserve the original on write failure. + const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) + const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` + // Preserve owner-only permissions: agent configs can contain API keys. + const existingMode = + options?.preserveMode !== false && existsSync(writePath) + ? statSync(writePath).mode & 0o777 + : options?.defaultMode + + // Identical reinstalls must not rotate away the last recoverable backup. + if (existsSync(writePath)) { + try { + if (readFileSync(writePath, 'utf-8') === serialized) { + return + } + } catch { + // Retry through the write path after a failed read. + } + } + + try { + // Windows read-only mode could prevent deleting a failed temporary write. + const tmpMode = process.platform === 'win32' ? undefined : existingMode + writeFileSync(tmpPath, serialized, { encoding: 'utf-8', mode: tmpMode, flag: 'wx' }) + if (existingMode !== undefined && process.platform !== 'win32') { + // Preserve requested permissions even with a stricter process umask. + chmodSync(tmpPath, existingMode) + } + // Keep one prior version for recovery from a bad merge. + if (existsSync(writePath)) { + writeRollingFileBackup(writePath, `${writePath}.bak`) + } + renameSync(tmpPath, writePath) + } finally { + if (existsSync(tmpPath)) { + try { + unlinkSync(tmpPath) + } catch { + // best effort + } + } + } +} diff --git a/src/main/agent-hooks/managed-hooks-json-events.ts b/src/main/agent-hooks/installation/configuration/managed-hooks-json-events.ts similarity index 94% rename from src/main/agent-hooks/managed-hooks-json-events.ts rename to src/main/agent-hooks/installation/configuration/managed-hooks-json-events.ts index fac57d23e64..f786474bc5b 100644 --- a/src/main/agent-hooks/managed-hooks-json-events.ts +++ b/src/main/agent-hooks/installation/configuration/managed-hooks-json-events.ts @@ -1,4 +1,4 @@ -import { isPlainObject } from './installer-utils' +import { isPlainObject } from './hooks-json-read' /** Treat malformed user-edited nodes as absent events when reporting installation status. */ export function readManagedHookEventsFromJson( diff --git a/src/main/agent-hooks/managed-toml-ownership.test.ts b/src/main/agent-hooks/installation/configuration/managed-toml-ownership.test.ts similarity index 100% rename from src/main/agent-hooks/managed-toml-ownership.test.ts rename to src/main/agent-hooks/installation/configuration/managed-toml-ownership.test.ts diff --git a/src/main/agent-hooks/managed-toml-ownership.ts b/src/main/agent-hooks/installation/configuration/managed-toml-ownership.ts similarity index 100% rename from src/main/agent-hooks/managed-toml-ownership.ts rename to src/main/agent-hooks/installation/configuration/managed-toml-ownership.ts diff --git a/src/main/agent-hooks/install-telemetry.ts b/src/main/agent-hooks/installation/install-telemetry.ts similarity index 63% rename from src/main/agent-hooks/install-telemetry.ts rename to src/main/agent-hooks/installation/install-telemetry.ts index 5502c07bb8c..b64fa1fce86 100644 --- a/src/main/agent-hooks/install-telemetry.ts +++ b/src/main/agent-hooks/installation/install-telemetry.ts @@ -1,6 +1,6 @@ -import { errnoCodeOrUnknown } from '../../shared/errno-code' -import type { HookInstallAgent } from '../../shared/telemetry-events' -import { track } from '../telemetry/client' +import { errnoCodeOrUnknown } from '../../../shared/errno-code' +import type { HookInstallAgent } from '../../../shared/telemetry-daemon-event-schemas' +import { track } from '../../telemetry/client' export function recordManagedHookInstallFailure(agent: HookInstallAgent, error: unknown): void { try { diff --git a/src/main/agent-hooks/local-agent-cli-presence.test.ts b/src/main/agent-hooks/installation/local-agent-cli-presence.test.ts similarity index 94% rename from src/main/agent-hooks/local-agent-cli-presence.test.ts rename to src/main/agent-hooks/installation/local-agent-cli-presence.test.ts index 56d19bac881..723e0fdb83c 100644 --- a/src/main/agent-hooks/local-agent-cli-presence.test.ts +++ b/src/main/agent-hooks/installation/local-agent-cli-presence.test.ts @@ -2,13 +2,13 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { ManagedAgentHookTarget } from '../../shared/managed-agent-hook-targets' +import type { ManagedAgentHookTarget } from '../../../shared/managed-agent-hook-targets' import { detectLocalManagedAgentCliPresence } from './local-agent-cli-presence' const { mergePersistedWindowsPathAsyncMock } = vi.hoisted(() => ({ mergePersistedWindowsPathAsyncMock: vi.fn(async (_env: NodeJS.ProcessEnv) => undefined) })) -vi.mock('../pty/environment/windows-environment-path', () => ({ +vi.mock('../../pty/environment/windows-environment-path', () => ({ mergePersistedWindowsPathAsync: mergePersistedWindowsPathAsyncMock })) diff --git a/src/main/agent-hooks/local-agent-cli-presence.ts b/src/main/agent-hooks/installation/local-agent-cli-presence.ts similarity index 91% rename from src/main/agent-hooks/local-agent-cli-presence.ts rename to src/main/agent-hooks/installation/local-agent-cli-presence.ts index 76d44cf188b..4533059fcf3 100644 --- a/src/main/agent-hooks/local-agent-cli-presence.ts +++ b/src/main/agent-hooks/installation/local-agent-cli-presence.ts @@ -2,22 +2,22 @@ import { constants } from 'node:fs' import { access, stat } from 'node:fs/promises' import { homedir } from 'node:os' import path from 'node:path' -import type { AgentHookTarget } from '../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { AgentHookTarget } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' import { extractExecutableToken, hasPathSeparatorToken, isSafeExecutableBasename -} from '../../shared/managed-agent-command-token' -import type { ManagedAgentHookTarget } from '../../shared/managed-agent-hook-targets' -import type { GlobalSettings } from '../../shared/global-settings-types' -import { mapWithConcurrency } from '../../shared/map-with-concurrency' -import { hydrateShellPath, mergePathSegments } from '../startup/hydrate-shell-path' -import { mergePersistedWindowsPathAsync } from '../pty/environment/windows-environment-path' -import { resolvePathEnvKey } from '../pty/environment/windows-path-segment-merge' +} from '../../../shared/managed-agent-command-token' +import type { ManagedAgentHookTarget } from '../../../shared/managed-agent-hook-targets' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import { mapWithConcurrency } from '../../../shared/map-with-concurrency' +import { hydrateShellPath, mergePathSegments } from '../../startup/hydrate-shell-path' +import { mergePersistedWindowsPathAsync } from '../../pty/environment/windows-environment-path' +import { resolvePathEnvKey } from '../../pty/environment/windows-path-segment-merge' import { isUnderWindowsDriveMount, readGuestWindowsDriveMounts -} from '../ipc/wsl-guest-windows-drive-path' +} from '../../ipc/wsl-guest-windows-drive-path' export type LocalCliPresenceState = 'found' | 'missing' | 'unknown' export type LocalCliPresenceByAgent = Partial< diff --git a/src/main/agent-hooks/managed-hook-install-lock.test.ts b/src/main/agent-hooks/installation/locking/managed-hook-install-lock.test.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-install-lock.test.ts rename to src/main/agent-hooks/installation/locking/managed-hook-install-lock.test.ts diff --git a/src/main/agent-hooks/managed-hook-install-lock.ts b/src/main/agent-hooks/installation/locking/managed-hook-install-lock.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-install-lock.ts rename to src/main/agent-hooks/installation/locking/managed-hook-install-lock.ts diff --git a/src/main/agent-hooks/managed-hook-lock-claims.ts b/src/main/agent-hooks/installation/locking/managed-hook-lock-claims.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-lock-claims.ts rename to src/main/agent-hooks/installation/locking/managed-hook-lock-claims.ts diff --git a/src/main/agent-hooks/managed-hook-lock-records.ts b/src/main/agent-hooks/installation/locking/managed-hook-lock-records.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-lock-records.ts rename to src/main/agent-hooks/installation/locking/managed-hook-lock-records.ts diff --git a/src/main/agent-hooks/managed-hook-owner-identity.ts b/src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-owner-identity.ts rename to src/main/agent-hooks/installation/locking/managed-hook-owner-identity.ts diff --git a/src/main/agent-hooks/managed-agent-hook-controls.test.ts b/src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts similarity index 99% rename from src/main/agent-hooks/managed-agent-hook-controls.test.ts rename to src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts index 3bbd19f82e8..5a2cf7af25e 100644 --- a/src/main/agent-hooks/managed-agent-hook-controls.test.ts +++ b/src/main/agent-hooks/installation/managed-agent-hook-controls.test.ts @@ -19,7 +19,7 @@ vi.mock('./local-agent-cli-presence', () => ({ detectLocalManagedAgentCliPresence: mocks.detect })) -vi.mock('../claude/claude-hook-event-versions', () => ({ +vi.mock('../../claude/claude-hook-event-versions', () => ({ probeClaudeCliVersion: mocks.probeClaudeVersion })) diff --git a/src/main/agent-hooks/managed-agent-hook-controls.ts b/src/main/agent-hooks/installation/managed-agent-hook-controls.ts similarity index 94% rename from src/main/agent-hooks/managed-agent-hook-controls.ts rename to src/main/agent-hooks/installation/managed-agent-hook-controls.ts index 00868c771cb..76e1e46da60 100644 --- a/src/main/agent-hooks/managed-agent-hook-controls.ts +++ b/src/main/agent-hooks/installation/managed-agent-hook-controls.ts @@ -1,18 +1,18 @@ import type { AgentHookInstallStatus, AgentHookTarget -} from '../../shared/agent-hook-listener/configuration/agent-hook-types' +} from '../../../shared/agent-hook-listener/configuration/agent-hook-types' import { getManagedAgentHookTarget, isManagedAgentHookTarget -} from '../../shared/managed-agent-hook-targets' -import { normalizeDisabledTuiAgents } from '../../shared/agent-launch/catalog/tui-agent-selection' -import type { GlobalSettings } from '../../shared/global-settings-types' +} from '../../../shared/managed-agent-hook-targets' +import { normalizeDisabledTuiAgents } from '../../../shared/agent-launch/catalog/tui-agent-selection' +import type { GlobalSettings } from '../../../shared/global-settings-types' import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent -} from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { probeClaudeCliVersion } from '../claude/claude-hook-event-versions' +} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { probeClaudeCliVersion } from '../../claude/claude-hook-event-versions' import { detectLocalManagedAgentCliPresence } from './local-agent-cli-presence' import { MANAGED_AGENT_HOOK_ASYNC_REMOVERS, diff --git a/src/main/agent-hooks/managed-agent-hook-registry.ts b/src/main/agent-hooks/installation/managed-agent-hook-registry.ts similarity index 79% rename from src/main/agent-hooks/managed-agent-hook-registry.ts rename to src/main/agent-hooks/installation/managed-agent-hook-registry.ts index 9b272d5d420..91feaeae5d8 100644 --- a/src/main/agent-hooks/managed-agent-hook-registry.ts +++ b/src/main/agent-hooks/installation/managed-agent-hook-registry.ts @@ -1,27 +1,27 @@ -import { codebuddyHookService } from '../codebuddy/hook-service' -import { qwenCodeHookService } from '../qwen-code/hook-service' -import { qoderCnHookService, qoderHookService } from '../qoder/hook-service' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import type { HookInstallAgent } from '../../shared/telemetry-events' -import { ampHookService } from '../amp/hook-service' -import { antigravityHookService } from '../antigravity/hook-service' -import { claudeHookService } from '../claude/hook-service' -import { codexHookService } from '../codex/hooks/installation/hook-service' -import { commandCodeHookService } from '../command-code/hook-service' -import { copilotHookService } from '../copilot/hook-service' -import { cursorHookService } from '../cursor/hook-service' -import { devinHookService } from '../devin/hook-service' -import { dshHookService } from '../dsh/hook-service' -import { droidHookService } from '../droid/hook-service' -import { geminiHookService } from '../gemini/hook-service' -import { grokHookService } from '../grok/hook-service' -import { hermesHookService } from '../hermes/hook-service' -import { jcodeHookService } from '../jcode/hook-service' -import { kimiHookService } from '../kimi/hook-service' -import { kiroHookService } from '../kiro/hook-service' -import { museHookService } from '../muse/hook-service' -import { openClaudeHookService } from '../openclaude/hook-service' -import { zcodeHookService } from '../zcode/hook-service' +import { codebuddyHookService } from '../../codebuddy/hook-service' +import { qwenCodeHookService } from '../../qwen-code/hook-service' +import { qoderCnHookService, qoderHookService } from '../../qoder/hook-service' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { HookInstallAgent } from '../../../shared/telemetry-daemon-event-schemas' +import { ampHookService } from '../../amp/hook-service' +import { antigravityHookService } from '../../antigravity/hook-service' +import { claudeHookService } from '../../claude/hook-service' +import { codexHookService } from '../../codex/hooks/installation/hook-service' +import { commandCodeHookService } from '../../command-code/hook-service' +import { copilotHookService } from '../../copilot/hook-service' +import { cursorHookService } from '../../cursor/hook-service' +import { devinHookService } from '../../devin/hook-service' +import { dshHookService } from '../../dsh/hook-service' +import { droidHookService } from '../../droid/hook-service' +import { geminiHookService } from '../../gemini/hook-service' +import { grokHookService } from '../../grok/hook-service' +import { hermesHookService } from '../../hermes/hook-service' +import { jcodeHookService } from '../../jcode/hook-service' +import { kimiHookService } from '../../kimi/hook-service' +import { kiroHookService } from '../../kiro/hook-service' +import { museHookService } from '../../muse/hook-service' +import { openClaudeHookService } from '../../openclaude/hook-service' +import { zcodeHookService } from '../../zcode/hook-service' export type ManagedAgentHookInstallOptions = { userInitiated?: boolean; cliVersion?: string } export type ManagedAgentHookInstaller = readonly [ diff --git a/src/main/agent-hooks/managed-agent-hook-startup.ts b/src/main/agent-hooks/installation/managed-agent-hook-startup.ts similarity index 100% rename from src/main/agent-hooks/managed-agent-hook-startup.ts rename to src/main/agent-hooks/installation/managed-agent-hook-startup.ts diff --git a/src/main/agent-hooks/managed-hook-detection-commands.ts b/src/main/agent-hooks/installation/managed-hook-detection-commands.ts similarity index 77% rename from src/main/agent-hooks/managed-hook-detection-commands.ts rename to src/main/agent-hooks/installation/managed-hook-detection-commands.ts index 274a43a930d..0378b0aba67 100644 --- a/src/main/agent-hooks/managed-hook-detection-commands.ts +++ b/src/main/agent-hooks/installation/managed-hook-detection-commands.ts @@ -1,13 +1,13 @@ -import type { AgentHookTarget } from '../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { AgentHookTarget } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' import { extractExecutableToken, isSafeOverrideExecutableToken -} from '../../shared/managed-agent-command-token' -import { MANAGED_AGENT_HOOK_TARGETS } from '../../shared/managed-agent-hook-targets' -import { normalizeDisabledTuiAgents } from '../../shared/agent-launch/catalog/tui-agent-selection' -import type { GlobalSettings } from '../../shared/global-settings-types' -import type { TuiAgentDetectionCommand } from '../../shared/agent-launch/catalog/tui-agent-detection-commands' -import { parseClaudeCliVersionOutput } from '../claude/claude-hook-event-versions' +} from '../../../shared/managed-agent-command-token' +import { MANAGED_AGENT_HOOK_TARGETS } from '../../../shared/managed-agent-hook-targets' +import { normalizeDisabledTuiAgents } from '../../../shared/agent-launch/catalog/tui-agent-selection' +import type { GlobalSettings } from '../../../shared/global-settings-types' +import type { TuiAgentDetectionCommand } from '../../../shared/agent-launch/catalog/tui-agent-detection-commands' +import { parseClaudeCliVersionOutput } from '../../claude/claude-hook-event-versions' export type ManagedHookDetectionSettings = Partial< Pick< diff --git a/src/main/agent-hooks/opencode-plugin-settings.ts b/src/main/agent-hooks/installation/opencode-plugin-settings.ts similarity index 85% rename from src/main/agent-hooks/opencode-plugin-settings.ts rename to src/main/agent-hooks/installation/opencode-plugin-settings.ts index 8514cba992b..6818153fb7a 100644 --- a/src/main/agent-hooks/opencode-plugin-settings.ts +++ b/src/main/agent-hooks/installation/opencode-plugin-settings.ts @@ -1,5 +1,5 @@ -import type { PluginSources } from '../../wsl-guest/plugin-overlay' -import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' +import { isAgentStatusHooksEnabledForAgent } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' function enabled(settings: ManagedHookDetectionSettings, agent: 'opencode' | 'opencode2'): boolean { diff --git a/src/main/agent-hooks/remote-managed-hook-installers.ts b/src/main/agent-hooks/installation/remote-managed-hook-installers.ts similarity index 77% rename from src/main/agent-hooks/remote-managed-hook-installers.ts rename to src/main/agent-hooks/installation/remote-managed-hook-installers.ts index d73da317035..c95c3c871a9 100644 --- a/src/main/agent-hooks/remote-managed-hook-installers.ts +++ b/src/main/agent-hooks/installation/remote-managed-hook-installers.ts @@ -1,30 +1,30 @@ -import { codebuddyHookService } from '../codebuddy/hook-service' -import { qwenCodeHookService } from '../qwen-code/hook-service' -import { qoderCnHookService, qoderHookService } from '../qoder/hook-service' +import { codebuddyHookService } from '../../codebuddy/hook-service' +import { qwenCodeHookService } from '../../qwen-code/hook-service' +import { qoderCnHookService, qoderHookService } from '../../qoder/hook-service' import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus, AgentHookTarget -} from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { ampHookService } from '../amp/hook-service' -import { claudeHookService } from '../claude/hook-service' -import { codexHookService } from '../codex/hooks/installation/hook-service' -import { geminiHookService } from '../gemini/hook-service' -import { antigravityHookService } from '../antigravity/hook-service' -import { cursorHookService } from '../cursor/hook-service' -import { commandCodeHookService } from '../command-code/hook-service' -import { copilotHookService } from '../copilot/hook-service' -import { devinHookService } from '../devin/hook-service' -import { droidHookService } from '../droid/hook-service' -import { grokHookService } from '../grok/hook-service' -import { hermesHookService } from '../hermes/hook-service' -import { jcodeHookService } from '../jcode/hook-service' -import { kimiHookService } from '../kimi/hook-service' -import { kiroHookService } from '../kiro/hook-service' -import { dshHookService } from '../dsh/hook-service' -import { museHookService } from '../muse/hook-service' -import { zcodeHookService } from '../zcode/hook-service' -import { openClaudeHookService } from '../openclaude/hook-service' +} from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import { ampHookService } from '../../amp/hook-service' +import { claudeHookService } from '../../claude/hook-service' +import { codexHookService } from '../../codex/hooks/installation/hook-service' +import { geminiHookService } from '../../gemini/hook-service' +import { antigravityHookService } from '../../antigravity/hook-service' +import { cursorHookService } from '../../cursor/hook-service' +import { commandCodeHookService } from '../../command-code/hook-service' +import { copilotHookService } from '../../copilot/hook-service' +import { devinHookService } from '../../devin/hook-service' +import { droidHookService } from '../../droid/hook-service' +import { grokHookService } from '../../grok/hook-service' +import { hermesHookService } from '../../hermes/hook-service' +import { jcodeHookService } from '../../jcode/hook-service' +import { kimiHookService } from '../../kimi/hook-service' +import { kiroHookService } from '../../kiro/hook-service' +import { dshHookService } from '../../dsh/hook-service' +import { museHookService } from '../../muse/hook-service' +import { zcodeHookService } from '../../zcode/hook-service' +import { openClaudeHookService } from '../../openclaude/hook-service' export type RemoteManagedHookInstallOptions = { /** Redirected runtime CODEX_HOME, including managed WSL homes. */ diff --git a/src/main/agent-hooks/installer-utils-remote.ts b/src/main/agent-hooks/installation/remote/hook-sftp-operations.ts similarity index 51% rename from src/main/agent-hooks/installer-utils-remote.ts rename to src/main/agent-hooks/installation/remote/hook-sftp-operations.ts index 4ac7f9c655e..fb342c59d4d 100644 --- a/src/main/agent-hooks/installer-utils-remote.ts +++ b/src/main/agent-hooks/installation/remote/hook-sftp-operations.ts @@ -1,160 +1,9 @@ -// Share parsing and merge rules with local installation; replace only filesystem operations. - -import { randomUUID } from 'node:crypto' import type { SFTPWrapper, FileEntryWithStats } from 'ssh2' -import type { HooksConfig } from './installer-utils' -import { parseHooksJsonText } from './hooks-json-read' +export const DEFAULT_REMOTE_CONFIG_MODE = 0o600 -const DEFAULT_REMOTE_CONFIG_MODE = 0o600 const REMOTE_SFTP_OPERATION_TIMEOUT_MS = 10_000 -/** Null means invalid JSON, {} means missing; propagate other I/O failures. */ -export async function readHooksJsonRemote( - sftp: SFTPWrapper, - remotePath: string -): Promise { - let body: string - try { - body = await readFile(sftp, remotePath) - } catch (err) { - if (isNoEntryError(err)) { - return {} - } - throw err - } - return parseHooksJsonText(body) -} - -/** Atomically replace the remote config without rotating local-style backups. */ -export async function writeHooksJsonRemote( - sftp: SFTPWrapper, - remotePath: string, - config: Record, - // JSONC callers can supply text edited in place. - options?: { serialized?: string } -): Promise { - const dir = dirnamePosix(remotePath) - await mkdirpRemote(sftp, dir) - const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` - // Preserve mtime and inode on repeated installs. - try { - const existing = await readFile(sftp, remotePath) - if (existing === serialized) { - return - } - } catch { - // Retry through the write path after a failed read. - } - // Atomic replacement prevents interrupted writes from truncating live settings. - const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` - try { - const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) - await writeFile(sftp, tmp, serialized, mode) - await chmod(sftp, tmp, mode) - await rename(sftp, tmp, remotePath) - } finally { - try { - await unlink(sftp, tmp) - } catch { - // Cleanup is best effort. - } - } -} - -/** POSIX SSH targets only: paths and script payloads follow POSIX conventions. */ -export async function writeManagedScriptRemote( - sftp: SFTPWrapper, - remotePath: string, - content: string -): Promise { - const dir = dirnamePosix(remotePath) - await mkdirpRemote(sftp, dir) - try { - const existing = await readFile(sftp, remotePath) - if (existing === content) { - await chmod(sftp, remotePath, 0o755) - return - } - } catch { - // Retry through the atomic write path after a failed read. - } - - // Publish only a complete executable script; existing configs may invoke it during reinstall. - const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` - try { - await writeFile(sftp, tmp, content, 0o755) - await chmod(sftp, tmp, 0o755) - await rename(sftp, tmp, remotePath) - } finally { - try { - await unlink(sftp, tmp) - } catch { - // Cleanup is best effort. - } - } -} - -export async function readTextFileRemote( - sftp: SFTPWrapper, - remotePath: string -): Promise { - try { - return await readFile(sftp, remotePath) - } catch (err) { - if (isNoEntryError(err)) { - return null - } - throw err - } -} - -/** Null means the directory is missing; propagate other I/O failures. */ -export async function listRemoteDirectory( - sftp: SFTPWrapper, - remotePath: string -): Promise { - try { - return (await readdir(sftp, remotePath)).map((entry) => entry.filename) - } catch (err) { - if (isNoEntryError(err)) { - return null - } - throw err - } -} - -export async function writeTextFileRemoteAtomic( - sftp: SFTPWrapper, - remotePath: string, - content: string -): Promise { - const dir = dirnamePosix(remotePath) - await mkdirpRemote(sftp, dir) - try { - const existing = await readFile(sftp, remotePath) - if (existing === content) { - return - } - } catch { - // Retry through the atomic write path after a failed read. - } - - const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` - try { - const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) - await writeFile(sftp, tmp, content, mode) - await chmod(sftp, tmp, mode) - await rename(sftp, tmp, remotePath) - } finally { - try { - await unlink(sftp, tmp) - } catch { - // Cleanup is best effort. - } - } -} - function sftpOperation( label: string, run: (callback: (err: unknown, value?: T) => void) => void @@ -194,14 +43,14 @@ function sftpOperation( }) } -async function readFile(sftp: SFTPWrapper, remotePath: string): Promise { +export async function readFile(sftp: SFTPWrapper, remotePath: string): Promise { const data = await sftpOperation(`readFile ${remotePath}`, (callback) => { sftp.readFile(remotePath, 'utf8', callback) }) return typeof data === 'string' ? data : data.toString('utf8') } -async function writeFile( +export async function writeFile( sftp: SFTPWrapper, remotePath: string, content: string, @@ -221,7 +70,7 @@ async function statMode(sftp: SFTPWrapper, remotePath: string): Promise return stats.mode & 0o7777 } -async function getRemoteFileModeOrDefault( +export async function getRemoteFileModeOrDefault( sftp: SFTPWrapper, remotePath: string, defaultMode: number @@ -236,7 +85,7 @@ async function getRemoteFileModeOrDefault( } } -async function rename(sftp: SFTPWrapper, src: string, dst: string): Promise { +export async function rename(sftp: SFTPWrapper, src: string, dst: string): Promise { if (typeof sftp.ext_openssh_rename === 'function') { try { await renameOpenSsh(sftp, src, dst) @@ -264,19 +113,22 @@ async function renameOpenSsh(sftp: SFTPWrapper, src: string, dst: string): Promi }) } -async function unlink(sftp: SFTPWrapper, remotePath: string): Promise { +export async function unlink(sftp: SFTPWrapper, remotePath: string): Promise { await sftpOperation(`unlink ${remotePath}`, (callback) => { sftp.unlink(remotePath, callback) }) } -async function chmod(sftp: SFTPWrapper, remotePath: string, mode: number): Promise { +export async function chmod(sftp: SFTPWrapper, remotePath: string, mode: number): Promise { await sftpOperation(`chmod ${remotePath}`, (callback) => { sftp.chmod(remotePath, mode, callback) }) } -async function readdir(sftp: SFTPWrapper, remotePath: string): Promise { +export async function readdir( + sftp: SFTPWrapper, + remotePath: string +): Promise { return await sftpOperation(`readdir ${remotePath}`, (callback) => { sftp.readdir(remotePath, callback) }) @@ -288,7 +140,7 @@ async function mkdir(sftp: SFTPWrapper, remotePath: string): Promise { }) } -async function mkdirpRemote(sftp: SFTPWrapper, remotePath: string): Promise { +export async function mkdirpRemote(sftp: SFTPWrapper, remotePath: string): Promise { if (remotePath === '/' || remotePath === '' || remotePath === '.') { return } @@ -312,7 +164,7 @@ async function mkdirpRemote(sftp: SFTPWrapper, remotePath: string): Promise { + try { + return await readFile(sftp, remotePath) + } catch (err) { + if (isNoEntryError(err)) { + return null + } + throw err + } +} + +/** Null means the directory is missing; propagate other I/O failures. */ +export async function listRemoteDirectory( + sftp: SFTPWrapper, + remotePath: string +): Promise { + try { + return (await readdir(sftp, remotePath)).map((entry) => entry.filename) + } catch (err) { + if (isNoEntryError(err)) { + return null + } + throw err + } +} + +export async function writeTextFileRemoteAtomic( + sftp: SFTPWrapper, + remotePath: string, + content: string +): Promise { + const dir = dirnamePosix(remotePath) + await mkdirpRemote(sftp, dir) + try { + const existing = await readFile(sftp, remotePath) + if (existing === content) { + return + } + } catch { + // Retry through the atomic write path after a failed read. + } + + const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` + try { + const mode = await getRemoteFileModeOrDefault(sftp, remotePath, DEFAULT_REMOTE_CONFIG_MODE) + await writeFile(sftp, tmp, content, mode) + await chmod(sftp, tmp, mode) + await rename(sftp, tmp, remotePath) + } finally { + try { + await unlink(sftp, tmp) + } catch { + // Cleanup is best effort. + } + } +} diff --git a/src/main/agent-hooks/agent-hook-memory-sftp.test-fixture.ts b/src/main/agent-hooks/installation/remote/testing/agent-hook-memory-sftp.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/agent-hook-memory-sftp.test-fixture.ts rename to src/main/agent-hooks/installation/remote/testing/agent-hook-memory-sftp.test-fixture.ts diff --git a/src/main/agent-hooks/managed-hook-local-filesystem.test-fixture.ts b/src/main/agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/managed-hook-local-filesystem.test-fixture.ts rename to src/main/agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture.ts diff --git a/src/main/agent-hooks/claude-background-job-guard.ts b/src/main/agent-hooks/installation/scripts/claude-background-job-guard.ts similarity index 100% rename from src/main/agent-hooks/claude-background-job-guard.ts rename to src/main/agent-hooks/installation/scripts/claude-background-job-guard.ts diff --git a/src/main/agent-hooks/cursor-replay-guard.test.ts b/src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts similarity index 77% rename from src/main/agent-hooks/cursor-replay-guard.test.ts rename to src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts index 82802ffd057..413ae77c29b 100644 --- a/src/main/agent-hooks/cursor-replay-guard.test.ts +++ b/src/main/agent-hooks/installation/scripts/cursor-replay-guard.test.ts @@ -2,10 +2,10 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } })) -import { runVendorHook } from './vendor-hook-delivery.test-fixture' +import { runVendorHook } from './testing/vendor-hook-delivery.test-fixture' -import { getManagedScript as getClaudeManagedScript } from '../claude/hook-service' -import { getManagedScript as getCursorManagedScript } from '../cursor/hook-script' +import { getManagedScript as getClaudeManagedScript } from '../../../claude/hook-service' +import { getManagedScript as getCursorManagedScript } from '../../../cursor/hook-script' const CLAUDE_SCRIPT_OPTIONS = { skipWhenDevinImportsClaude: true, diff --git a/src/main/agent-hooks/cursor-replay-guard.ts b/src/main/agent-hooks/installation/scripts/cursor-replay-guard.ts similarity index 100% rename from src/main/agent-hooks/cursor-replay-guard.ts rename to src/main/agent-hooks/installation/scripts/cursor-replay-guard.ts diff --git a/src/main/agent-hooks/grok-replay-guard.test.ts b/src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts similarity index 85% rename from src/main/agent-hooks/grok-replay-guard.test.ts rename to src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts index 78407c2929e..b21f154bc0d 100644 --- a/src/main/agent-hooks/grok-replay-guard.test.ts +++ b/src/main/agent-hooks/installation/scripts/grok-replay-guard.test.ts @@ -2,9 +2,9 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } })) -import { getManagedScript as getClaudeManagedScript } from '../claude/hook-service' -import { getManagedScript as getCursorManagedScript } from '../cursor/hook-script' -import { runVendorHook } from './vendor-hook-delivery.test-fixture' +import { getManagedScript as getClaudeManagedScript } from '../../../claude/hook-service' +import { getManagedScript as getCursorManagedScript } from '../../../cursor/hook-script' +import { runVendorHook } from './testing/vendor-hook-delivery.test-fixture' const CLAUDE_SCRIPT_OPTIONS = { skipWhenDevinImportsClaude: true, diff --git a/src/main/agent-hooks/grok-replay-guard.ts b/src/main/agent-hooks/installation/scripts/grok-replay-guard.ts similarity index 100% rename from src/main/agent-hooks/grok-replay-guard.ts rename to src/main/agent-hooks/installation/scripts/grok-replay-guard.ts diff --git a/src/main/agent-hooks/hook-post-command.ts b/src/main/agent-hooks/installation/scripts/hook-post-command.ts similarity index 94% rename from src/main/agent-hooks/hook-post-command.ts rename to src/main/agent-hooks/installation/scripts/hook-post-command.ts index 8cac17f0526..b0c6ce3e807 100644 --- a/src/main/agent-hooks/hook-post-command.ts +++ b/src/main/agent-hooks/installation/scripts/hook-post-command.ts @@ -1,6 +1,6 @@ -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { ORCA_HOOK_RAW_JSON_TRANSPORT } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { AGENT_HOOK_METADATA_CACHE_DIR } from '../../shared/agent-hook-listener/transport/agent-hook-spool' +import type { AgentHookSource } from '../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { ORCA_HOOK_RAW_JSON_TRANSPORT } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' +import { AGENT_HOOK_METADATA_CACHE_DIR } from '../../../../shared/agent-hook-listener/transport/agent-hook-spool' // Older curl needs C numeric parsing; keep the parent script's UTF-8 locale unchanged. export function posixCurlCommand(curlCommand = 'curl'): string { diff --git a/src/main/agent-hooks/hook-process-capture.test.ts b/src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts similarity index 85% rename from src/main/agent-hooks/hook-process-capture.test.ts rename to src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts index 6671f77ecea..bc749510993 100644 --- a/src/main/agent-hooks/hook-process-capture.test.ts +++ b/src/main/agent-hooks/installation/scripts/hook-process-capture.test.ts @@ -3,10 +3,10 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { runProcess } from '@orca/process-host' -import { wrapRuntimeHomeHookCommand } from './runtime-home-hook-command' +import { wrapRuntimeHomeHookCommand } from '../commands/runtime-home-hook-command' import { buildHookProcessCapture } from './hook-process-capture' -import { readAgentProcessIdentity } from '../../shared/agent-status/process/agent-process-presence' -import { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { readAgentProcessIdentity } from '../../../../shared/agent-status/process/agent-process-presence' +import { probeAgentProcessPresence } from '../../../../shared/agent-status/process/agent-process-presence-probe' describe('Claude outer hook process capture', () => { it.skipIf(process.platform === 'win32').each([undefined, 'Asia/Tokyo'])( diff --git a/src/main/agent-hooks/hook-process-capture.ts b/src/main/agent-hooks/installation/scripts/hook-process-capture.ts similarity index 100% rename from src/main/agent-hooks/hook-process-capture.ts rename to src/main/agent-hooks/installation/scripts/hook-process-capture.ts diff --git a/src/main/agent-hooks/hook-script-outside-orca.test.ts b/src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts similarity index 98% rename from src/main/agent-hooks/hook-script-outside-orca.test.ts rename to src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts index 25c0abe3991..b94fcd9ac5a 100644 --- a/src/main/agent-hooks/hook-script-outside-orca.test.ts +++ b/src/main/agent-hooks/installation/scripts/hook-script-outside-orca.test.ts @@ -11,7 +11,7 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { getManagedScript } from '../codex/hooks/definitions/codex-hook-script' +import { getManagedScript } from '../../../codex/hooks/definitions/codex-hook-script' import { buildPosixHookSpoolLines } from './hook-stdin-contract' const roots: string[] = [] diff --git a/src/main/agent-hooks/hook-stdin-contract.ts b/src/main/agent-hooks/installation/scripts/hook-stdin-contract.ts similarity index 100% rename from src/main/agent-hooks/hook-stdin-contract.ts rename to src/main/agent-hooks/installation/scripts/hook-stdin-contract.ts diff --git a/src/main/agent-hooks/locked-executable-rename.test.ts b/src/main/agent-hooks/installation/scripts/locked-executable-rename.test.ts similarity index 100% rename from src/main/agent-hooks/locked-executable-rename.test.ts rename to src/main/agent-hooks/installation/scripts/locked-executable-rename.test.ts diff --git a/src/main/agent-hooks/locked-executable-rename.ts b/src/main/agent-hooks/installation/scripts/locked-executable-rename.ts similarity index 96% rename from src/main/agent-hooks/locked-executable-rename.ts rename to src/main/agent-hooks/installation/scripts/locked-executable-rename.ts index 091fbf83e3f..d45c90576ca 100644 --- a/src/main/agent-hooks/locked-executable-rename.ts +++ b/src/main/agent-hooks/installation/scripts/locked-executable-rename.ts @@ -1,6 +1,6 @@ import { existsSync, renameSync, rmSync } from 'node:fs' import { rename, rm, stat } from 'node:fs/promises' -import { isPermissionError } from '../filesystem/permission-errors' +import { isPermissionError } from '../../../filesystem/permission-errors' /** Windows permits renaming a running executable aside so a new build can take its path. */ export function getLockedExecutableAsidePath(targetPath: string): string { diff --git a/src/main/agent-hooks/installation/scripts/managed-hook-script-path.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-path.ts new file mode 100644 index 00000000000..d8bb5590c93 --- /dev/null +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-path.ts @@ -0,0 +1,7 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' + +// Parallel Orca instances must share one user-wide script path. +export function getSharedManagedScriptPath(scriptFileName: string): string { + return join(homedir(), '.orca', 'agent-hooks', scriptFileName) +} diff --git a/src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts similarity index 96% rename from src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts index 77c5b3d5be7..24fcba35e5a 100644 --- a/src/main/agent-hooks/managed-hook-script-refresh-main-thread.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh-main-thread.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import type * as NodeOsModule from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' +import { installFakeAppEnvironment } from '../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup' const state = vi.hoisted((): { home: string; syncCalls: { name: string; target: string }[] } => ({ home: '', @@ -36,7 +36,7 @@ vi.mock('node:os', async (importOriginal) => { vi.mock('electron', () => ({ app: { getPath: () => '/tmp/orca-user-data' } })) -import { MANAGED_AGENT_HOOK_SCRIPT_REFRESHERS } from './managed-agent-hook-registry' +import { MANAGED_AGENT_HOOK_SCRIPT_REFRESHERS } from '../managed-agent-hook-registry' function syncCallsUnderHome(): string[] { return state.syncCalls diff --git a/src/main/agent-hooks/managed-hook-script-refresh.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts similarity index 94% rename from src/main/agent-hooks/managed-hook-script-refresh.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts index 761d77e7bff..067f10062fc 100644 --- a/src/main/agent-hooks/managed-hook-script-refresh.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as CodexHookHashLookup from '../codex/trust/hooks/codex-hook-hash-lookup' +import type * as CodexHookHashLookup from '../../../codex/trust/hooks/codex-hook-hash-lookup' import { existsSync, chmodSync, @@ -45,11 +45,11 @@ const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) -vi.mock('../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ +vi.mock('../../../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ ...(await importOriginal()), resolveCodexHookAnswerForLaunch: async () => ( - await import('../codex/hooks/installation/hook-service-test-harness') + await import('../../../codex/hooks/installation/hook-service-test-harness') ).codexHookAnswerForTests() })) @@ -68,7 +68,7 @@ vi.mock('os', async (importOriginal) => { }) import { refreshManagedScriptIfPresent } from './managed-hook-script-refresh' -import { ClaudeHookService } from '../claude/hook-service' +import { ClaudeHookService } from '../../../claude/hook-service' describe('refreshManagedScriptIfPresent', () => { it('rewrites an existing script and refuses to create a missing one', async () => { diff --git a/src/main/agent-hooks/managed-hook-script-refresh.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.ts similarity index 95% rename from src/main/agent-hooks/managed-hook-script-refresh.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.ts index a5a78c97a56..91c4a785b17 100644 --- a/src/main/agent-hooks/managed-hook-script-refresh.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-refresh.ts @@ -1,8 +1,8 @@ import { randomUUID } from 'node:crypto' import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' -import { grantDirAclAsync } from '../windows/windows-directory-acl' -import { isPermissionError } from '../filesystem/permission-errors' +import { grantDirAclAsync } from '../../../windows/windows-directory-acl' +import { isPermissionError } from '../../../filesystem/permission-errors' import { renameOverLockedTargetAsync } from './locked-executable-rename' type ExistingScript = { exists: false } | { exists: true; content: Buffer | null } diff --git a/src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts b/src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts new file mode 100644 index 00000000000..101257aa580 --- /dev/null +++ b/src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts @@ -0,0 +1,67 @@ +import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync, unlinkSync } from 'node:fs' + +import { dirname, join } from 'node:path' + +import { randomUUID } from 'node:crypto' +import { grantDirAcl } from '../../../windows/windows-directory-acl' +import { isPermissionError } from '../../../filesystem/permission-errors' +import { renameOverLockedTarget } from './locked-executable-rename' + +// Atomic replacement protects scripts being read by in-flight hooks. +export function writeManagedScript( + scriptPath: string, + content: string | Buffer, + options: { moveLockedTargetAside?: boolean } = {} +): void { + const dir = dirname(scriptPath) + mkdirSync(dir, { recursive: true }) + + if (existsSync(scriptPath)) { + try { + if (readFileSync(scriptPath).equals(Buffer.from(content))) { + if (process.platform !== 'win32') { + chmodSync(scriptPath, 0o755) + } + return + } + } catch { + // Fall through to the atomic write path. + } + } + + const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) + try { + writeScriptWithAclRetry(tmpPath, content) + // Publish with execute permission so POSIX guards never skip a newly installed script. + if (process.platform !== 'win32') { + chmodSync(tmpPath, 0o755) + } + renameOverLockedTarget(tmpPath, scriptPath, options.moveLockedTargetAside === true) + } finally { + if (existsSync(tmpPath)) { + try { + unlinkSync(tmpPath) + } catch { + // best effort + } + } + } +} + +// Retry Windows EPERM once after repairing a restrictive directory ACL. +function writeScriptWithAclRetry(scriptPath: string, content: string | Buffer): void { + try { + writeFileSync(scriptPath, content, 'utf-8') + } catch (error) { + if (isPermissionError(error) && process.platform === 'win32') { + try { + grantDirAcl(dirname(scriptPath)) + writeFileSync(scriptPath, content, 'utf-8') + return + } catch { + // a failed grant is not actionable; re-throw the original EPERM + } + } + throw error + } +} diff --git a/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts similarity index 86% rename from src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts index 1e5ee4fd94b..c6cffd1ba59 100644 --- a/src/main/agent-hooks/managed-hook-stdin-lifecycle.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-stdin-lifecycle.test.ts @@ -1,13 +1,13 @@ // POSIX hooks drain before exit; Windows missing-context hooks may exit without owning stdin. import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as CodexHookHashLookup from '../codex/trust/hooks/codex-hook-hash-lookup' +import type * as CodexHookHashLookup from '../../../codex/trust/hooks/codex-hook-hash-lookup' import { spawnProcess } from '@orca/process-host' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as osModule from 'node:os' -import type * as NativeHookExecutableModule from './windows-native-hook-executable' +import type * as NativeHookExecutableModule from '../commands/windows-native-hook-executable' let isolatedUserDataDir = '' let previousUserDataPath: string | undefined @@ -40,16 +40,16 @@ const { homedirMock, bundledHook } = vi.hoisted(() => { }) // Test the real built executable without packaged resource lookup. -vi.mock('./windows-native-hook-executable', async (importOriginal) => ({ +vi.mock('../commands/windows-native-hook-executable', async (importOriginal) => ({ ...(await importOriginal()), resolveBundledWindowsNativeHookExecutable: () => bundledHook.path })) -vi.mock('../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ +vi.mock('../../../codex/trust/hooks/codex-hook-hash-lookup', async (importOriginal) => ({ ...(await importOriginal()), resolveCodexHookAnswerForLaunch: async () => ( - await import('../codex/hooks/installation/hook-service-test-harness') + await import('../../../codex/hooks/installation/hook-service-test-harness') ).codexHookAnswerForTests() })) @@ -67,34 +67,34 @@ vi.mock('os', async (importOriginal) => { } }) -import '../antigravity/hook-service' -import { ClaudeHookService } from '../claude/hook-service' -import '../claude/hook-settings' -import '../codex/hooks/installation/hook-service' -import '../codex/hooks/installation/codex-hook-service-implementation' -import '../command-code/hook-service' -import '../copilot/hook-service' -import '../cursor/hook-service' -import '../devin/hook-service' -import '../droid/hook-service' -import '../gemini/hook-service' -import '../grok/hook-service' -import '../kimi/hook-service' +import '../../../antigravity/hook-service' +import { ClaudeHookService } from '../../../claude/hook-service' +import '../../../claude/hook-settings' +import '../../../codex/hooks/installation/hook-service' +import '../../../codex/hooks/installation/codex-hook-service-implementation' +import '../../../command-code/hook-service' +import '../../../copilot/hook-service' +import '../../../cursor/hook-service' +import '../../../devin/hook-service' +import '../../../droid/hook-service' +import '../../../gemini/hook-service' +import '../../../grok/hook-service' +import '../../../kimi/hook-service' + +import '../../../openclaude/hook-service' -import '../openclaude/hook-service' -import './installer-utils' import { POSIX_HOOK_STDIN_READER } from './hook-stdin-contract' -import './runtime-home-hook-command' -import './agent-hook-memory-sftp.test-fixture' -import { findGitBash } from './windows-git-bash-path.test-fixture' +import '../commands/runtime-home-hook-command' +import '../remote/testing/agent-hook-memory-sftp.test-fixture' +import { findGitBash } from '../commands/testing/windows-git-bash-path.test-fixture' import { WINDOWS_POWERSHELL_WARM_UP_TIMEOUT_MS, warmWindowsEncodedPowerShell -} from './windows-powershell-warm-up.test-fixture' +} from '../commands/testing/windows-powershell-warm-up.test-fixture' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from './windows-native-hook-exe.test-fixture' +} from '../commands/testing/windows-native-hook-exe.test-fixture' const REMOTE_HOME = '/home/dev' const LARGE_PAYLOAD = Buffer.alloc(1_000_000, 'x') diff --git a/src/main/agent-hooks/managed-hook-timeout.test.ts b/src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts similarity index 95% rename from src/main/agent-hooks/managed-hook-timeout.test.ts rename to src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts index efdb31cb61b..ed6ac082b4a 100644 --- a/src/main/agent-hooks/managed-hook-timeout.test.ts +++ b/src/main/agent-hooks/installation/scripts/managed-hook-timeout.test.ts @@ -25,9 +25,9 @@ vi.mock('os', async (importOriginal) => { homedir: homedirMock.mockImplementation(actual.homedir) } }) -import '../codex/hooks/installation/hook-service' -import { CodexHookService } from '../codex/hooks/installation/codex-hook-service-implementation' -import { createAgentHookMemorySftp as createFakeSftp } from './agent-hook-memory-sftp.test-fixture' +import '../../../codex/hooks/installation/hook-service' +import { CodexHookService } from '../../../codex/hooks/installation/codex-hook-service-implementation' +import { createAgentHookMemorySftp as createFakeSftp } from '../remote/testing/agent-hook-memory-sftp.test-fixture' const REMOTE_HOME = '/home/dev' diff --git a/src/main/agent-hooks/installation/scripts/managed-script-write-remote.ts b/src/main/agent-hooks/installation/scripts/managed-script-write-remote.ts new file mode 100644 index 00000000000..4a2fc5973cc --- /dev/null +++ b/src/main/agent-hooks/installation/scripts/managed-script-write-remote.ts @@ -0,0 +1,44 @@ +import { randomUUID } from 'node:crypto' +import type { SFTPWrapper } from 'ssh2' +import { + readFile, + writeFile, + rename, + unlink, + chmod, + mkdirpRemote, + dirnamePosix +} from '../remote/hook-sftp-operations' + +/** POSIX SSH targets only: paths and script payloads follow POSIX conventions. */ +export async function writeManagedScriptRemote( + sftp: SFTPWrapper, + remotePath: string, + content: string +): Promise { + const dir = dirnamePosix(remotePath) + await mkdirpRemote(sftp, dir) + try { + const existing = await readFile(sftp, remotePath) + if (existing === content) { + await chmod(sftp, remotePath, 0o755) + return + } + } catch { + // Retry through the atomic write path after a failed read. + } + + // Publish only a complete executable script; existing configs may invoke it during reinstall. + const tmp = `${dir}/.${Date.now()}-${randomUUID()}.tmp` + try { + await writeFile(sftp, tmp, content, 0o755) + await chmod(sftp, tmp, 0o755) + await rename(sftp, tmp, remotePath) + } finally { + try { + await unlink(sftp, tmp) + } catch { + // Cleanup is best effort. + } + } +} diff --git a/src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts b/src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts similarity index 100% rename from src/main/agent-hooks/posix-hook-json-stdin-reader.test.ts rename to src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts diff --git a/src/main/agent-hooks/vendor-hook-delivery.test-fixture.ts b/src/main/agent-hooks/installation/scripts/testing/vendor-hook-delivery.test-fixture.ts similarity index 100% rename from src/main/agent-hooks/vendor-hook-delivery.test-fixture.ts rename to src/main/agent-hooks/installation/scripts/testing/vendor-hook-delivery.test-fixture.ts diff --git a/src/main/agent-hooks/installer-utils.test.ts b/src/main/agent-hooks/installation/testing/installer-contract.test.ts similarity index 95% rename from src/main/agent-hooks/installer-utils.test.ts rename to src/main/agent-hooks/installation/testing/installer-contract.test.ts index 51ef481467c..e3797f0e102 100644 --- a/src/main/agent-hooks/installer-utils.test.ts +++ b/src/main/agent-hooks/installation/testing/installer-contract.test.ts @@ -14,14 +14,12 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import { runProcessSync } from '@orca/process-host' -import { - wrapPosixHookCommand, - wrapWindowsHookCommand, - writeHooksJson, - type HooksConfig -} from './installer-utils' -import './hook-post-command' -import { wrapRuntimeHomeHookCommand } from './runtime-home-hook-command' +import { wrapPosixHookCommand } from '../commands/posix-hook-command' +import { wrapWindowsHookCommand } from '../commands/windows-hook-command' +import { writeHooksJson } from '../configuration/hooks-json-write' +import type { HooksConfig } from '../configuration/hook-config-schema' +import '../scripts/hook-post-command' +import { wrapRuntimeHomeHookCommand } from '../commands/runtime-home-hook-command' let tmpDir: string let configPath: string diff --git a/src/main/agent-hooks/installer-utils.ts b/src/main/agent-hooks/installer-utils.ts deleted file mode 100644 index d0865969033..00000000000 --- a/src/main/agent-hooks/installer-utils.ts +++ /dev/null @@ -1,359 +0,0 @@ -import { - existsSync, - mkdirSync, - readFileSync, - statSync, - writeFileSync, - chmodSync, - renameSync, - unlinkSync -} from 'node:fs' -import { homedir } from 'node:os' -import { dirname, join } from 'node:path' -import { randomUUID } from 'node:crypto' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { grantDirAcl } from '../windows/windows-directory-acl' -import { isPermissionError } from '../filesystem/permission-errors' -import { resolveHooksJsonWritePath } from './hook-config-write-path' -import { writeRollingFileBackup } from '../filesystem/rolling-file-backup' -import { renameOverLockedTarget } from './locked-executable-rename' -import { - getWindowsNativeHookAgent, - WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME -} from './windows-native-hook-executable' - -export type HookCommandConfig = { - type: 'command' - command: string - args?: string[] - timeout?: number - async?: boolean - statusMessage?: string - [key: string]: unknown -} - -export type HookDefinition = { - matcher?: string - command?: string - bash?: string - powershell?: string - hooks?: HookCommandConfig[] - [key: string]: unknown -} - -export type HooksConfig = { - hooks?: Record - [key: string]: unknown -} - -// Host-level backstop independent of curl and provider-specific timeouts. -export const MANAGED_HOOK_TIMEOUT_SECONDS = 10 -export const MANAGED_HOOK_TIMEOUT_MILLISECONDS = MANAGED_HOOK_TIMEOUT_SECONDS * 1000 - -// Claude-shaped schemas nest command hooks; Cursor puts command on the definition itself. -export function buildManagedCommandHook( - command: string, - timeout = MANAGED_HOOK_TIMEOUT_SECONDS -): HookCommandConfig { - return { type: 'command', command, timeout } -} - -export function buildManagedCommandDefinition(command: string): HookDefinition { - return { command, timeout: MANAGED_HOOK_TIMEOUT_SECONDS } -} - -export { - isPlainObject, - readHooksJson, - readHooksJsonWithRaw, - type HooksJsonSnapshot -} from './hooks-json-read' - -// Match script names so reinstalls sweep entries from old and parallel installations. -export function createManagedCommandMatcher( - scriptFileName: string -): (command: string | undefined) => boolean { - const scriptStem = scriptFileName.replace(/\.(?:cmd|ps1|sh)$/, '') - // Sweep every platform suffix after a platform switch. - const needles = [ - `agent-hooks/${scriptFileName}`, - `agent-hooks/${scriptStem}.cmd`, - `agent-hooks/${scriptStem}.ps1`, - `agent-hooks/${scriptStem}.sh` - ] - // The native executable selects its provider through argv[1]. - const nativeHook = `agent-hooks/${WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME} ${getWindowsNativeHookAgent(scriptFileName)} ` - return (command) => { - if (!command) { - return false - } - const decodedCommand = decodePowerShellEncodedCommand(command) - const searchText = decodedCommand ? `${command}\n${decodedCommand}` : command - const normalizedCommand = searchText.replaceAll('\\', '/') - return ( - needles.some((needle) => normalizedCommand.includes(needle)) || - normalizedCommand.split('\n').some((line) => `${line} `.includes(nativeHook)) - ) - } -} - -function decodePowerShellEncodedCommand(command: string): string | null { - const match = command.match(/\s-EncodedCommand\s+(\S+)/i) - if (!match) { - return null - } - try { - return Buffer.from(match[1], 'base64').toString('utf16le') - } catch { - return null - } -} - -// Parallel Orca instances must share one user-wide script path. -export function getSharedManagedScriptPath(scriptFileName: string): string { - return join(homedir(), '.orca', 'agent-hooks', scriptFileName) -} - -export { wrapPosixHookCommand } from './posix-hook-command' - -export { - wrapWindowsPowerShellEncodedCommand, - WINDOWS_POWERSHELL_HOOK_SWITCHES -} from './windows-powershell-hook-launcher' - -export { - buildWindowsHookPowerShellCommand, - isSafeUnicodeWindowsBatchHookPath, - WINDOWS_CMD_SAFE_PATH, - wrapWindowsHookCommand -} from './windows-hook-command' - -/** Extra form lines precede payload@- and must end with ` ^`. */ -export function buildWindowsAgentHookPostCommand( - source: AgentHookSource, - extraFormLines: readonly string[] = [] -): string { - // Avoid PowerShell startup; qualify curl to prevent repo-local payload interception. - return [ - `"%SystemRoot%\\System32\\curl.exe" -sS -X POST "http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}" ^`, - ' --connect-timeout 0.5 --max-time 1.5 ^', - ' -H "Content-Type: application/x-www-form-urlencoded" ^', - ' -H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%" ^', - ' --data-urlencode "paneKey=%ORCA_PANE_KEY%" ^', - ' --data-urlencode "tabId=%ORCA_TAB_ID%" ^', - ' --data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%" ^', - ' --data-urlencode "worktreeId=%ORCA_WORKTREE_ID%" ^', - ' --data-urlencode "env=%ORCA_AGENT_HOOK_ENV%" ^', - ' --data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%" ^', - ...extraFormLines, - ' --data-urlencode "payload@-" >nul 2>nul' - ].join('\r\n') -} - -// curl.exe avoids PowerShell startup and code-page corruption of UTF-8 payloads. -export function buildWindowsAgentHookCurlPostCommand(source: AgentHookSource): string { - return [ - '"%SystemRoot%\\System32\\curl.exe" -sS -X POST', - `"http://127.0.0.1:%ORCA_AGENT_HOOK_PORT%/hook/${source}"`, - '--connect-timeout 0.5 --max-time 1.5', - '-H "Content-Type: application/x-www-form-urlencoded"', - '-H "X-Orca-Agent-Hook-Token: %ORCA_AGENT_HOOK_TOKEN%"', - '--data-urlencode "paneKey=%ORCA_PANE_KEY%"', - '--data-urlencode "tabId=%ORCA_TAB_ID%"', - '--data-urlencode "launchToken=%ORCA_AGENT_LAUNCH_TOKEN%"', - '--data-urlencode "worktreeId=%ORCA_WORKTREE_ID%"', - '--data-urlencode "env=%ORCA_AGENT_HOOK_ENV%"', - '--data-urlencode "version=%ORCA_AGENT_HOOK_VERSION%"', - '--data-urlencode "payload@-"', - '>nul 2>&1' - ].join(' ') -} - -export function removeManagedCommands( - definitions: HookDefinition[], - isManagedCommand: (command: string | undefined) => boolean -): HookDefinition[] { - return definitions.flatMap((definition) => { - const directCommandKeys = ['command', 'bash', 'powershell'] as const - const directManagedKeys = directCommandKeys.filter((key) => isManagedCommand(definition[key])) - const hasNestedHooks = Array.isArray(definition.hooks) - const hasManagedNestedHook = - hasNestedHooks && - definition.hooks!.some((hook) => hookHasManagedCommand(hook, isManagedCommand)) - - if (directManagedKeys.length === 0 && !hasManagedNestedHook) { - return [definition] - } - - const nextDefinition: HookDefinition = { ...definition } - for (const key of directManagedKeys) { - delete nextDefinition[key] - } - - if (hasManagedNestedHook) { - const filteredHooks = definition.hooks!.filter( - (hook) => !hookHasManagedCommand(hook, isManagedCommand) - ) - if (filteredHooks.length > 0) { - nextDefinition.hooks = filteredHooks - } else { - delete nextDefinition.hooks - } - } - - const hasCommandAfterCleanup = - directCommandKeys.some((key) => typeof nextDefinition[key] === 'string') || - (Array.isArray(nextDefinition.hooks) && nextDefinition.hooks.length > 0) - if (!hasCommandAfterCleanup) { - return [] - } - - return [nextDefinition] - }) -} - -function hookHasManagedCommand(hook: HookCommandConfig, matches: (value?: string) => boolean) { - const args = Array.isArray(hook.args) ? hook.args : [] - return matches(hook.command) || args.some((arg) => typeof arg === 'string' && matches(arg)) -} - -// Users may opt a managed hook into async; keep that choice when the hook is rewritten. -export function withPreviousManagedAsync( - hook: HookCommandConfig, - definitions: HookDefinition[], - matches: (command: string | undefined) => boolean -): HookCommandConfig { - const async = definitions - .flatMap((definition) => (Array.isArray(definition.hooks) ? definition.hooks : [])) - .find((prev) => typeof prev.async === 'boolean' && hookHasManagedCommand(prev, matches))?.async - return async === undefined ? hook : { ...hook, async } -} - -export function hookDefinitionHasManagedCommand( - definition: HookDefinition, - isManagedCommand: (command: string | undefined) => boolean -): boolean { - return ( - isManagedCommand(definition.command) || - isManagedCommand(definition.bash) || - isManagedCommand(definition.powershell) || - (Array.isArray(definition.hooks) && - definition.hooks.some((hook) => hookHasManagedCommand(hook, isManagedCommand))) - ) -} - -// Atomic replacement protects scripts being read by in-flight hooks. -export function writeManagedScript( - scriptPath: string, - content: string | Buffer, - options: { moveLockedTargetAside?: boolean } = {} -): void { - const dir = dirname(scriptPath) - mkdirSync(dir, { recursive: true }) - - if (existsSync(scriptPath)) { - try { - if (readFileSync(scriptPath).equals(Buffer.from(content))) { - if (process.platform !== 'win32') { - chmodSync(scriptPath, 0o755) - } - return - } - } catch { - // Fall through to the atomic write path. - } - } - - const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) - try { - writeScriptWithAclRetry(tmpPath, content) - // Publish with execute permission so POSIX guards never skip a newly installed script. - if (process.platform !== 'win32') { - chmodSync(tmpPath, 0o755) - } - renameOverLockedTarget(tmpPath, scriptPath, options.moveLockedTargetAside === true) - } finally { - if (existsSync(tmpPath)) { - try { - unlinkSync(tmpPath) - } catch { - // best effort - } - } - } -} - -// Retry Windows EPERM once after repairing a restrictive directory ACL. -function writeScriptWithAclRetry(scriptPath: string, content: string | Buffer): void { - try { - writeFileSync(scriptPath, content, 'utf-8') - } catch (error) { - if (isPermissionError(error) && process.platform === 'win32') { - try { - grantDirAcl(dirname(scriptPath)) - writeFileSync(scriptPath, content, 'utf-8') - return - } catch { - // a failed grant is not actionable; re-throw the original EPERM - } - } - throw error - } -} - -export function writeHooksJson( - configPath: string, - // Fallback serialization accepts provider-specific JSON shapes, including nested hooks.events. - config: Record, - // JSONC callers supply edited text while retaining atomic writes and backups. - options?: { preserveMode?: boolean; defaultMode?: number; serialized?: string } -): void { - const writePath = resolveHooksJsonWritePath(configPath) - const dir = dirname(writePath) - mkdirSync(dir, { recursive: true }) - - // Unique temp paths isolate concurrent writers and preserve the original on write failure. - const tmpPath = join(dir, `.${Date.now()}-${randomUUID()}.tmp`) - const serialized = options?.serialized ?? `${JSON.stringify(config, null, 2)}\n` - // Preserve owner-only permissions: agent configs can contain API keys. - const existingMode = - options?.preserveMode !== false && existsSync(writePath) - ? statSync(writePath).mode & 0o777 - : options?.defaultMode - - // Identical reinstalls must not rotate away the last recoverable backup. - if (existsSync(writePath)) { - try { - if (readFileSync(writePath, 'utf-8') === serialized) { - return - } - } catch { - // Retry through the write path after a failed read. - } - } - - try { - // Windows read-only mode could prevent deleting a failed temporary write. - const tmpMode = process.platform === 'win32' ? undefined : existingMode - writeFileSync(tmpPath, serialized, { encoding: 'utf-8', mode: tmpMode, flag: 'wx' }) - if (existingMode !== undefined && process.platform !== 'win32') { - // Preserve requested permissions even with a stricter process umask. - chmodSync(tmpPath, existingMode) - } - // Keep one prior version for recovery from a bad merge. - if (existsSync(writePath)) { - writeRollingFileBackup(writePath, `${writePath}.bak`) - } - renameSync(tmpPath, writePath) - } finally { - if (existsSync(tmpPath)) { - try { - unlinkSync(tmpPath) - } catch { - // best effort - } - } - } -} - -export { writeHooksJsonAsync } from './hooks-json-write-async' diff --git a/src/main/agent-hooks/agent-transition-detector.test.ts b/src/main/agent-hooks/observations/agent-transition-detector.test.ts similarity index 94% rename from src/main/agent-hooks/agent-transition-detector.test.ts rename to src/main/agent-hooks/observations/agent-transition-detector.test.ts index 0b6d61f33aa..13bb1ba51be 100644 --- a/src/main/agent-hooks/agent-transition-detector.test.ts +++ b/src/main/agent-hooks/observations/agent-transition-detector.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' +import { AgentHookServer } from '../server/agent-hook-server' import { AgentTransitionDetector, type AgentPaneChange } from './agent-transition-detector' -import type { AgentTransitionStep } from '../../shared/agent-status/lifecycle/agent-transitions.test-fixture' +import type { AgentTransitionStep } from '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) +vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) const WT = 'repo-1::/tmp/a' const OTHER_WT = 'repo-1::/tmp/b' diff --git a/src/main/agent-hooks/agent-transition-detector.ts b/src/main/agent-hooks/observations/agent-transition-detector.ts similarity index 94% rename from src/main/agent-hooks/agent-transition-detector.ts rename to src/main/agent-hooks/observations/agent-transition-detector.ts index 2a579dfe393..1aaa6046d1b 100644 --- a/src/main/agent-hooks/agent-transition-detector.ts +++ b/src/main/agent-hooks/observations/agent-transition-detector.ts @@ -1,5 +1,5 @@ -import { resolveAgentStatusWorktreeId } from '../../shared/agent-status/identity/agent-status-worktree-attribution' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +import { resolveAgentStatusWorktreeId } from '../../../shared/agent-status/identity/agent-status-worktree-attribution' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import { agentPhaseTransition, hookRowAgentPhase, @@ -8,14 +8,14 @@ import { titleAgentPhase, type AgentPhase, type AgentTransition -} from '../../shared/agent-status/lifecycle/agent-transitions' -import type { TerminalSideEffectBatch } from '../../shared/terminal/output/terminal-side-effect-facts' +} from '../../../shared/agent-status/lifecycle/agent-transitions' +import type { TerminalSideEffectBatch } from '../../../shared/terminal/output/terminal-side-effect-facts' import { getConnectionExecutionHostId, LOCAL_EXECUTION_HOST_ID, type ExecutionHostId -} from '../../shared/execution-host' -import type { AgentHookServer } from './server' +} from '../../../shared/execution-host' +import type { AgentHookServer } from '../server/agent-hook-server' export type AgentTransitionStore = Pick< AgentHookServer, diff --git a/src/main/agent-hooks/local-hook-root-evidence.ts b/src/main/agent-hooks/observations/local-hook-root-evidence.ts similarity index 69% rename from src/main/agent-hooks/local-hook-root-evidence.ts rename to src/main/agent-hooks/observations/local-hook-root-evidence.ts index 03ec1717c78..413ae59469b 100644 --- a/src/main/agent-hooks/local-hook-root-evidence.ts +++ b/src/main/agent-hooks/observations/local-hook-root-evidence.ts @@ -1,12 +1,12 @@ -import type { AgentHookServer } from './server' +import type { AgentHookServer } from '../server/agent-hook-server' import { createLocalHookPaneRootResolver, createLocalPtyInventoryReader, type LocalPtyInventoryReader } from './local-tmux-managed-pty' -import { createLocalHookRootEvidenceReader } from '../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' -import { getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' -import { getLocalPtyProvider } from '../ipc/pty/provider/registry' +import { createLocalHookRootEvidenceReader } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence-reader' +import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' +import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' /** Hooks posted on this host name panes its own provider owns; their roots come from that * provider's inventory, read lazily because daemon swaps replace the provider. */ diff --git a/src/main/agent-hooks/local-tmux-managed-pty.test.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts similarity index 96% rename from src/main/agent-hooks/local-tmux-managed-pty.test.ts rename to src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts index f324d43ace8..fc229bc9ed0 100644 --- a/src/main/agent-hooks/local-tmux-managed-pty.test.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.test.ts @@ -4,7 +4,7 @@ import { createLocalPtyInventoryReader, createLocalTmuxManagedPtyResolver } from './local-tmux-managed-pty' -import type { PtyProcessInfo } from '../providers/pty-provider-contract' +import type { PtyProcessInfo } from '../../providers/pty-provider-contract' const row: PtyProcessInfo = { id: 'pty', diff --git a/src/main/agent-hooks/local-tmux-managed-pty.ts b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts similarity index 94% rename from src/main/agent-hooks/local-tmux-managed-pty.ts rename to src/main/agent-hooks/observations/local-tmux-managed-pty.ts index edd4e2a1a61..e3d6a683309 100644 --- a/src/main/agent-hooks/local-tmux-managed-pty.ts +++ b/src/main/agent-hooks/observations/local-tmux-managed-pty.ts @@ -1,6 +1,6 @@ -import type { PtyProcessInfo } from '../providers/pty-provider-contract' -import type { TmuxManagedPty } from '../../shared/tmux-agent-hook-contract' -import type { HookPaneProcessIo } from '../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { PtyProcessInfo } from '../../providers/pty-provider-contract' +import type { TmuxManagedPty } from '../../../shared/tmux-agent-hook-contract' +import type { HookPaneProcessIo } from '../../../shared/agent-hook-listener/presence/hook-process-root-evidence' type InventoryOptions = { getPtyId: (paneKey: string) => string | undefined | null diff --git a/src/main/agent-hooks/migration-unsupported-pty-state.ts b/src/main/agent-hooks/observations/migration-unsupported-pty-state.ts similarity index 95% rename from src/main/agent-hooks/migration-unsupported-pty-state.ts rename to src/main/agent-hooks/observations/migration-unsupported-pty-state.ts index 0d5dd17f084..c1e35d2b03c 100644 --- a/src/main/agent-hooks/migration-unsupported-pty-state.ts +++ b/src/main/agent-hooks/observations/migration-unsupported-pty-state.ts @@ -1,4 +1,4 @@ -import type { MigrationUnsupportedPtyEntry } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { MigrationUnsupportedPtyEntry } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' type MigrationUnsupportedPtyEvent = | { type: 'set'; entry: MigrationUnsupportedPtyEntry } diff --git a/src/main/agent-hooks/restored-status-dead-terminal-sweep.ts b/src/main/agent-hooks/observations/restored-status-dead-terminal-sweep.ts similarity index 90% rename from src/main/agent-hooks/restored-status-dead-terminal-sweep.ts rename to src/main/agent-hooks/observations/restored-status-dead-terminal-sweep.ts index cd485f64fae..cd856a1303c 100644 --- a/src/main/agent-hooks/restored-status-dead-terminal-sweep.ts +++ b/src/main/agent-hooks/observations/restored-status-dead-terminal-sweep.ts @@ -2,13 +2,13 @@ import { getConnectionExecutionHostId, parseExecutionHostId, type ExecutionHostId -} from '../../shared/execution-host' -import type { FolderWorkspace } from '../../shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../shared/project-group-types' -import { getRepoIdFromWorktreeId } from '../../shared/worktree/id' -import { parseWorkspaceKey } from '../../shared/workspace-scope' -import { isLocalHookConnectionId } from '../../shared/wsl-hook-relay-contract' -import type { AgentHookServer } from './server' +} from '../../../shared/execution-host' +import type { FolderWorkspace } from '../../../shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../../../shared/project-group-types' +import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' +import { parseWorkspaceKey } from '../../../shared/workspace-scope' +import { isLocalHookConnectionId } from '../../../shared/wsl-hook-relay-contract' +import type { AgentHookServer } from '../server/agent-hook-server' type RestoredStatusSweepServer = Pick< AgentHookServer, diff --git a/src/main/agent-hooks/agent-hook-runtime-deps.ts b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts similarity index 89% rename from src/main/agent-hooks/agent-hook-runtime-deps.ts rename to src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts index f48cc6836e6..1d65427fe77 100644 --- a/src/main/agent-hooks/agent-hook-runtime-deps.ts +++ b/src/main/agent-hooks/runtime/agent-hook-runtime-deps.ts @@ -1,7 +1,7 @@ -import type { OrcaRuntimeService } from '../runtime/orca-runtime' -import type { AgentStatusObservedPaneIdentities } from '../runtime/terminal/identity/agent-status-observed-pane-identity' -import type { AgentHookServer } from './server' -import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import type { OrcaRuntimeService } from '../../runtime/orca-runtime' +import type { AgentStatusObservedPaneIdentities } from '../../runtime/terminal/identity/agent-status-observed-pane-identity' +import type { AgentHookServer } from '../server/agent-hook-server' +import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' type RuntimeDeps = NonNullable[2]> diff --git a/src/main/agent-hooks/agent-status-pane-index.ts b/src/main/agent-hooks/runtime/agent-status-pane-index.ts similarity index 82% rename from src/main/agent-hooks/agent-status-pane-index.ts rename to src/main/agent-hooks/runtime/agent-status-pane-index.ts index 75a38ac615f..2abd2153c7d 100644 --- a/src/main/agent-hooks/agent-status-pane-index.ts +++ b/src/main/agent-hooks/runtime/agent-status-pane-index.ts @@ -1,4 +1,4 @@ -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' /** Index once per snapshot to avoid rematerializing rows for every pane. */ export function indexAgentStatusRowsByPaneKey( diff --git a/src/main/agent-hooks/hook-status-session-tabs-republish.ts b/src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts similarity index 96% rename from src/main/agent-hooks/hook-status-session-tabs-republish.ts rename to src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts index 460aae88aa3..9df5ff4e61d 100644 --- a/src/main/agent-hooks/hook-status-session-tabs-republish.ts +++ b/src/main/agent-hooks/runtime/hook-status-session-tabs-republish.ts @@ -1,4 +1,4 @@ -import type { AgentHookServer } from './server' +import type { AgentHookServer } from '../server/agent-hook-server' type SessionTabsRepublisher = { getTerminalWorktreeIdForHandle(handle: string): string | null diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts deleted file mode 100644 index f66f4b38526..00000000000 --- a/src/main/agent-hooks/server.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Shared listener internals let relays host the same pipeline without Electron. -import { clearAllListenerCaches } from '../../shared/agent-hook-listener/listener-state' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { parseFormEncodedBody } from '../../shared/agent-hook-listener/request-body' -import type { AgentHookEventPayload } from '../../shared/agent-hook-listener/listener-event' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { AgentHookServerAgentPresence } from './server/server-agent-presence' - -export class AgentHookServer extends AgentHookServerAgentPresence {} - -export const agentHookServer = new AgentHookServer() - -export const _internals = { - // Bind normalization to singleton state so tests exercise its caches. - normalizeHookPayload: ( - source: AgentHookSource, - body: unknown, - expectedEnv: string - ): AgentHookEventPayload | null => - normalizeHookPayload(agentHookServer._getStateForTests(), source, body, expectedEnv), - parseFormEncodedBody, - resetCachesForTests: (): void => { - clearAllListenerCaches(agentHookServer._getStateForTests()) - agentHookServer._resetCanonicalStatusForTests() - agentHookServer._resetRowOwnershipForTests() - agentHookServer._resetPromptSentDedupeForTests() - agentHookServer._resetConnectionTimestampWatermarksForTests() - } -} diff --git a/src/main/agent-hooks/server/server-agent-presence.ts b/src/main/agent-hooks/server/agent-hook-server.ts similarity index 88% rename from src/main/agent-hooks/server/server-agent-presence.ts rename to src/main/agent-hooks/server/agent-hook-server.ts index 0bd520d83a1..85a6fccb2a6 100644 --- a/src/main/agent-hooks/server/server-agent-presence.ts +++ b/src/main/agent-hooks/server/agent-hook-server.ts @@ -1,3 +1,8 @@ +import { clearAllListenerCaches } from '../../../shared/agent-hook-listener/listener-state' +import { normalizeHookPayload } from '../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { parseFormEncodedBody } from '../../../shared/agent-hook-listener/request-body' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { cliWriterTopology, type CliWriterObservation } from './cli-writer-observation' import type { AgentStatusIpcPayload } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { ParsedAgentStatusPayload } from '../../../shared/agent-status/contracts/agent-status-types' @@ -5,7 +10,6 @@ import { ClaudeSessionContinuationTracker, resolvePaneClaudeContinuation } from '../../../shared/agent-hook-listener/claude-session-continuation' -import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import { isSameAgentProcess, type AgentProcessVerdict @@ -13,7 +17,7 @@ import { import { probeAgentProcessPresence } from '../../../shared/agent-status/process/agent-process-presence-probe' import { AgentHookServerLifecycle } from './server-lifecycle' -export abstract class AgentHookServerAgentPresence extends AgentHookServerLifecycle { +export class AgentHookServer extends AgentHookServerLifecycle { private readonly presenceChecks = new WeakMap< AgentHookEventPayload, { @@ -239,3 +243,23 @@ export abstract class AgentHookServerAgentPresence extends AgentHookServerLifecy : null } } + +export const agentHookServer = new AgentHookServer() + +export const _internals = { + // Bind normalization to singleton state so tests exercise its caches. + normalizeHookPayload: ( + source: AgentHookSource, + body: unknown, + expectedEnv: string + ): AgentHookEventPayload | null => + normalizeHookPayload(agentHookServer._getStateForTests(), source, body, expectedEnv), + parseFormEncodedBody, + resetCachesForTests: (): void => { + clearAllListenerCaches(agentHookServer._getStateForTests()) + agentHookServer._resetCanonicalStatusForTests() + agentHookServer._resetRowOwnershipForTests() + agentHookServer._resetPromptSentDedupeForTests() + agentHookServer._resetConnectionTimestampWatermarksForTests() + } +} diff --git a/src/main/agent-hooks/server/server-lifecycle.ts b/src/main/agent-hooks/server/server-lifecycle.ts index 194d7c5c0d4..22035d2950a 100644 --- a/src/main/agent-hooks/server/server-lifecycle.ts +++ b/src/main/agent-hooks/server/server-lifecycle.ts @@ -20,7 +20,7 @@ import { trackEmptyPaneKeyHook } from './server-transport-rules' import { AgentHookServerStatusHookLifecycle } from './server-status-hook-lifecycle' import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../../shared/agent-launch/startup/opencode-startup-prompt' import { CLAUDE_AGENT_VIEW_PATH } from '../../../shared/claude-agent-view' -import { respondAfterAgentToolPluginHooks } from '../agent-tool-plugin-hooks' +import { respondAfterAgentToolPluginHooks } from '../tool-events/agent-tool-plugin-hooks' import type { HookServerStartOptions } from './server-types' diff --git a/src/main/agent-hooks/server-accepted-reply.test.ts b/src/main/agent-hooks/server/testing/accepted-replies/server-accepted-reply.test.ts similarity index 88% rename from src/main/agent-hooks/server-accepted-reply.test.ts rename to src/main/agent-hooks/server/testing/accepted-replies/server-accepted-reply.test.ts index 2a873d3d9fd..268762da77f 100644 --- a/src/main/agent-hooks/server-accepted-reply.test.ts +++ b/src/main/agent-hooks/server/testing/accepted-replies/server-accepted-reply.test.ts @@ -2,14 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' -import { mainAgentDoneAt } from '../../shared/agent-status/lifecycle/main-agent-status' -import type { AutomationRun } from '../../shared/automations/history/automation-run' -import { createRuntimeAutomationRunTerminalObserver } from '../automations/runtime-terminal-run-observer' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' +import { mainAgentDoneAt } from '../../../../../shared/agent-status/lifecycle/main-agent-status' +import type { AutomationRun } from '../../../../../shared/automations/history/automation-run' +import { createRuntimeAutomationRunTerminalObserver } from '../../../../automations/runtime-terminal-run-observer' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-closed-tab-suppression.test.ts b/src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts similarity index 97% rename from src/main/agent-hooks/server-closed-tab-suppression.test.ts rename to src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts index 8e171a99a38..70dafb046a5 100644 --- a/src/main/agent-hooks/server-closed-tab-suppression.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-closed-tab-suppression.test.ts @@ -1,20 +1,20 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createHash } from 'node:crypto' -import { AgentHookServer, _internals } from './server' -import { CLOSED_AGENT_STATUS_TAB_IDS_MAX } from './server/server-constants' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { buildBody, PANE, LEAF_2, LEAF_3 } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { CLOSED_AGENT_STATUS_TAB_IDS_MAX } from '../../server-constants' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { buildBody, PANE, LEAF_2, LEAF_3 } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-omp-retired-ingress.test.ts b/src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts similarity index 90% rename from src/main/agent-hooks/server-omp-retired-ingress.test.ts rename to src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts index 1cb38afb372..2746269d8a1 100644 --- a/src/main/agent-hooks/server-omp-retired-ingress.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-omp-retired-ingress.test.ts @@ -1,9 +1,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) afterEach(() => vi.restoreAllMocks()) const working = { agentType: 'omp', state: 'working', prompt: 'new turn' } diff --git a/src/main/agent-hooks/server-omp-retirement-ack.test.ts b/src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts similarity index 92% rename from src/main/agent-hooks/server-omp-retirement-ack.test.ts rename to src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts index ae0bfe338f6..ebf219467eb 100644 --- a/src/main/agent-hooks/server-omp-retirement-ack.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-omp-retirement-ack.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { GOOD_PANE, PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { GOOD_PANE, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) const ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' const hook = { paneKey: PANE, diff --git a/src/main/agent-hooks/server-pane-authority.test.ts b/src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts similarity index 96% rename from src/main/agent-hooks/server-pane-authority.test.ts rename to src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts index e1ebfc2df6e..d7449fc32e0 100644 --- a/src/main/agent-hooks/server-pane-authority.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' -import { PANE_KEY_ALIASES_MAX } from './server/server-constants' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../agent-hook-server' +import { PANE_KEY_ALIASES_MAX } from '../../server-constants' const SOURCE = makePaneKey('tab-source', '11111111-1111-4111-8111-111111111111') const TARGET = makePaneKey('tab-target', '22222222-2222-4222-8222-222222222222') diff --git a/src/main/agent-hooks/server-reminted-pane-key.test.ts b/src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts similarity index 95% rename from src/main/agent-hooks/server-reminted-pane-key.test.ts rename to src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts index 14f63089f48..b3eb282c93a 100644 --- a/src/main/agent-hooks/server-reminted-pane-key.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-reminted-pane-key.test.ts @@ -2,19 +2,19 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, GOOD_PANE, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, GOOD_PANE, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts similarity index 97% rename from src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts rename to src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts index 62606e5729c..141e9f6f6fa 100644 --- a/src/main/agent-hooks/server-removed-worktree-foreign-authority.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-foreign-authority.test.ts @@ -3,9 +3,9 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { LEAF_1 } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { LEAF_1 } from '../server.test-fixtures' const REMOVED = 'repo::/removed' const KEPT = 'repo::/kept' diff --git a/src/main/agent-hooks/server-removed-worktree-status.test.ts b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts similarity index 97% rename from src/main/agent-hooks/server-removed-worktree-status.test.ts rename to src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts index e05dbe504e3..fa24ce40be1 100644 --- a/src/main/agent-hooks/server-removed-worktree-status.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-removed-worktree-status.test.ts @@ -2,9 +2,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { LEAF_1, LEAF_2, LEAF_3, LEAF_4, LEAF_5, recentTs } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { LEAF_1, LEAF_2, LEAF_3, LEAF_4, LEAF_5, recentTs } from '../server.test-fixtures' const REMOVED = 'repo-1::/workspace/removed' const KEPT = 'repo-1::/workspace/kept' diff --git a/src/main/agent-hooks/server-retired-pane-new-turn.test.ts b/src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts similarity index 91% rename from src/main/agent-hooks/server-retired-pane-new-turn.test.ts rename to src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts index ab9e005bed0..66dbcaf20dd 100644 --- a/src/main/agent-hooks/server-retired-pane-new-turn.test.ts +++ b/src/main/agent-hooks/server/testing/authority/server-retired-pane-new-turn.test.ts @@ -1,14 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +import type { AgentHookSource } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({ trackMock: vi.fn(), getCohortAtEmitMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-claude-statusline.test.ts b/src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts similarity index 93% rename from src/main/agent-hooks/server-claude-statusline.test.ts rename to src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts index edb5008a285..0f5132ad5ca 100644 --- a/src/main/agent-hooks/server-claude-statusline.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-claude-statusline.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AgentHookServer } from './server' -import type { ClaudeStatusLineRateLimits } from '../../shared/claude-statusline-rate-limits' +import { AgentHookServer } from '../../agent-hook-server' +import type { ClaudeStatusLineRateLimits } from '../../../../../shared/claude-statusline-rate-limits' describe('AgentHookServer /statusline/claude', () => { let server: AgentHookServer diff --git a/src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts b/src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts similarity index 96% rename from src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts index fc7a48b7f87..ee591caafaf 100644 --- a/src/main/agent-hooks/server-endpoint-file-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-endpoint-file-lifecycle.test.ts @@ -12,18 +12,18 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' +import { AgentHookServer, _internals } from '../../agent-hook-server' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-hook-http-ingest.test.ts b/src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts similarity index 96% rename from src/main/agent-hooks/server-hook-http-ingest.test.ts rename to src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts index d5ba925b721..0d12cee0e50 100644 --- a/src/main/agent-hooks/server-hook-http-ingest.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-hook-http-ingest.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-startup-lifecycle.test.ts b/src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts similarity index 85% rename from src/main/agent-hooks/server-startup-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts index 59153450bb0..e81d00e1006 100644 --- a/src/main/agent-hooks/server-startup-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-startup-lifecycle.test.ts @@ -2,17 +2,20 @@ import { afterEach, expect, it, vi } from 'vitest' import { existsSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import type { drainAgentHookSpoolAsync } from '../../shared/agent-hook-listener/transport/agent-hook-spool' -import type * as HookSpoolModule from '../../shared/agent-hook-listener/transport/agent-hook-spool' -import { getEndpointFileName } from '../../shared/agent-hook-listener/transport/endpoint-publication' +import { AgentHookServer } from '../../agent-hook-server' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import type { drainAgentHookSpoolAsync } from '../../../../../shared/agent-hook-listener/transport/agent-hook-spool' +import type * as HookSpoolModule from '../../../../../shared/agent-hook-listener/transport/agent-hook-spool' +import { getEndpointFileName } from '../../../../../shared/agent-hook-listener/transport/endpoint-publication' const drain = vi.hoisted(() => vi.fn()) -vi.mock('../../shared/agent-hook-listener/transport/agent-hook-spool', async (importOriginal) => ({ - ...(await importOriginal()), - drainAgentHookSpoolAsync: drain -})) +vi.mock( + '../../../../../shared/agent-hook-listener/transport/agent-hook-spool', + async (importOriginal) => ({ + ...(await importOriginal()), + drainAgentHookSpoolAsync: drain + }) +) const directories: string[] = [] const servers: { stop: () => void }[] = [] diff --git a/src/main/agent-hooks/server-startup-prompt-control.test.ts b/src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts similarity index 91% rename from src/main/agent-hooks/server-startup-prompt-control.test.ts rename to src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts index 87827926b68..e2bdd770fb6 100644 --- a/src/main/agent-hooks/server-startup-prompt-control.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-startup-prompt-control.test.ts @@ -2,10 +2,10 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'no import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { parseAgentHookEndpointFile } from '../../shared/agent-hook-listener/transport/agent-hook-endpoint-file' -import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../shared/agent-launch/startup/opencode-startup-prompt' -import { PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { parseAgentHookEndpointFile } from '../../../../../shared/agent-hook-listener/transport/agent-hook-endpoint-file' +import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../../../../shared/agent-launch/startup/opencode-startup-prompt' +import { PANE } from '../server.test-fixtures' describe('startup prompt control with status hooks disabled', () => { it.each([false, true])( diff --git a/src/main/agent-hooks/server-transport-interference.test.ts b/src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts similarity index 93% rename from src/main/agent-hooks/server-transport-interference.test.ts rename to src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts index 12d8f354dec..e8b6ce0d085 100644 --- a/src/main/agent-hooks/server-transport-interference.test.ts +++ b/src/main/agent-hooks/server/testing/http/server-transport-interference.test.ts @@ -2,10 +2,10 @@ import { connect } from 'node:net' import { IncomingMessage, ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { HookTransportInterferenceReport } from '../../shared/agent-hook-listener/transport/agent-hook-transport-interference' -import { AgentHookServer } from './server' -import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../shared/agent-launch/startup/opencode-startup-prompt' -import { HOOK_REQUEST_SLOWLORIS_MS } from '../../shared/agent-hook-listener/listener-limits' +import type { HookTransportInterferenceReport } from '../../../../../shared/agent-hook-listener/transport/agent-hook-transport-interference' +import { AgentHookServer } from '../../agent-hook-server' +import { OPENCODE_STARTUP_PROMPT_CLAIM_PATH } from '../../../../../shared/agent-launch/startup/opencode-startup-prompt' +import { HOOK_REQUEST_SLOWLORIS_MS } from '../../../../../shared/agent-hook-listener/listener-limits' async function postTruncatedHook( port: number, diff --git a/src/main/agent-hooks/server-ai-vault-liveness.test.ts b/src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts similarity index 92% rename from src/main/agent-hooks/server-ai-vault-liveness.test.ts rename to src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts index b19c9dcdcec..16f29b1072c 100644 --- a/src/main/agent-hooks/server-ai-vault-liveness.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-ai-vault-liveness.test.ts @@ -2,8 +2,8 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it } from 'vitest' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../agent-hook-server' const PANE = makePaneKey('external-live', '11111111-1111-4111-8111-111111111111') const PROVIDER_SESSION = { key: 'session_id' as const, id: 'session-live' } diff --git a/src/main/agent-hooks/server-claude-resume-record-continuity.test.ts b/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts similarity index 93% rename from src/main/agent-hooks/server-claude-resume-record-continuity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts index 480d4f35423..6ba51d5812e 100644 --- a/src/main/agent-hooks/server-claude-resume-record-continuity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-claude-resume-record-continuity.test.ts @@ -2,9 +2,9 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from './server/program-status/hook-precedence' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from '../../program-status/hook-precedence' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' const SESSION = '70efcb3f-ae17-4863-9318-649f5469408b' diff --git a/src/main/agent-hooks/server-claude-session-continuation.test.ts b/src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts similarity index 88% rename from src/main/agent-hooks/server-claude-session-continuation.test.ts rename to src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts index 3cb205c11b8..9b35c902e0c 100644 --- a/src/main/agent-hooks/server-claude-session-continuation.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-claude-session-continuation.test.ts @@ -2,14 +2,14 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' -import { buildBody, GOOD_PANE, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' +import { buildBody, GOOD_PANE, PANE, postHookEvent } from '../server.test-fixtures' const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) diff --git a/src/main/agent-hooks/server-copilot-resume-identity.test.ts b/src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts similarity index 90% rename from src/main/agent-hooks/server-copilot-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts index a6b595c350d..476e1a49bfe 100644 --- a/src/main/agent-hooks/server-copilot-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-copilot-resume-identity.test.ts @@ -2,12 +2,12 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { resumeRecordFromStatus } from '../../shared/agent-session/lifecycle/agent-resume-record-from-status' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import { AgentHookServer } from './server' -import { type Body, buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { resumeRecordFromStatus } from '../../../../../shared/agent-session/lifecycle/agent-resume-record-from-status' +import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv' +import { AgentHookServer } from '../../agent-hook-server' +import { type Body, buildBody, PANE, postHookEvent } from '../server.test-fixtures' const ROOT = 'cf0e6ff2-9ede-46de-a430-5778cf8da164' const CHILD = 'copilot-helper' diff --git a/src/main/agent-hooks/server-hermes-resume-identity.test.ts b/src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts similarity index 90% rename from src/main/agent-hooks/server-hermes-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts index 66691cd4422..d53513294c4 100644 --- a/src/main/agent-hooks/server-hermes-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-hermes-resume-identity.test.ts @@ -2,14 +2,14 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { resumeRecordFromStatus } from '../../shared/agent-session/lifecycle/agent-resume-record-from-status' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { resumeRecordFromStatus } from '../../../../../shared/agent-session/lifecycle/agent-resume-record-from-status' +import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv' +import type { AgentHookRelayEnvelope } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' const ROOT = 'local-parent' const CHILD = '20261024_child' diff --git a/src/main/agent-hooks/server-hook-session-binding.test.ts b/src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts similarity index 88% rename from src/main/agent-hooks/server-hook-session-binding.test.ts rename to src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts index cc2b7889686..6c37cd1f9a6 100644 --- a/src/main/agent-hooks/server-hook-session-binding.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts @@ -3,42 +3,46 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { HookSessionBindingRendererFixture } from '../../shared/agent-hook-listener/state/agent-hook-session-binding.test-fixture' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' +import type { HookSessionBindingRendererFixture } from '../../../../../shared/agent-hook-listener/state/agent-hook-session-binding.test-fixture' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' import { createHookListenerState, admitLegacyAgentStatus -} from '../../shared/agent-hook-listener/listener-state' -import { readAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence' -import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../shared/agent-status/transport/agent-status-legacy-adapter' -import { getDefaultWorkspaceSession } from '../../shared/constants' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' -import { RelayProviderHookNormalization } from '../../wsl-guest/agent-hook-provider-normalization' -import { hookRowPaneResumeRecord } from '../runtime/session-lifecycle/projection/hook-row-pane-resume-record' +} from '../../../../../shared/agent-hook-listener/listener-state' +import { readAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence' +import { AGENT_STATUS_2A_CURRENT_PRODUCER_MODE } from '../../../../../shared/agent-status/transport/agent-status-legacy-adapter' +import { getDefaultWorkspaceSession } from '../../../../../shared/constants' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' +import { RelayProviderHookNormalization } from '../../../../../wsl-guest/agent-hook-provider-normalization' +import { hookRowPaneResumeRecord } from '../../../../runtime/session-lifecycle/projection/hook-row-pane-resume-record' import { hookStatusResumeCommand, quitResumeRecords, resumeStatusFromHookRow -} from '../runtime/terminal/stop/hook-status-resume-records' +} from '../../../../runtime/terminal/stop/hook-status-resume-records' import { installMainWindowAgentStatusListeners, clearMainWindowAgentStatusListeners -} from '../startup/main-window-agent-status' -import { agentHookServer as server } from './server' -import { buildBody, PANE, GOOD_PANE, postHookEvent } from './server.test-fixtures' +} from '../../../../startup/main-window-agent-status' +import { agentHookServer as server } from '../../agent-hook-server' +import { buildBody, PANE, GOOD_PANE, postHookEvent } from '../server.test-fixtures' const bridge = vi.hoisted(() => ({ send: vi.fn<(channel: string, data: AgentStatusIpcPayload) => void>() })) -vi.mock('../startup/main-process-state', () => ({ +vi.mock('../../../../startup/main-process-state', () => ({ mainProcessState: { mainWindow: { isDestroyed: () => false, webContents: bridge }, runtime: null } })) -vi.mock('../window/dashboard-popout-window', () => ({ getDashboardPopoutWindow: () => null })) -vi.mock('../startup/synthetic-title-runtime', () => ({ stopSyntheticTitleSpinnerTimer: () => {} })) +vi.mock('../../../../window/dashboard-popout-window', () => ({ + getDashboardPopoutWindow: () => null +})) +vi.mock('../../../../startup/synthetic-title-runtime', () => ({ + stopSyntheticTitleSpinnerTimer: () => {} +})) const rendererFixture: unknown = await vi.importActual( - '../../renderer/src/store/slices/agent-status/hook-session-binding-renderer.test-fixture' + '../../../../../renderer/src/store/slices/agent-status/hook-session-binding-renderer.test-fixture' ) function isRendererFixture(value: unknown): value is HookSessionBindingRendererFixture { return ( diff --git a/src/main/agent-hooks/server-launch-resume-identity.test.ts b/src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts similarity index 92% rename from src/main/agent-hooks/server-launch-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts index f6f1978f31b..396f7741356 100644 --- a/src/main/agent-hooks/server-launch-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-launch-resume-identity.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const RESUMED = { key: 'session_id' as const, id: 'resumed-session' } diff --git a/src/main/agent-hooks/server-nested-agent-boundaries.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts similarity index 92% rename from src/main/agent-hooks/server-nested-agent-boundaries.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts index 8bf72bf7640..7570c06c56e 100644 --- a/src/main/agent-hooks/server-nested-agent-boundaries.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-agent-boundaries.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status/contracts/agent-status-freshness' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) diff --git a/src/main/agent-hooks/server-nested-agent-consumers.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts similarity index 83% rename from src/main/agent-hooks/server-nested-agent-consumers.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts index 847d65015bd..c9e1a79d245 100644 --- a/src/main/agent-hooks/server-nested-agent-consumers.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-agent-consumers.test.ts @@ -1,10 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { buildRuntimeMobileAgentStatus } from '../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { buildRuntimeMobileAgentStatus } from '../../../../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) diff --git a/src/main/agent-hooks/server-nested-agent-model.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts similarity index 90% rename from src/main/agent-hooks/server-nested-agent-model.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts index deb4119d6e4..6691b0afd49 100644 --- a/src/main/agent-hooks/server-nested-agent-model.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-agent-model.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) diff --git a/src/main/agent-hooks/server-nested-same-provider-owner.test.ts b/src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts similarity index 83% rename from src/main/agent-hooks/server-nested-same-provider-owner.test.ts rename to src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts index 477bedac070..7dbc60dff96 100644 --- a/src/main/agent-hooks/server-nested-same-provider-owner.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-nested-same-provider-owner.test.ts @@ -1,12 +1,12 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-opencode-writer-observation.test.ts b/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts similarity index 86% rename from src/main/agent-hooks/server-opencode-writer-observation.test.ts rename to src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts index 5c206bf848d..bf9b8721ca5 100644 --- a/src/main/agent-hooks/server-opencode-writer-observation.test.ts +++ b/src/main/agent-hooks/server/testing/identity/server-opencode-writer-observation.test.ts @@ -1,17 +1,17 @@ import { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture -} from '../runtime/terminal/identity/agent-status-observed-pane-identity' -import { OPEN_CODE_WRITER_TOPOLOGY } from './server/cli-writer-observation' -import { toAgentStatusIpcPayload } from './server/server-status-identity' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' +} from '../../../../runtime/terminal/identity/agent-status-observed-pane-identity' +import { OPEN_CODE_WRITER_TOPOLOGY } from '../../cli-writer-observation' +import { toAgentStatusIpcPayload } from '../../server-status-identity' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: async () => 'unverifiable' })) diff --git a/src/main/agent-hooks/terminal-handle-row-identity.test.ts b/src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts similarity index 92% rename from src/main/agent-hooks/terminal-handle-row-identity.test.ts rename to src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts index 9ab60d53759..80bcf54ef99 100644 --- a/src/main/agent-hooks/terminal-handle-row-identity.test.ts +++ b/src/main/agent-hooks/server/testing/identity/terminal-handle-row-identity.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status/contracts/agent-status-freshness' -import { selectFreshExplicitAgentStatus } from '../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' -import { wslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' +import { AgentHookServer } from '../../agent-hook-server' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status/contracts/agent-status-freshness' +import { selectFreshExplicitAgentStatus } from '../../../../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' +import { wslHookRelayConnectionId } from '../../../../../shared/wsl-hook-relay-contract' const PANE_KEY = 'tab-handle:33333333-3333-4333-8333-333333333333' const HANDLE = 'term_identity' diff --git a/src/main/agent-hooks/claude-cancel-capture.test-fixture.ts b/src/main/agent-hooks/server/testing/interruptions/claude-cancel-capture.test-fixture.ts similarity index 91% rename from src/main/agent-hooks/claude-cancel-capture.test-fixture.ts rename to src/main/agent-hooks/server/testing/interruptions/claude-cancel-capture.test-fixture.ts index bb5dcf75fbd..2b9eafd496f 100644 --- a/src/main/agent-hooks/claude-cancel-capture.test-fixture.ts +++ b/src/main/agent-hooks/server/testing/interruptions/claude-cancel-capture.test-fixture.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { AGENT_INTERRUPT_SETTLE_MS } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' +import { AGENT_INTERRUPT_SETTLE_MS } from '../../../../../shared/agent-status/lifecycle/agent-interrupt-intent' const capturedHook = z.object({ kind: z.literal('hook'), @@ -28,7 +28,7 @@ export type CapturedRecord = z.infer export function loadCapture(name: string): CapturedRecord[] { return readFileSync( - join(__dirname, '..', '..', 'shared', '__fixtures__', `${name}.jsonl`), + join(__dirname, '..', '..', '..', '..', '..', 'shared', '__fixtures__', `${name}.jsonl`), 'utf8' ) .trim() diff --git a/src/main/agent-hooks/claude-terminal-interrupt-capture.test-fixture.ts b/src/main/agent-hooks/server/testing/interruptions/claude-terminal-interrupt-capture.test-fixture.ts similarity index 86% rename from src/main/agent-hooks/claude-terminal-interrupt-capture.test-fixture.ts rename to src/main/agent-hooks/server/testing/interruptions/claude-terminal-interrupt-capture.test-fixture.ts index f46e2d488df..ba117bf65b0 100644 --- a/src/main/agent-hooks/claude-terminal-interrupt-capture.test-fixture.ts +++ b/src/main/agent-hooks/server/testing/interruptions/claude-terminal-interrupt-capture.test-fixture.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import { z } from 'zod' -import { extractAllOscTitleEntries } from '../../shared/agent-status/title/osc-title-extraction' +import { extractAllOscTitleEntries } from '../../../../../shared/agent-status/title/osc-title-extraction' const captureEvent = z.discriminatedUnion('kind', [ z.object({ kind: z.literal('title'), title: z.string(), atMs: z.number() }), @@ -9,7 +9,7 @@ const captureEvent = z.discriminatedUnion('kind', [ ]) export function loadClaudeInterruptCapture(name: string) { - const base = join(__dirname, '../runtime/__fixtures__', `claude-interrupt-${name}`) + const base = join(__dirname, '../../../../runtime/__fixtures__', `claude-interrupt-${name}`) const transcript = readFileSync(`${base}.txt`, 'utf8') const events = z.array(captureEvent).parse(JSON.parse(readFileSync(`${base}.input.json`, 'utf8'))) const titleEntries = extractAllOscTitleEntries(transcript) diff --git a/src/main/agent-hooks/server-claude-helper-kill.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts similarity index 91% rename from src/main/agent-hooks/server-claude-helper-kill.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts index fe25c65c80b..79d2fb290f8 100644 --- a/src/main/agent-hooks/server-claude-helper-kill.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-kill.test.ts @@ -2,15 +2,15 @@ import { appendFile, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/pro import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { selectFreshExplicitAgentStatus } from '../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' -import { selectRuntimeHookAgentRowForPane } from '../runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection' -import { buildRunningAgentChildRowModels } from '../../shared/running-agent-child-rows' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { selectFreshExplicitAgentStatus } from '../../../../runtime/workspaces/process-listing/runtime-hook-agent-row-selection' +import { selectRuntimeHookAgentRowForPane } from '../../../../runtime/session-lifecycle/projection/runtime-mobile-agent-status-projection' +import { buildRunningAgentChildRowModels } from '../../../../../shared/running-agent-child-rows' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) const servers: { stop: () => void }[] = [] @@ -44,7 +44,7 @@ async function host(kind: string, initial: Record[] = []) { ( await readFile( new URL( - `../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, + `../../../../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, import.meta.url ), 'utf8' diff --git a/src/main/agent-hooks/server-claude-helper-recovery.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts similarity index 95% rename from src/main/agent-hooks/server-claude-helper-recovery.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts index e7702995c23..cada292132b 100644 --- a/src/main/agent-hooks/server-claude-helper-recovery.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-claude-helper-recovery.test.ts @@ -4,17 +4,17 @@ import { tmpdir } from 'node:os' import { createServer } from 'node:http' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { ClaudeHelperKillPoller } from '../../shared/agent-hook-listener/providers/claude-helper-kill-poller' -import '../../shared/agent-hook-listener/providers/claude-transcript-decoder' -import * as cursor from '../../shared/agent-hook-listener/providers/claude-transcript-cursor' -import '../../shared/agent-hook-listener/transcripts/agent-transcript-poll-scheduler' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { ClaudeHelperKillPoller } from '../../../../../shared/agent-hook-listener/providers/claude-helper-kill-poller' +import '../../../../../shared/agent-hook-listener/providers/claude-transcript-decoder' +import * as cursor from '../../../../../shared/agent-hook-listener/providers/claude-transcript-cursor' +import '../../../../../shared/agent-hook-listener/transcripts/agent-transcript-poll-scheduler' // Complete captured lifecycle records, with runtime replay seeded by real persisted HTTP state. -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) const servers: { stop: () => void }[] = [] @@ -51,7 +51,7 @@ async function load(stream: string): Promise[]> { return ( await readFile( new URL( - `../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, + `../../../../../shared/__fixtures__/claude-helper-kill-2.1.310-${stream}.jsonl`, import.meta.url ), 'utf8' diff --git a/src/main/agent-hooks/server-claude-terminal-interrupt.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts similarity index 94% rename from src/main/agent-hooks/server-claude-terminal-interrupt.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts index 5a0b6885950..25271e944cf 100644 --- a/src/main/agent-hooks/server-claude-terminal-interrupt.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-claude-terminal-interrupt.test.ts @@ -1,11 +1,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from '../server.test-fixtures' import { loadClaudeInterruptCapture } from './claude-terminal-interrupt-capture.test-fixture' -import { createTerminalTitleTracker } from '../../shared/terminal/output/terminal-output-side-effects' +import { createTerminalTitleTracker } from '../../../../../shared/terminal/output/terminal-output-side-effects' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) let server: AgentHookServer diff --git a/src/main/agent-hooks/server-interrupt-inference-guards.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts similarity index 98% rename from src/main/agent-hooks/server-interrupt-inference-guards.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts index 08940da57fd..80d23e8188a 100644 --- a/src/main/agent-hooks/server-interrupt-inference-guards.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-guards.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts similarity index 96% rename from src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts index 61dc79c709c..8e7022748c9 100644 --- a/src/main/agent-hooks/server-interrupt-inference-resurrection.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-interrupt-inference-resurrection.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-relayed-claude-cancel.test.ts b/src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts similarity index 97% rename from src/main/agent-hooks/server-relayed-claude-cancel.test.ts rename to src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts index 671ddbf97aa..cef90654fd8 100644 --- a/src/main/agent-hooks/server-relayed-claude-cancel.test.ts +++ b/src/main/agent-hooks/server/testing/interruptions/server-relayed-claude-cancel.test.ts @@ -3,9 +3,9 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' import { hookAt, loadCapture, type CapturedHook } from './claude-cancel-capture.test-fixture' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ @@ -13,8 +13,8 @@ const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const temporaryPaths: string[] = [] const running: { stop: () => void }[] = [] diff --git a/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts b/src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts similarity index 94% rename from src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts rename to src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts index 46464397956..f711a261ae2 100644 --- a/src/main/agent-hooks/server-main-agent-turn-verdicts.test.ts +++ b/src/main/agent-hooks/server/testing/main-agent/server-main-agent-turn-verdicts.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-turn-ended-at.test.ts b/src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts similarity index 97% rename from src/main/agent-hooks/server-turn-ended-at.test.ts rename to src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts index 695f97cfd0a..6289c4c35f3 100644 --- a/src/main/agent-hooks/server-turn-ended-at.test.ts +++ b/src/main/agent-hooks/server/testing/main-agent/server-turn-ended-at.test.ts @@ -2,11 +2,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) // Only identified turns or verified Stop revisions mint an end; repeats and ambiguity never mint another. describe('the host-stamped turn end', () => { diff --git a/src/main/agent-hooks/server-turn-started-at.test.ts b/src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts similarity index 94% rename from src/main/agent-hooks/server-turn-started-at.test.ts rename to src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts index dd3749e0b99..34e6a034bdc 100644 --- a/src/main/agent-hooks/server-turn-started-at.test.ts +++ b/src/main/agent-hooks/server/testing/main-agent/server-turn-started-at.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-codex-normalization.test.ts b/src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts similarity index 96% rename from src/main/agent-hooks/server-codex-normalization.test.ts rename to src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts index d8944e6ff0c..42c4dbf7c57 100644 --- a/src/main/agent-hooks/server-codex-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/normalization/server-provider-normalization.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _internals } from './server' -import { buildBody } from './server.test-fixtures' +import { _internals } from '../../agent-hook-server' +import { buildBody } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts similarity index 95% rename from src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts index c376744fbf0..57e55ea2ebb 100644 --- a/src/main/agent-hooks/server-claude-child-permission-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-child-permission-lifecycle.test.ts @@ -1,14 +1,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-claude-permission-batch-release.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-batch-release.test.ts similarity index 98% rename from src/main/agent-hooks/server-claude-permission-batch-release.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-permission-batch-release.test.ts index d7edeca89c0..b0dd862a04c 100644 --- a/src/main/agent-hooks/server-claude-permission-batch-release.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-batch-release.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-claude-permission-tool-failure.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts similarity index 93% rename from src/main/agent-hooks/server-claude-permission-tool-failure.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts index 6248d8f238f..08fb7a0fed7 100644 --- a/src/main/agent-hooks/server-claude-permission-tool-failure.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-tool-failure.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-claude-permission-visibility.test.ts b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts similarity index 98% rename from src/main/agent-hooks/server-claude-permission-visibility.test.ts rename to src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts index 660c6dc2500..294a901f15d 100644 --- a/src/main/agent-hooks/server-claude-permission-visibility.test.ts +++ b/src/main/agent-hooks/server/testing/permissions/server-claude-permission-visibility.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts similarity index 97% rename from src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts index c666a276b2a..3f36e949da2 100644 --- a/src/main/agent-hooks/server-last-status-child-held-main-agent.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-child-held-main-agent.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts similarity index 97% rename from src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts index 50f927557ef..5df796b53a5 100644 --- a/src/main/agent-hooks/server-last-status-hydrate-confirmation.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-confirmation.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, recentTs, PANE, GOOD_PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, recentTs, PANE, GOOD_PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-last-status-hydrate-validation.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts similarity index 94% rename from src/main/agent-hooks/server-last-status-hydrate-validation.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts index 09c2db1e40c..874d124818b 100644 --- a/src/main/agent-hooks/server-last-status-hydrate-validation.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-hydrate-validation.test.ts @@ -11,8 +11,8 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { buildBody, postHookEvent, @@ -21,18 +21,18 @@ import { GOOD_PANE, LEAF_2, LEAF_5 -} from './server.test-fixtures' +} from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-last-status-lead-boundary.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts similarity index 95% rename from src/main/agent-hooks/server-last-status-lead-boundary.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts index 35f22f1f239..6d428b401dd 100644 --- a/src/main/agent-hooks/server-last-status-lead-boundary.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-lead-boundary.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-last-status-main-agent-fact.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts similarity index 95% rename from src/main/agent-hooks/server-last-status-main-agent-fact.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts index 252dcf47233..51baddf328d 100644 --- a/src/main/agent-hooks/server-last-status-main-agent-fact.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-main-agent-fact.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, recentTs, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, recentTs, PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-last-status-restored-children.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts similarity index 97% rename from src/main/agent-hooks/server-last-status-restored-children.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts index cb4f96ba0df..812b2270511 100644 --- a/src/main/agent-hooks/server-last-status-restored-children.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-restored-children.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-last-status-write.test.ts b/src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts similarity index 97% rename from src/main/agent-hooks/server-last-status-write.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts index 2f04341bc41..9386306f039 100644 --- a/src/main/agent-hooks/server-last-status-write.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-last-status-write.test.ts @@ -3,19 +3,19 @@ import { createHash } from 'node:crypto' import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, postHookEvent, recentTs, PANE, RUNNING_SHELL } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, postHookEvent, recentTs, PANE, RUNNING_SHELL } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-observation-provenance.test.ts b/src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts similarity index 86% rename from src/main/agent-hooks/server-observation-provenance.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts index 707c6de2479..3d6f077bb6f 100644 --- a/src/main/agent-hooks/server-observation-provenance.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-observation-provenance.test.ts @@ -2,16 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const LEAF = '11111111-1111-4111-8111-111111111111' const PANE = makePaneKey('tab-1', LEAF) diff --git a/src/main/agent-hooks/server-restored-agent-status.test.ts b/src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts similarity index 92% rename from src/main/agent-hooks/server-restored-agent-status.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts index 49d29fef55e..7ab071e2870 100644 --- a/src/main/agent-hooks/server-restored-agent-status.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-restored-agent-status.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { GOOD_PANE as REMOTE_PANE, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { GOOD_PANE as REMOTE_PANE, PANE } from '../server.test-fixtures' describe('restored agent status', () => { let userDataPath: string diff --git a/src/main/agent-hooks/server-status-persist-nonblocking.test.ts b/src/main/agent-hooks/server/testing/persistence/server-status-persist-nonblocking.test.ts similarity index 90% rename from src/main/agent-hooks/server-status-persist-nonblocking.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-status-persist-nonblocking.test.ts index cfca74a39c4..f9a7e1c65d0 100644 --- a/src/main/agent-hooks/server-status-persist-nonblocking.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-status-persist-nonblocking.test.ts @@ -4,15 +4,15 @@ import * as fsPromises from 'node:fs/promises' import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { AtomicSnapshotWriter } from '../persistence/atomic-snapshot-writer' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { AtomicSnapshotWriter } from '../../../../persistence/atomic-snapshot-writer' type FsModule = typeof fs type FsPromisesModule = typeof fsPromises -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) vi.mock('node:fs', async (importOriginal) => { diff --git a/src/main/agent-hooks/server-status-persist-throttle.test.ts b/src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts similarity index 93% rename from src/main/agent-hooks/server-status-persist-throttle.test.ts rename to src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts index e9dc5042863..68a928815fc 100644 --- a/src/main/agent-hooks/server-status-persist-throttle.test.ts +++ b/src/main/agent-hooks/server/testing/persistence/server-status-persist-throttle.test.ts @@ -2,13 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { STATUS_PERSIST_MIN_INTERVAL_MS } from './server/server-constants' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { AtomicSnapshotWriter } from '../persistence/atomic-snapshot-writer' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { STATUS_PERSIST_MIN_INTERVAL_MS } from '../../server-constants' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { AtomicSnapshotWriter } from '../../../../persistence/atomic-snapshot-writer' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) diff --git a/src/main/agent-hooks/server-agent-presence.test.ts b/src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts similarity index 91% rename from src/main/agent-hooks/server-agent-presence.test.ts rename to src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts index 3dbaad35f30..1eb588b08c5 100644 --- a/src/main/agent-hooks/server-agent-presence.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-agent-presence.test.ts @@ -2,16 +2,16 @@ 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 { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async (): Promise<'live' | 'unverifiable' | 'exited'> => 'unverifiable') ) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-hook-root-acquisition.test.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root-acquisition.test.ts similarity index 97% rename from src/main/agent-hooks/server-hook-root-acquisition.test.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root-acquisition.test.ts index 08ef8a93e59..982b2de7ba6 100644 --- a/src/main/agent-hooks/server-hook-root-acquisition.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root-acquisition.test.ts @@ -2,9 +2,9 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import type { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import type { AgentHookServer } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { NOW, CLAUDE, @@ -23,9 +23,9 @@ import { registerRootTestHarness } from './server-hook-root.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn() })) diff --git a/src/main/agent-hooks/server-hook-root-provenance.test.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root-provenance.test.ts similarity index 96% rename from src/main/agent-hooks/server-hook-root-provenance.test.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root-provenance.test.ts index 862168007bb..d926d208476 100644 --- a/src/main/agent-hooks/server-hook-root-provenance.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root-provenance.test.ts @@ -2,13 +2,13 @@ import { mkdtempSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' -import { PANE } from './server.test-fixtures' +import { PANE } from '../server.test-fixtures' -import '../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import '../../wsl-guest/agent-hook-server' -import '../../wsl-guest/relay-pane-root' -import './local-tmux-managed-pty' +import '../../../../../wsl-guest/agent-hook-server' +import '../../../../../wsl-guest/relay-pane-root' +import '../../../observations/local-tmux-managed-pty' import { NOW, @@ -35,9 +35,9 @@ import { type Proc } from './server-hook-root.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn() })) diff --git a/src/main/agent-hooks/server-hook-root-replay.test.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts similarity index 94% rename from src/main/agent-hooks/server-hook-root-replay.test.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts index 7fb1e4ffdd0..ea3922d640d 100644 --- a/src/main/agent-hooks/server-hook-root-replay.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root-replay.test.ts @@ -2,15 +2,15 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { beforeEach, describe, expect, it, vi } from 'vitest' -import { PANE } from './server.test-fixtures' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { PANE } from '../server.test-fixtures' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' import { readHookRootEvidence, type HookPaneRoot -} from '../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { startOrcadAgentHookServer } from '../orcad/orcad-managed-agent-hooks' +} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { AgentHookRelayEnvelope } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { startOrcadAgentHookServer } from '../../../../orcad/orcad-managed-agent-hooks' import { NOW, CLAUDE, @@ -29,9 +29,9 @@ import { type Proc } from './server-hook-root.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn() })) diff --git a/src/main/agent-hooks/server-hook-root.test-fixtures.ts b/src/main/agent-hooks/server/testing/presence/server-hook-root.test-fixtures.ts similarity index 93% rename from src/main/agent-hooks/server-hook-root.test-fixtures.ts rename to src/main/agent-hooks/server/testing/presence/server-hook-root.test-fixtures.ts index f02642ab2db..c1944c69eed 100644 --- a/src/main/agent-hooks/server-hook-root.test-fixtures.ts +++ b/src/main/agent-hooks/server/testing/presence/server-hook-root.test-fixtures.ts @@ -1,15 +1,15 @@ import { rmSync } from 'node:fs' import { afterEach, beforeEach, expect, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import type { AgentProcessIdentity } from '../../shared/agent-status/process/agent-process-presence' -import { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import type { AgentProcessIdentity } from '../../../../../shared/agent-status/process/agent-process-presence' +import { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' import { readHookRootEvidence, type HookPaneProcessIo, type HookPaneRoot -} from '../../shared/agent-hook-listener/presence/hook-process-root-evidence' -import type { ProcessTableRow } from '../../shared/process-table-snapshot' +} from '../../../../../shared/agent-hook-listener/presence/hook-process-root-evidence' +import type { ProcessTableRow } from '../../../../../shared/process-table-snapshot' // Shared harness for the hook server's pane-root acquisition tests. Each test file mocks // '../telemetry/client', '../telemetry/cohort-classifier' and the process probe module. diff --git a/src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts b/src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts similarity index 88% rename from src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts index d21d4b41347..c314525df3a 100644 --- a/src/main/agent-hooks/server-http-owner-probe-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-http-owner-probe-lifecycle.test.ts @@ -1,12 +1,12 @@ import { afterEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-idle-process-owner.test.ts b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts similarity index 95% rename from src/main/agent-hooks/server-idle-process-owner.test.ts rename to src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts index c09295979e0..f16f83c8204 100644 --- a/src/main/agent-hooks/server-idle-process-owner.test.ts +++ b/src/main/agent-hooks/server/testing/presence/server-idle-process-owner.test.ts @@ -2,16 +2,16 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { buildRuntimeMobileAgentStatus } from '../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import type { probeAgentProcessPresence } from '../../shared/agent-status/process/agent-process-presence-probe' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' +import { buildRuntimeMobileAgentStatus } from '../../../../runtime/session-lifecycle/projection/runtime-mobile-agent-status-builder' +import { getAgentResumeArgv } from '../../../../../shared/agent-launch/startup/agent-resume-argv' +import type { probeAgentProcessPresence } from '../../../../../shared/agent-status/process/agent-process-presence-probe' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn(async () => 'live')) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: probe })) const servers: AgentHookServer[] = [] diff --git a/src/main/agent-hooks/server-amp-normalization.test.ts b/src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts similarity index 92% rename from src/main/agent-hooks/server-amp-normalization.test.ts rename to src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts index bf6f5061b78..8dccccd8d43 100644 --- a/src/main/agent-hooks/server-amp-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/providers/amp/server-amp-normalization.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { _internals } from './server' -import { buildBody } from './server.test-fixtures' +import { _internals } from '../../../agent-hook-server' +import { buildBody } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-antigravity-background-command-hold.test.ts b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-background-command-hold.test.ts similarity index 87% rename from src/main/agent-hooks/server-antigravity-background-command-hold.test.ts rename to src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-background-command-hold.test.ts index ace807b350a..d1b29eaad49 100644 --- a/src/main/agent-hooks/server-antigravity-background-command-hold.test.ts +++ b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-background-command-hold.test.ts @@ -2,10 +2,10 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from './server/program-status/hook-precedence' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status/contracts/agent-status-freshness' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../../agent-hook-server' +import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from '../../../program-status/hook-precedence' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../../shared/agent-status/contracts/agent-status-freshness' +import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures' let dir: string let server: AgentHookServer diff --git a/src/main/agent-hooks/server-antigravity-resume-identity.test.ts b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts similarity index 90% rename from src/main/agent-hooks/server-antigravity-resume-identity.test.ts rename to src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts index bf0f0373028..d33950bbfd3 100644 --- a/src/main/agent-hooks/server-antigravity-resume-identity.test.ts +++ b/src/main/agent-hooks/server/testing/providers/antigravity/server-antigravity-resume-identity.test.ts @@ -2,13 +2,13 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { resumeRecordFromStatus } from '../../shared/agent-session/lifecycle/agent-resume-record-from-status' -import { getAgentResumeArgv } from '../../shared/agent-launch/startup/agent-resume-argv' -import { TRANSCRIPT_MAX_SCAN_BYTES } from '../../shared/agent-hook-listener/transcript-reader' -import { AgentHookServer } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createHookListenerState } from '../../../../../../shared/agent-hook-listener/listener-state' +import { resumeRecordFromStatus } from '../../../../../../shared/agent-session/lifecycle/agent-resume-record-from-status' +import { getAgentResumeArgv } from '../../../../../../shared/agent-launch/startup/agent-resume-argv' +import { TRANSCRIPT_MAX_SCAN_BYTES } from '../../../../../../shared/agent-hook-listener/transcript-reader' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' // Exact origin metadata and hook shape captured from agy 1.4.11; paths/IDs are test-local. const ROOT = '6bba92d4-47e1-440a-9571-b12bb2d474bc' diff --git a/src/main/agent-hooks/server-claude-blocked-prompt.test.ts b/src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts similarity index 88% rename from src/main/agent-hooks/server-claude-blocked-prompt.test.ts rename to src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts index 7110215005a..92df34ee30c 100644 --- a/src/main/agent-hooks/server-claude-blocked-prompt.test.ts +++ b/src/main/agent-hooks/server/testing/providers/claude/server-claude-blocked-prompt.test.ts @@ -1,10 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { createProgramStatusProjector } from '../../shared/program-status/agent-status-projector' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures' +import { createProgramStatusProjector } from '../../../../../../shared/program-status/agent-status-projector' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) +vi.mock('../../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn() })) let server: AgentHookServer let projector: ReturnType diff --git a/src/main/agent-hooks/server-claude-config-dir-observation.test.ts b/src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts similarity index 74% rename from src/main/agent-hooks/server-claude-config-dir-observation.test.ts rename to src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts index 91c4082e2f4..51245f74e48 100644 --- a/src/main/agent-hooks/server-claude-config-dir-observation.test.ts +++ b/src/main/agent-hooks/server/testing/providers/claude/server-claude-config-dir-observation.test.ts @@ -2,14 +2,14 @@ import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, GOOD_PANE, PANE, postHookEvent } from './server.test-fixtures' -import { ClaudeObservedConfigDirs } from '../claude-accounts/claude-observed-config-dirs' -import { installClaudeObservedConfigDirs } from '../claude-accounts/claude-profile-installed-router' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, GOOD_PANE, PANE, postHookEvent } from '../../server.test-fixtures' +import { ClaudeObservedConfigDirs } from '../../../../../claude-accounts/claude-observed-config-dirs' +import { installClaudeObservedConfigDirs } from '../../../../../claude-accounts/claude-profile-installed-router' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: async () => 'live' })) diff --git a/src/main/agent-hooks/server-claude-normalization.test.ts b/src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts similarity index 95% rename from src/main/agent-hooks/server-claude-normalization.test.ts rename to src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts index 6318211f1ba..4d6f9f42f38 100644 --- a/src/main/agent-hooks/server-claude-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/providers/claude/server-claude-normalization.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { _internals } from './server' -import { buildBody } from './server.test-fixtures' +import { _internals } from '../../../agent-hook-server' +import { buildBody } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-codex-capacity.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts similarity index 92% rename from src/main/agent-hooks/server-codex-capacity.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts index 879b52edb24..9df7e909d78 100644 --- a/src/main/agent-hooks/server-codex-capacity.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-capacity.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' -import { CODEX_CAPACITY_MESSAGE } from '../../shared/codex-native-notice' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../../server.test-fixtures' +import { CODEX_CAPACITY_MESSAGE } from '../../../../../../shared/codex-native-notice' afterEach(() => _internals.resetCachesForTests()) diff --git a/src/main/agent-hooks/server-codex-interrupt-hook.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts similarity index 92% rename from src/main/agent-hooks/server-codex-interrupt-hook.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts index aa8360341ef..cd72f4f9ee3 100644 --- a/src/main/agent-hooks/server-codex-interrupt-hook.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-interrupt-hook.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-codex-review-turn-end.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts similarity index 95% rename from src/main/agent-hooks/server-codex-review-turn-end.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts index b1a0dc190f7..c437a330f66 100644 --- a/src/main/agent-hooks/server-codex-review-turn-end.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-review-turn-end.test.ts @@ -9,13 +9,13 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { RelayAgentHookServer } from '../../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, postHookEvent } from '../../server.test-fixtures' // Captured from a completed Codex CLI 0.159.0 /review; session and turn IDs were replaced. const reviewRecords = readFileSync( - new URL('./__fixtures__/codex-review-child-0159.jsonl', import.meta.url), + new URL('../../../../__fixtures__/codex-review-child-0159.jsonl', import.meta.url), 'utf8' ) .trimEnd() diff --git a/src/main/agent-hooks/server-codex-side-thread.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts similarity index 98% rename from src/main/agent-hooks/server-codex-side-thread.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts index bf9d3a9a323..b2602cf3297 100644 --- a/src/main/agent-hooks/server-codex-side-thread.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-side-thread.test.ts @@ -2,8 +2,8 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../../agent-hook-server' +import { buildBody, postHookEvent } from '../../server.test-fixtures' // Shapes captured from Codex 0.164: a /side fork is its own session with no rollout. const MAIN = '01a16f91-ac03-73f2-acdc-2bc83dbedce3' diff --git a/src/main/agent-hooks/server-codex-subagent-transcript.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts similarity index 97% rename from src/main/agent-hooks/server-codex-subagent-transcript.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts index 744554663a0..575ca65c93c 100644 --- a/src/main/agent-hooks/server-codex-subagent-transcript.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-subagent-transcript.test.ts @@ -3,8 +3,8 @@ import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') const CHILD_ID = '019fa65f-3144-7151-9c02-cff7a28f316f' diff --git a/src/main/agent-hooks/server-codex-turn-interruption.test.ts b/src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts similarity index 97% rename from src/main/agent-hooks/server-codex-turn-interruption.test.ts rename to src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts index d3ffcb886e8..5cdced2e665 100644 --- a/src/main/agent-hooks/server-codex-turn-interruption.test.ts +++ b/src/main/agent-hooks/server/testing/providers/codex/server-codex-turn-interruption.test.ts @@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer } from '../../../agent-hook-server' +import { PANE } from '../../server.test-fixtures' const line = (payload: unknown): string => `${JSON.stringify({ type: 'event_msg', payload })}\n` diff --git a/src/main/agent-hooks/server-cursor-normalization.test.ts b/src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts similarity index 90% rename from src/main/agent-hooks/server-cursor-normalization.test.ts rename to src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts index 9948bf9e90f..f61b10697c1 100644 --- a/src/main/agent-hooks/server-cursor-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/providers/cursor/server-cursor-normalization.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import { agentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-grok-background-status.test.ts b/src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts similarity index 94% rename from src/main/agent-hooks/server-grok-background-status.test.ts rename to src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts index b298d7ceec4..399b5bc6f81 100644 --- a/src/main/agent-hooks/server-grok-background-status.test.ts +++ b/src/main/agent-hooks/server/testing/providers/grok/server-grok-background-status.test.ts @@ -2,17 +2,19 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { AgentSessionTransitionRecorder } from '../stats/agent-session-transition-recorder' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { AgentSessionTransitionRecorder } from '../../../../../stats/agent-session-transition-recorder' +import { buildBody, PANE } from '../../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: getCohortAtEmitMock +})) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-grok-cancel.test.ts b/src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts similarity index 83% rename from src/main/agent-hooks/server-grok-cancel.test.ts rename to src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts index 52f0a1d5e04..1237c8122ee 100644 --- a/src/main/agent-hooks/server-grok-cancel.test.ts +++ b/src/main/agent-hooks/server/testing/providers/grok/server-grok-cancel.test.ts @@ -1,16 +1,18 @@ // Grok 1.0.70: Esc never cancels and Ctrl+C can open a stop dialog; only StopCancelled reports a cancel. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' -import type { AgentInterruptInputIntent } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' +import { AgentHookServer, _internals } from '../../../agent-hook-server' +import { buildBody, PANE } from '../../server.test-fixtures' +import type { AgentInterruptInputIntent } from '../../../../../../shared/agent-status/lifecycle/agent-interrupt-intent' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: getCohortAtEmitMock +})) beforeEach(() => { _internals.resetCachesForTests() diff --git a/src/main/agent-hooks/server-grok-discovery.test.ts b/src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts similarity index 94% rename from src/main/agent-hooks/server-grok-discovery.test.ts rename to src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts index 5570ab9d8cf..fd5ab84b161 100644 --- a/src/main/agent-hooks/server-grok-discovery.test.ts +++ b/src/main/agent-hooks/server/testing/providers/grok/server-grok-discovery.test.ts @@ -2,9 +2,9 @@ import { mkdirSync, mkdtempSync, 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 * as agentHookListener from '../../shared/agent-hook-listener/grok-result-discovery' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' +import * as agentHookListener from '../../../../../../shared/agent-hook-listener/grok-result-discovery' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') diff --git a/src/main/agent-hooks/server-muse-session-log-poll.test.ts b/src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts similarity index 95% rename from src/main/agent-hooks/server-muse-session-log-poll.test.ts rename to src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts index f0f60cc36f5..34cc0f7728f 100644 --- a/src/main/agent-hooks/server-muse-session-log-poll.test.ts +++ b/src/main/agent-hooks/server/testing/providers/muse/server-muse-session-log-poll.test.ts @@ -3,9 +3,9 @@ import { appendFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'n import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import type { EnrichedAgentHookEventPayload } from './server/server-types' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' +import type { EnrichedAgentHookEventPayload } from '../../../server-types' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' const PANE_KEY = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') const SESSION_ID = '01a0caa3-0e77-7d41-bad7-46283a45633d' diff --git a/src/main/agent-hooks/server-opencode-tui-identity.test.ts b/src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts similarity index 88% rename from src/main/agent-hooks/server-opencode-tui-identity.test.ts rename to src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts index bd87e0e315a..84bb1a998e4 100644 --- a/src/main/agent-hooks/server-opencode-tui-identity.test.ts +++ b/src/main/agent-hooks/server/testing/providers/opencode/server-opencode-tui-identity.test.ts @@ -2,9 +2,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer } from './server' -import { lookupOpenCodeSessionPane } from '../../shared/agent-hook-listener/opencode-session-registry' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../../agent-hook-server' +import { lookupOpenCodeSessionPane } from '../../../../../../shared/agent-hook-listener/opencode-session-registry' +import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id' const PANE_A = makePaneKey('tab-a', 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa') diff --git a/src/main/agent-hooks/server-status-listener-fanout.test.ts b/src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts similarity index 96% rename from src/main/agent-hooks/server-status-listener-fanout.test.ts rename to src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts index 8120569fb0f..2e5d11ed9e4 100644 --- a/src/main/agent-hooks/server-status-listener-fanout.test.ts +++ b/src/main/agent-hooks/server/testing/publication/server-status-listener-fanout.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, GOOD_PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, GOOD_PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/ended-process-reconciliation.test.ts b/src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts similarity index 96% rename from src/main/agent-hooks/ended-process-reconciliation.test.ts rename to src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts index 9d0be0aceba..9a94104ed0e 100644 --- a/src/main/agent-hooks/ended-process-reconciliation.test.ts +++ b/src/main/agent-hooks/server/testing/reconciliation/ended-process-reconciliation.test.ts @@ -2,9 +2,9 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import { AgentHookServer } from './server' -import { buildBody, postHookEvent } from './server.test-fixtures' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, postHookEvent } from '../server.test-fixtures' const LEAF = '11111111-1111-4111-8111-111111111111' const PANE = makePaneKey('tab-1', LEAF) diff --git a/src/main/agent-hooks/server-ingest-remote-codex-question.test.ts b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts similarity index 87% rename from src/main/agent-hooks/server-ingest-remote-codex-question.test.ts rename to src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts index a4a8469e713..b225204259e 100644 --- a/src/main/agent-hooks/server-ingest-remote-codex-question.test.ts +++ b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-question.test.ts @@ -1,15 +1,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' import { createHookListenerState, seedLegacyAgentStatusForTests -} from '../../shared/agent-hook-listener/listener-state' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' -import { AgentHookServer, _internals } from './server' -import { PANE, buildBody } from './server.test-fixtures' +} from '../../../../../shared/agent-hook-listener/listener-state' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE, buildBody } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts similarity index 89% rename from src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts rename to src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts index fd9be19a4e2..4b8b6e4c152 100644 --- a/src/main/agent-hooks/server-ingest-remote-codex-transcript.test.ts +++ b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote-codex-transcript.test.ts @@ -2,17 +2,17 @@ import { appendFileSync, mkdtempSync, 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 { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { createShedSubagentsField } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { pollCodexTranscriptStatus } from '../../shared/agent-hook-listener/providers/codex-transcript-poll' -import { transcriptPollUpdate } from '../../shared/agent-hook-listener/transcript-poll-policy' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' -import { AgentHookServer, _internals } from './server' -import { PANE, buildBody } from './server.test-fixtures' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import { createShedSubagentsField } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { pollCodexTranscriptStatus } from '../../../../../shared/agent-hook-listener/providers/codex-transcript-poll' +import { transcriptPollUpdate } from '../../../../../shared/agent-hook-listener/transcript-poll-policy' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE, buildBody } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-ingest-remote.test.ts b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts similarity index 79% rename from src/main/agent-hooks/server-ingest-remote.test.ts rename to src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts index d8286646eb5..1c727f7beed 100644 --- a/src/main/agent-hooks/server-ingest-remote.test.ts +++ b/src/main/agent-hooks/server/testing/remote-ingress/server-ingest-remote.test.ts @@ -1,18 +1,18 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' -import { AGENT_STATUS_RUNS_RUNTIME_CAPABILITY } from '../../shared/agent-status/contracts/agent-status-run-capability' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' +import { AGENT_STATUS_RUNS_RUNTIME_CAPABILITY } from '../../../../../shared/agent-status/contracts/agent-status-run-capability' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts b/src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts similarity index 90% rename from src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts rename to src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts index 24541691f72..71462710607 100644 --- a/src/main/agent-hooks/server-relayed-claude-permission-replay.test.ts +++ b/src/main/agent-hooks/server/testing/replay/server-relayed-claude-permission-replay.test.ts @@ -3,20 +3,20 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' -import { hookAt, loadCapture } from './claude-cancel-capture.test-fixture' -import selfDenied from '../claude/__fixtures__/claude-self-denied-permission-hooks.json' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import type { AgentHookRelayEnvelope } from '../../../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' +import { hookAt, loadCapture } from '../interruptions/claude-cancel-capture.test-fixture' +import selfDenied from '../../../../claude/__fixtures__/claude-self-denied-permission-hooks.json' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) const records = loadCapture('claude-permission-approve-deny-hooks') const prompt = hookAt(records, 0).payload diff --git a/src/main/agent-hooks/server-replay-evidence-clock.test.ts b/src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts similarity index 86% rename from src/main/agent-hooks/server-replay-evidence-clock.test.ts rename to src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts index e9c0bb4b3a4..599dfe50a0a 100644 --- a/src/main/agent-hooks/server-replay-evidence-clock.test.ts +++ b/src/main/agent-hooks/server/testing/replay/server-replay-evidence-clock.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state' -import { normalizeHookPayload } from '../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import type { EnrichedAgentHookEventPayload } from './server/server-types' -import { buildBody, PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' +import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' +import type { EnrichedAgentHookEventPayload } from '../../server-types' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const CONNECTION = 'conn-1' const T0 = 1_800_000_000_000 diff --git a/src/main/agent-hooks/spool.test.ts b/src/main/agent-hooks/server/testing/replay/spool.test.ts similarity index 96% rename from src/main/agent-hooks/spool.test.ts rename to src/main/agent-hooks/server/testing/replay/spool.test.ts index 412246660b6..8dd464b3d81 100644 --- a/src/main/agent-hooks/spool.test.ts +++ b/src/main/agent-hooks/server/testing/replay/spool.test.ts @@ -17,12 +17,12 @@ import { drainAgentHookSpoolAsync, launchTokenHash, type SpoolRecord -} from '../../shared/agent-hook-listener/transport/agent-hook-spool' -import { AgentHookServer, _internals } from './server' -import { buildBody } from './server.test-fixtures' -import { _internals as codexInternals } from '../codex/hooks/installation/hook-service' -import { getManagedScript as getClaudeManagedScript } from '../claude/hook-script' -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' +} from '../../../../../shared/agent-hook-listener/transport/agent-hook-spool' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody } from '../server.test-fixtures' +import { _internals as codexInternals } from '../../../../codex/hooks/installation/hook-service' +import { getManagedScript as getClaudeManagedScript } from '../../../../claude/hook-script' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' describe('agent hook spool', () => { it('waits for a newline before replaying a complete-looking final record', async () => { diff --git a/src/main/agent-hooks/server.test-fixtures.ts b/src/main/agent-hooks/server/testing/server.test-fixtures.ts similarity index 93% rename from src/main/agent-hooks/server.test-fixtures.ts rename to src/main/agent-hooks/server/testing/server.test-fixtures.ts index 1479f9330ab..9b380067b2f 100644 --- a/src/main/agent-hooks/server.test-fixtures.ts +++ b/src/main/agent-hooks/server/testing/server.test-fixtures.ts @@ -1,5 +1,5 @@ -import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' -import type { AgentHookServer } from './server' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import type { AgentHookServer } from '../agent-hook-server' export const LEAF_1 = '11111111-1111-4111-8111-111111111111' export const LEAF_2 = '22222222-2222-4222-8222-222222222222' diff --git a/src/main/agent-hooks/server-ingest-structured-state-clock.test.ts b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts similarity index 89% rename from src/main/agent-hooks/server-ingest-structured-state-clock.test.ts rename to src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts index f4ff1bffb5e..c919c8780ca 100644 --- a/src/main/agent-hooks/server-ingest-structured-state-clock.test.ts +++ b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-state-clock.test.ts @@ -1,10 +1,10 @@ // Use the session lifecycle clock across projections; older summaries retain ingest continuity. import { beforeEach, describe, expect, it } from 'vitest' -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer, _internals } from './server' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' +import type { AgentChildWorkEvidence } from '../../../../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { makeStructuredAgentStatusSubject } from '../../../../../shared/agent-status/contracts/agent-status-subject' +import { AgentHookServer, _internals } from '../../agent-hook-server' const SESSION = 'b2c3d4e5-f6a7-4b8c-9d0e-1f2a3b4c5d6e' const SUBJECT = makeStructuredAgentStatusSubject( diff --git a/src/main/agent-hooks/server-ingest-structured-status.test.ts b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts similarity index 92% rename from src/main/agent-hooks/server-ingest-structured-status.test.ts rename to src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts index 08659472d24..3473b8781db 100644 --- a/src/main/agent-hooks/server-ingest-structured-status.test.ts +++ b/src/main/agent-hooks/server/testing/structured-ingress/server-ingest-structured-status.test.ts @@ -1,28 +1,28 @@ -import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' +import { makeStructuredAgentStatusSubject } from '../../../../../shared/agent-status/contracts/agent-status-subject' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' -import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' -import { isFreshNonDoneAgentStatus } from '../../shared/agent-status/contracts/agent-status-freshness' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' +import type { AgentChildWorkEvidence } from '../../../../../shared/agent-status/child-work/agent-status-child-work-evidence' +import { isFreshNonDoneAgentStatus } from '../../../../../shared/agent-status/contracts/agent-status-freshness' import { structuredAgentSessionPaneKey, structuredAgentSessionTabId -} from '../../shared/agent-session/view/structured-agent-session-projection' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +} from '../../../../../shared/agent-session/view/structured-agent-session-projection' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-structured-canonical-status.test.ts b/src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts similarity index 89% rename from src/main/agent-hooks/server-structured-canonical-status.test.ts rename to src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts index 0ec09ac098f..4d79694cf68 100644 --- a/src/main/agent-hooks/server-structured-canonical-status.test.ts +++ b/src/main/agent-hooks/server/testing/structured-ingress/server-structured-canonical-status.test.ts @@ -3,17 +3,17 @@ import { makeStructuredAgentStatusSubject, type AgentStatusExecutionScope, type AgentStatusStructuredSessionSubject -} from '../../shared/agent-status/contracts/agent-status-subject' -import type { AgentSessionStatusSummary } from '../../shared/agent-session/agent-session-wire' +} from '../../../../../shared/agent-status/contracts/agent-status-subject' +import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' import { structuredAgentSessionPaneKey, structuredAgentSessionTabId -} from '../../shared/agent-session/view/structured-agent-session-projection' -import { AgentHookServer } from './server' -import { PANE } from './server.test-fixtures' +} from '../../../../../shared/agent-session/view/structured-agent-session-projection' +import { AgentHookServer } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) const SESSION = 'canonical-session-one' const SCOPE: AgentStatusExecutionScope = { diff --git a/src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts similarity index 89% rename from src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts rename to src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts index 6038b0f28eb..0c9aaed459f 100644 --- a/src/main/agent-hooks/server-claude-owed-notification-expiry.test.ts +++ b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-owed-notification-expiry.test.ts @@ -1,15 +1,15 @@ // No hook fires at lease expiry, so the server must release owed-notification holds itself. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { CLAUDE_OWED_TASK_NOTIFICATION_LEASE_MS } from '../../shared/agent-hook-listener/providers/claude-owed-task-notifications' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from './server.test-fixtures' +import { CLAUDE_OWED_TASK_NOTIFICATION_LEASE_MS } from '../../../../../shared/agent-hook-listener/providers/claude-owed-task-notifications' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent, RUNNING_SHELL } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) })) // The fixture's owner process is fictional; the pane's owning Claude is still running. -vi.mock('../../shared/agent-status/process/agent-process-presence-probe', () => ({ +vi.mock('../../../../../shared/agent-status/process/agent-process-presence-probe', () => ({ probeAgentProcessPresence: vi.fn(async () => 'live') })) diff --git a/src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts similarity index 94% rename from src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts rename to src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts index 4d0e98c6387..bb306de2ae9 100644 --- a/src/main/agent-hooks/server-claude-task-wakeup-lifecycle.test.ts +++ b/src/main/agent-hooks/server/testing/task-wakeup/server-claude-task-wakeup-lifecycle.test.ts @@ -2,14 +2,14 @@ import { readFileSync, mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' -import { AgentHookServer, _internals } from './server' -import { createRuntimeAutomationRunTerminalObserver } from '../automations/runtime-terminal-run-observer' +import { RelayAgentHookServer } from '../../../../../wsl-guest/agent-hook-server' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { createRuntimeAutomationRunTerminalObserver } from '../../../../automations/runtime-terminal-run-observer' import { createTranscriptPane, TRANSCRIPT_PANE_PTY_ID -} from '../runtime/orca-runtime-tests/agent-transcript-pane-test-harness' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +} from '../../../../runtime/orca-runtime-tests/agent-transcript-pane-test-harness' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' vi.mock('electron', () => ({ BrowserWindow: { fromId: vi.fn(() => null) }, @@ -18,12 +18,15 @@ vi.mock('electron', () => ({ app: { getPath: vi.fn(() => '/tmp') } })) -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) })) type CapturedHook = { scenario: string; kind: string; payload?: Record } const hooks: CapturedHook[] = readFileSync( - join(import.meta.dirname, '../../shared/__fixtures__/claude-task-notification-hooks.jsonl'), + join( + import.meta.dirname, + '../../../../../shared/__fixtures__/claude-task-notification-hooks.jsonl' + ), 'utf8' ) .trim() @@ -190,7 +193,7 @@ describe.each([false, true])('real automation Claude wake-up oracle remote=%s', const server = await host(remote, 'transcript-launch') const controller = new AbortController() const ready = readFileSync( - join(import.meta.dirname, '../runtime/__fixtures__/claude-ready-task-wakeup.txt'), + join(import.meta.dirname, '../../../../runtime/__fixtures__/claude-ready-task-wakeup.txt'), 'utf8' ) const pane = await createTranscriptPane( diff --git a/src/main/agent-hooks/server-prompt-sent-telemetry.test.ts b/src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts similarity index 96% rename from src/main/agent-hooks/server-prompt-sent-telemetry.test.ts rename to src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts index 5013ec39c1d..3488f31c9ec 100644 --- a/src/main/agent-hooks/server-prompt-sent-telemetry.test.ts +++ b/src/main/agent-hooks/server/testing/telemetry/server-prompt-sent-telemetry.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE, GOOD_PANE, FRESH_PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE, GOOD_PANE, FRESH_PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-ingest-terminal-status.test.ts b/src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts similarity index 96% rename from src/main/agent-hooks/server-ingest-terminal-status.test.ts rename to src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts index 7d2d02f363e..a03ad6e54b4 100644 --- a/src/main/agent-hooks/server-ingest-terminal-status.test.ts +++ b/src/main/agent-hooks/server/testing/terminal-ingress/server-ingest-terminal-status.test.ts @@ -1,17 +1,17 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/server-process-lifetime-status.test.ts b/src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts similarity index 96% rename from src/main/agent-hooks/server-process-lifetime-status.test.ts rename to src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts index 262c82f4db7..359054798d4 100644 --- a/src/main/agent-hooks/server-process-lifetime-status.test.ts +++ b/src/main/agent-hooks/server/testing/terminal-ingress/server-process-lifetime-status.test.ts @@ -2,8 +2,8 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { AgentHookServer } from '../../agent-hook-server' +import { buildBody, PANE, postHookEvent } from '../server.test-fixtures' let dir: string let server: AgentHookServer diff --git a/src/main/agent-hooks/server-tmux-canonical.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts similarity index 86% rename from src/main/agent-hooks/server-tmux-canonical.test.ts rename to src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts index 01d0baad4b9..7ff17f52581 100644 --- a/src/main/agent-hooks/server-tmux-canonical.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-canonical.test.ts @@ -1,18 +1,20 @@ import { createHash } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { postHookEvent } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { postHookEvent } from '../server.test-fixtures' import { TMUX_TEST_PANE, TMUX_TEST_ROOT, TMUX_TEST_ROWS, tmuxTestBody -} from '../../shared/tmux-status.test-fixture' +} from '../../../../../shared/tmux-status.test-fixture' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const probe = vi.hoisted(() => vi.fn()) -vi.mock('../../shared/tmux-host-attachment-probe', () => ({ probeTmuxHostAttachments: probe })) +vi.mock('../../../../../shared/tmux-host-attachment-probe', () => ({ + probeTmuxHostAttachments: probe +})) class CanonicalTestServer extends AgentHookServer { hasLegacyRow(): boolean { return this.state.lastStatusByPaneKey.has(TMUX_TEST_PANE) diff --git a/src/main/agent-hooks/server-tmux-wire.test.ts b/src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts similarity index 89% rename from src/main/agent-hooks/server-tmux-wire.test.ts rename to src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts index 7b9ac0d0cf7..5944f21e770 100644 --- a/src/main/agent-hooks/server-tmux-wire.test.ts +++ b/src/main/agent-hooks/server/testing/tmux/server-tmux-wire.test.ts @@ -1,10 +1,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer, _internals } from './server' -import { PANE } from './server.test-fixtures' -import { buildRelayHookEnvelope } from '../../wsl-guest/agent-hook-envelope-build' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { PANE } from '../server.test-fixtures' +import { buildRelayHookEnvelope } from '../../../../../wsl-guest/agent-hook-envelope-build' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) const time = 1_800_000_000_000 const envelope = { source: 'opencode', diff --git a/src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts b/src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts similarity index 78% rename from src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts rename to src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts index d39ceb7d270..bbed8b3c40f 100644 --- a/src/main/agent-hooks/server-agent-tool-plugin-hooks.test.ts +++ b/src/main/agent-hooks/server/testing/tool-events/server-agent-tool-plugin-hooks.test.ts @@ -1,12 +1,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PluginHookName } from '../../shared/plugins/contributions/plugin-hook-contribution' -import { setPluginHookRunner } from '../plugins/hooks/plugin-hook-dispatch' -import { setAgentToolHookTerminalResolver } from './agent-tool-call-reader' -import { AgentHookServer, _internals } from './server' -import { buildBody, PANE } from './server.test-fixtures' +import type { PluginHookName } from '../../../../../shared/plugins/contributions/plugin-hook-contribution' +import { setPluginHookRunner } from '../../../../plugins/hooks/plugin-hook-dispatch' +import { setAgentToolHookTerminalResolver } from '../../../tool-events/agent-tool-call-reader' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody, PANE } from '../server.test-fixtures' -vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({ nth_repo_added: 2 }) })) diff --git a/src/main/agent-hooks/server-copilot-normalization.test.ts b/src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts similarity index 96% rename from src/main/agent-hooks/server-copilot-normalization.test.ts rename to src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts index bd0c75609db..6173fc19da4 100644 --- a/src/main/agent-hooks/server-copilot-normalization.test.ts +++ b/src/main/agent-hooks/server/testing/transcripts/server-transcript-result-retry.test.ts @@ -2,19 +2,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { AgentHookServer, _internals } from './server' -import { buildBody } from './server.test-fixtures' +import { AgentHookServer, _internals } from '../../agent-hook-server' +import { buildBody } from '../server.test-fixtures' const { getCohortAtEmitMock, trackMock } = vi.hoisted(() => ({ getCohortAtEmitMock: vi.fn(), trackMock: vi.fn() })) -vi.mock('../telemetry/client', () => ({ +vi.mock('../../../../telemetry/client', () => ({ track: trackMock })) -vi.mock('../telemetry/cohort-classifier', () => ({ +vi.mock('../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: getCohortAtEmitMock })) diff --git a/src/main/agent-hooks/agent-tool-call-reader.ts b/src/main/agent-hooks/tool-events/agent-tool-call-reader.ts similarity index 88% rename from src/main/agent-hooks/agent-tool-call-reader.ts rename to src/main/agent-hooks/tool-events/agent-tool-call-reader.ts index 0d7f62ad9ed..3527e45afc6 100644 --- a/src/main/agent-hooks/agent-tool-call-reader.ts +++ b/src/main/agent-hooks/tool-events/agent-tool-call-reader.ts @@ -1,15 +1,15 @@ import type { z } from 'zod' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import type { AgentHookEventPayload } from '../../shared/agent-hook-listener/listener-event' -import { normalizeHookEventName } from '../../shared/agent-hook-listener/provider-event-names' -import { parseAgentHookJson } from '../../shared/agent-hook-listener/request-body' -import { parseJsonObjectString } from '../../shared/agent-hook-listener/interactive-tool' +import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' +import { normalizeHookEventName } from '../../../shared/agent-hook-listener/provider-event-names' +import { parseAgentHookJson } from '../../../shared/agent-hook-listener/request-body' +import { parseJsonObjectString } from '../../../shared/agent-hook-listener/interactive-tool' import { normalizeCopilotEventName, readCopilotToolCall, resolveCopilotEventName -} from '../../shared/agent-hook-listener/providers/copilot-tool-fields' -import type { agentToolAfterHookPayloadSchema } from '../../shared/plugins/events/plugin-hook-payloads' +} from '../../../shared/agent-hook-listener/providers/copilot-tool-fields' +import type { agentToolAfterHookPayloadSchema } from '../../../shared/plugins/events/plugin-hook-payloads' const BEFORE_EVENTS = new Set([ 'pre_tool_use', diff --git a/src/main/agent-hooks/agent-tool-plugin-hooks.test.ts b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts similarity index 90% rename from src/main/agent-hooks/agent-tool-plugin-hooks.test.ts rename to src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts index 7b39e961aee..19a470c8c12 100644 --- a/src/main/agent-hooks/agent-tool-plugin-hooks.test.ts +++ b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.test.ts @@ -1,8 +1,8 @@ import type { ServerResponse } from 'node:http' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PluginHookName } from '../../shared/plugins/contributions/plugin-hook-contribution' -import type { PluginHookChainOutcome } from '../../shared/plugins/workers/plugin-hook-chain' -import { setPluginHookRunner } from '../plugins/hooks/plugin-hook-dispatch' +import type { PluginHookName } from '../../../shared/plugins/contributions/plugin-hook-contribution' +import type { PluginHookChainOutcome } from '../../../shared/plugins/workers/plugin-hook-chain' +import { setPluginHookRunner } from '../../plugins/hooks/plugin-hook-dispatch' import { answerAgentToolPluginHooks, respondAfterAgentToolPluginHooks diff --git a/src/main/agent-hooks/agent-tool-plugin-hooks.ts b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.ts similarity index 94% rename from src/main/agent-hooks/agent-tool-plugin-hooks.ts rename to src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.ts index 0fd41298dd7..b983d058624 100644 --- a/src/main/agent-hooks/agent-tool-plugin-hooks.ts +++ b/src/main/agent-hooks/tool-events/agent-tool-plugin-hooks.ts @@ -1,12 +1,12 @@ import type { IncomingHttpHeaders, ServerResponse } from 'node:http' -import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { PLUGIN_HOOK_SPECS } from '../../shared/plugins/events/plugin-hook-payloads' +import type { AgentHookSource } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { PLUGIN_HOOK_SPECS } from '../../../shared/plugins/events/plugin-hook-payloads' import { notifyPluginHook, PluginHookDeniedError, pluginHookWanted, runPluginHook -} from '../plugins/hooks/plugin-hook-dispatch' +} from '../../plugins/hooks/plugin-hook-dispatch' import { readAgentToolCall, type AgentToolCallOwner } from './agent-tool-call-reader' /** Sent by hook scripts that print Orca's answer as Claude Code's PreToolUse decision. */ diff --git a/src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts b/src/main/agent-hooks/transport/ssh-agent-hook-interrupt-reconciliation.ts similarity index 72% rename from src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts rename to src/main/agent-hooks/transport/ssh-agent-hook-interrupt-reconciliation.ts index 6413152e5af..d21a8c35790 100644 --- a/src/main/agent-hooks/ssh-agent-hook-interrupt-reconciliation.ts +++ b/src/main/agent-hooks/transport/ssh-agent-hook-interrupt-reconciliation.ts @@ -1,6 +1,6 @@ -import type { AgentHookServer } from './server' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { AGENT_HOOK_INFER_INTERRUPT_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-interrupt-reconciliation' +import type { AgentHookServer } from '../server/agent-hook-server' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { AGENT_HOOK_INFER_INTERRUPT_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-interrupt-reconciliation' /** A host revision proves this relay supports the command; older relays keep the legacy path. */ export function bindRemoteClaudeInterruptReconciliation( diff --git a/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts b/src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts rename to src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts index 98a192efd91..ed1ed3ded3e 100644 --- a/src/main/agent-hooks/wsl-hook-relay-live.integration.test.ts +++ b/src/main/agent-hooks/wsl-relay/testing/wsl-hook-relay-live.integration.test.ts @@ -13,10 +13,10 @@ import { delimiter, join } from 'node:path' import { createServer } from 'node:net' import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from './server' -import { WslHookRelayManager } from './wsl-hook-relay-manager' -import { createManagedHookLocalFilesystem } from './managed-hook-local-filesystem.test-fixture' -import { codexHookService } from '../codex/hooks/installation/hook-service' +import { AgentHookServer } from '../../server/agent-hook-server' +import { WslHookRelayManager } from '../wsl-hook-relay-manager' +import { createManagedHookLocalFilesystem } from '../../installation/remote/testing/managed-hook-local-filesystem.test-fixture' +import { codexHookService } from '../../../codex/hooks/installation/hook-service' const BUNDLE_DIR = join(process.cwd(), 'out', 'relay', 'wsl') const BUNDLE_JS = join(BUNDLE_DIR, 'wsl-agent-hook-relay.js') diff --git a/src/main/agent-hooks/wsl-agent-plugin-readiness.ts b/src/main/agent-hooks/wsl-relay/wsl-agent-plugin-readiness.ts similarity index 82% rename from src/main/agent-hooks/wsl-agent-plugin-readiness.ts rename to src/main/agent-hooks/wsl-relay/wsl-agent-plugin-readiness.ts index 78727a9b930..5a766c2ff30 100644 --- a/src/main/agent-hooks/wsl-agent-plugin-readiness.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-agent-plugin-readiness.ts @@ -1,17 +1,17 @@ -import { getAgentLaunchExecutableName } from '../../shared/agent-launch/startup/agent-command-line-intent' +import { getAgentLaunchExecutableName } from '../../../shared/agent-launch/startup/agent-command-line-intent' import { isAgentStatusHooksEnabledForAgent, type AgentStatusHooksSettings -} from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import type { ClaudeAgentViewSettings } from '../../shared/claude-agent-view' +} from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import type { ClaudeAgentViewSettings } from '../../../shared/claude-agent-view' import { detectExplicitPiAgentKindFromCommand, isPiCompatibleAgentType, type PiAgentKind -} from '../../shared/pi-agent-kind' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +} from '../../../shared/pi-agent-kind' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { wslHookRelayManager, type WslHookRelayManager } from './wsl-hook-relay-manager' -import { blockedWslDistroForExec } from '../wsl/discovery/wsl-background-exec-gate' +import { blockedWslDistroForExec } from '../../wsl/discovery/wsl-background-exec-gate' export async function awaitExplicitAgentPluginGuestReadiness(args: { isWsl: boolean diff --git a/src/main/agent-hooks/wsl-bridge-daemon-sessions.ts b/src/main/agent-hooks/wsl-relay/wsl-bridge-daemon-sessions.ts similarity index 89% rename from src/main/agent-hooks/wsl-bridge-daemon-sessions.ts rename to src/main/agent-hooks/wsl-relay/wsl-bridge-daemon-sessions.ts index 519eabbb3c1..bf59f85bddc 100644 --- a/src/main/agent-hooks/wsl-bridge-daemon-sessions.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-bridge-daemon-sessions.ts @@ -6,9 +6,9 @@ import { getDaemonProvider, listLiveDaemonSessions -} from '../daemon/providers/lifecycle/daemon-provider-state' -import type { SessionInfo } from '../daemon/protocol/daemon-session-info' -import { parseWslUncPath } from '../../shared/wsl-paths' +} from '../../daemon/providers/lifecycle/daemon-provider-state' +import type { SessionInfo } from '../../daemon/protocol/daemon-session-info' +import { parseWslUncPath } from '../../../shared/wsl-paths' import { wslHookRelayStateKey } from './wsl-hook-relay-state-key' /** 'unverifiable' when any daemon generation couldn't answer: the relay then stays. */ diff --git a/src/main/agent-hooks/wsl-bridge-pty-presence.ts b/src/main/agent-hooks/wsl-relay/wsl-bridge-pty-presence.ts similarity index 100% rename from src/main/agent-hooks/wsl-bridge-pty-presence.ts rename to src/main/agent-hooks/wsl-relay/wsl-bridge-pty-presence.ts diff --git a/src/main/agent-hooks/wsl-guest-plugin-install.test.ts b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts similarity index 94% rename from src/main/agent-hooks/wsl-guest-plugin-install.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts index 3d6fdf68d1c..d3b3092339e 100644 --- a/src/main/agent-hooks/wsl-guest-plugin-install.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' function fakeMux( request: () => Promise, diff --git a/src/main/agent-hooks/wsl-guest-plugin-install.ts b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.ts similarity index 83% rename from src/main/agent-hooks/wsl-guest-plugin-install.ts rename to src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.ts index a9da7757ace..716c24f4303 100644 --- a/src/main/agent-hooks/wsl-guest-plugin-install.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-guest-plugin-install.ts @@ -1,9 +1,9 @@ -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { isRecord } from '../../shared/agent-status/child-work/agent-status-child-work-value-guards' -import { selectOpenCodePluginSources } from './opencode-plugin-settings' -import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' -import type { PluginSources } from '../../wsl-guest/plugin-overlay' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { isRecord } from '../../../shared/agent-status/child-work/agent-status-child-work-value-guards' +import { selectOpenCodePluginSources } from '../installation/opencode-plugin-settings' +import type { ManagedHookDetectionSettings } from '../installation/managed-hook-detection-commands' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' type GuestPluginInstallDeps = { pluginSources: () => PluginSources diff --git a/src/main/agent-hooks/wsl-hook-fs-adapter.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts similarity index 92% rename from src/main/agent-hooks/wsl-hook-fs-adapter.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts index 103c91aeb55..e5985e0fb65 100644 --- a/src/main/agent-hooks/wsl-hook-fs-adapter.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-fs-adapter.ts @@ -1,15 +1,15 @@ // Adapt the guest fs bridge to SFTP so WSL can reuse SSH hook installers over the existing relay. import type { SFTPWrapper } from 'ssh2' -import type { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import type { installRemoteManagedAgentHooks } from '../installation/remote-managed-hook-installers' import { buildManagedHookDetectionCommands, readManagedHookDetectionResult, type ManagedHookDetectionSettings -} from './managed-hook-detection-commands' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { WSL_HOOK_FS_METHODS, type WslFsResult } from '../../shared/wsl-hook-relay-contract' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' +} from '../installation/managed-hook-detection-commands' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { WSL_HOOK_FS_METHODS, type WslFsResult } from '../../../shared/wsl-hook-relay-contract' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' export async function installWslGuestHooks(options: { mux: SshChannelMultiplexer diff --git a/src/main/agent-hooks/wsl-hook-relay-deps.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts similarity index 82% rename from src/main/agent-hooks/wsl-hook-relay-deps.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts index 9a5f21fcce6..5c74107a65b 100644 --- a/src/main/agent-hooks/wsl-hook-relay-deps.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts @@ -1,42 +1,42 @@ -import { CLAUDE_AGENT_VIEW_MOD_SOURCE } from '../claude/agent-view/agent-view-mod-source' -import { bindRemoteClaudeInterruptReconciliation } from './ssh-agent-hook-interrupt-reconciliation' +import { CLAUDE_AGENT_VIEW_MOD_SOURCE } from '../../claude/agent-view/agent-view-mod-source' +import { bindRemoteClaudeInterruptReconciliation } from '../transport/ssh-agent-hook-interrupt-reconciliation' import { createHash } from 'node:crypto' import { readFileSync } from 'node:fs' -import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { AGENT_STATUS_LEGACY_UNADVERTISED_PEER_CAPABILITIES } from '../../shared/agent-status/transport/agent-status-legacy-adapter' -import { agentHookServer } from './server' +import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' +import { AGENT_STATUS_LEGACY_UNADVERTISED_PEER_CAPABILITIES } from '../../../shared/agent-status/transport/agent-status-legacy-adapter' +import { agentHookServer } from '../server/agent-hook-server' import { createLocalPtyInventoryReader, createWslBridgePaneRootReader -} from './local-tmux-managed-pty' -import { getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' -import { getLocalPtyProvider } from '../ipc/pty/provider/registry' -import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' -import { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' -import { getOpenCode2PluginSource, getOpenCodePluginSource } from '../opencode/hook-service' -import { getPiAgentStatusExtensionSource } from '../pi/agent-status-extension-source' -import { codexHookService } from '../codex/hooks/installation/hook-service' -import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import type { PluginSources } from '../../wsl-guest/plugin-overlay' +} from '../observations/local-tmux-managed-pty' +import { getPtyIdForPaneKey } from '../../ipc/pty/pane/key-state' +import { getLocalPtyProvider } from '../../ipc/pty/provider/registry' +import type { ManagedHookDetectionSettings } from '../installation/managed-hook-detection-commands' +import { installRemoteManagedAgentHooks } from '../installation/remote-managed-hook-installers' +import { getOpenCode2PluginSource, getOpenCodePluginSource } from '../../opencode/hook-service' +import { getPiAgentStatusExtensionSource } from '../../pi/agent-status-extension-source' +import { codexHookService } from '../../codex/hooks/installation/hook-service' +import type { AgentHookInstallStatus } from '../../../shared/agent-hook-listener/configuration/agent-hook-types' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' import { resolveWslHookRelayBundle, runWslInstallProcess, spawnWslRelayProcess } from './wsl-hook-relay-launch' import { waitForWslRelaySentinel } from './wsl-hook-relay-sentinel' -import { resolveWslDefaultDistro as resolveSharedWslDefaultDistro } from '../wsl/discovery/wsl-default-distro' +import { resolveWslDefaultDistro as resolveSharedWslDefaultDistro } from '../../wsl/discovery/wsl-default-distro' import { deferUntilWslDistroRunning, isWslDistroRunning -} from '../wsl/discovery/wsl-background-distro-gate' -import { isWslAgentHookRelayEnabled } from '../../shared/agent-hook-listener/transport/agent-hook-relay' +} from '../../wsl/discovery/wsl-background-distro-gate' +import { isWslAgentHookRelayEnabled } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { wslBridgePtyPresence, type WslBridgePtyPresence } from './wsl-bridge-pty-presence' import { readDaemonBridgeSessions, type DaemonBridgeSessionVerdict } from './wsl-bridge-daemon-sessions' -import { blockedWslDistroForExec } from '../wsl/discovery/wsl-background-exec-gate' +import { blockedWslDistroForExec } from '../../wsl/discovery/wsl-background-exec-gate' // Concurrent wsl.exe spawns can trigger transient E_UNEXPECTED failures. export const WSL_RELAY_TRANSIENT_RETRY_DELAY_MS = 2_000 diff --git a/src/main/agent-hooks/wsl-hook-relay-guest-install.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-guest-install.ts similarity index 92% rename from src/main/agent-hooks/wsl-hook-relay-guest-install.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-guest-install.ts index 8240e4b1876..90a0bd09df2 100644 --- a/src/main/agent-hooks/wsl-hook-relay-guest-install.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-guest-install.ts @@ -1,16 +1,16 @@ import { WSL_HOOK_FS_METHODS, wslHookRelayEndpointFilePath -} from '../../shared/wsl-hook-relay-contract' +} from '../../../shared/wsl-hook-relay-contract' import type { WslRelayDistroState } from './wsl-hook-relay-state' -import type { ManagedHookDetectionSettings } from './managed-hook-detection-commands' -import type { installRemoteManagedAgentHooks } from './remote-managed-hook-installers' +import type { ManagedHookDetectionSettings } from '../installation/managed-hook-detection-commands' +import type { installRemoteManagedAgentHooks } from '../installation/remote-managed-hook-installers' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' import { installWslGuestHooks } from './wsl-hook-fs-adapter' import { REINSTALL_MIN_INTERVAL_MS, type WslHookRelayManagerDeps } from './wsl-hook-relay-deps' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { openCodePluginSettingsKey } from './opencode-plugin-settings' -import type { PluginSources } from '../../wsl-guest/plugin-overlay' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { openCodePluginSettingsKey } from '../installation/opencode-plugin-settings' +import type { PluginSources } from '../../../wsl-guest/plugin-sources' type GuestInstallDeps = { installHooks: typeof installRemoteManagedAgentHooks diff --git a/src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.test.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-idle-stop.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.test.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-idle-stop.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-idle-stop.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-idle-stop.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-launch.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts similarity index 91% rename from src/main/agent-hooks/wsl-hook-relay-launch.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts index 93a65618f8f..47458275181 100644 --- a/src/main/agent-hooks/wsl-hook-relay-launch.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts @@ -2,21 +2,21 @@ import type { PipedChildProcess } from '@orca/process-host/process-spec' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { spawnProcess } from '@orca/process-host' -import { relayBundleCandidates } from '../wsl/execution/relay-bundle-paths' -import { withWslGuestLauncherRevision } from '../wsl/execution/wsl-guest-launcher-revision' -import { orcadPosixNodeRuntimeGlobs } from '../managed-server/install/orcad-node-runtime-globs' +import { relayBundleCandidates } from '../../wsl/execution/relay-bundle-paths' +import { withWslGuestLauncherRevision } from '../../wsl/execution/wsl-guest-launcher-revision' +import { orcadPosixNodeRuntimeGlobs } from '../../managed-server/install/orcad-node-runtime-globs' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' import { MAX_STARTUP_BUFFER_BYTES, type waitForWslRelaySentinel, type WslRelayStartupFailure } from './wsl-hook-relay-sentinel' -import { addOrcaWslInteropEnv } from '../pty/shell-startup/wsl-orca-env' -import { runWslProcess } from '../wsl/execution/wsl-runner' -import { resolveWslExecutablePath } from '../wsl/execution/wsl-executable-path' -import { buildWslExecArgs } from '../../shared/wsl-login-shell-command' -import { resolveWslInteropSpawnCwd } from '../wsl/execution/wsl-interop-spawn-directory' +import { addOrcaWslInteropEnv } from '../../pty/shell-startup/wsl-orca-env' +import { runWslProcess } from '../../wsl/execution/wsl-runner' +import { resolveWslExecutablePath } from '../../wsl/execution/wsl-executable-path' +import { buildWslExecArgs } from '../../../shared/wsl-login-shell-command' +import { resolveWslInteropSpawnCwd } from '../../wsl/execution/wsl-interop-spawn-directory' import { WSL_HOOK_RELAY_BUNDLE_NAME, WSL_HOOK_RELAY_DIR, @@ -25,7 +25,7 @@ import { WSL_HOOK_RELAY_STALE_EXIT_CODE, WSL_HOOK_RELAY_VERSION_ENV, WSL_HOOK_RELAY_VERSION_FILE -} from '../../shared/wsl-hook-relay-contract' +} from '../../../shared/wsl-hook-relay-contract' const INSTALL_TIMEOUT_MS = 30_000 diff --git a/src/main/agent-hooks/wsl-hook-relay-link.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts similarity index 88% rename from src/main/agent-hooks/wsl-hook-relay-link.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts index 2212d4e776f..a526b0f3c71 100644 --- a/src/main/agent-hooks/wsl-hook-relay-link.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-link.ts @@ -1,12 +1,12 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' import { AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_PANE_ROOT_METHOD -} from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { wslHookRelayConnectionId } from '../../shared/wsl-hook-relay-contract' -import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../shared/claude-agent-view' +} from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { wslHookRelayConnectionId } from '../../../shared/wsl-hook-relay-contract' +import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../../shared/claude-agent-view' import type { WslHookRelayManagerDeps } from './wsl-hook-relay-deps' export type WslRelayLinkOptions = { diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts similarity index 97% rename from src/main/agent-hooks/wsl-hook-relay-manager.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts index 1622fad6e1a..dcf4b5694d7 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.test.ts @@ -4,23 +4,23 @@ import { join } from 'node:path' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { RelayDispatcher } from '../../wsl-guest/dispatcher' -import { registerWslHookFsHandlers } from '../../wsl-guest/wsl-hook-fs-bridge' -import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' +import { RelayDispatcher } from '../../../wsl-guest/dispatcher' +import { registerWslHookFsHandlers } from '../../../wsl-guest/wsl-hook-fs-bridge' +import { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' import { createWslHookSftpAdapter, installWslGuestHooks } from './wsl-hook-fs-adapter' import { installRemoteManagedAgentHooks, REMOTE_MANAGED_HOOK_INSTALLER_AGENTS -} from './remote-managed-hook-installers' +} from '../installation/remote-managed-hook-installers' import { WslHookRelayManager } from './wsl-hook-relay-manager' -import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../shared/claude-agent-view' +import { CLAUDE_AGENT_VIEW_RELAY_METHOD } from '../../../shared/claude-agent-view' import { awaitExplicitAgentPluginGuestReadiness } from './wsl-agent-plugin-readiness' import { FAILURE_COOLDOWN_BASE_MS, type WslHookRelayManagerDeps } from './wsl-hook-relay-deps' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD -} from '../../shared/agent-hook-listener/transport/agent-hook-relay' +} from '../../../shared/agent-hook-listener/transport/agent-hook-relay' type GuestHarness = { transport: MultiplexerTransport diff --git a/src/main/agent-hooks/wsl-hook-relay-manager.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-manager.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts index 112baed1ec8..72e13043e44 100644 --- a/src/main/agent-hooks/wsl-hook-relay-manager.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-manager.ts @@ -17,14 +17,14 @@ import { import { wireWslRelayLink } from './wsl-hook-relay-link' import type { WslRelayRecovery } from './wsl-hook-relay-recovery' import { wslHookRelayStateKey } from './wsl-hook-relay-state-key' -import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' -import { AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { sanitizeWslHookInstanceKey } from '../../shared/wsl-hook-relay-contract' +import { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' +import { AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { sanitizeWslHookInstanceKey } from '../../../shared/wsl-hook-relay-contract' import { recordManagedWslCodexHome, wslRuntimeHomePathsEqual -} from '../codex/configuration/homes/managed-wsl-codex-home-registry' +} from '../../codex/configuration/homes/managed-wsl-codex-home-registry' import { createWslRelayRecoveryForManager, markWslRelayFailed, diff --git a/src/main/agent-hooks/wsl-hook-relay-reattach.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.test.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-reattach.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.test.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-reattach.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts similarity index 89% rename from src/main/agent-hooks/wsl-hook-relay-reattach.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts index af8e18cafce..f86d3d9e498 100644 --- a/src/main/agent-hooks/wsl-hook-relay-reattach.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-reattach.ts @@ -1,4 +1,4 @@ -import type { PtySpawnResult } from '../providers/pty-spawn-result' +import type { PtySpawnResult } from '../../providers/pty-spawn-result' import { wslHookRelayManager } from './wsl-hook-relay-manager' type ReattachResult = Pick diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-recovery.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts index 8480c84ce36..471dcbce2f8 100644 --- a/src/main/agent-hooks/wsl-hook-relay-recovery.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.test.ts @@ -1,4 +1,4 @@ -import type * as WslBackgroundDistroGate from '../wsl/discovery/wsl-background-distro-gate' +import type * as WslBackgroundDistroGate from '../../wsl/discovery/wsl-background-distro-gate' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { WslRelayRecovery, type WslRelayRecoveryState } from './wsl-hook-relay-recovery' @@ -7,7 +7,7 @@ import type { WslRelayRestartSetup } from './wsl-hook-relay-state' const { noteWslDistroMayHaveStoppedMock } = vi.hoisted(() => ({ noteWslDistroMayHaveStoppedMock: vi.fn() })) -vi.mock('../wsl/discovery/wsl-background-distro-gate', async (importOriginal) => ({ +vi.mock('../../wsl/discovery/wsl-background-distro-gate', async (importOriginal) => ({ ...(await importOriginal()), ...(await (() => ({ noteWslDistroMayHaveStopped: noteWslDistroMayHaveStoppedMock diff --git a/src/main/agent-hooks/wsl-hook-relay-recovery.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-recovery.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-recovery.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts similarity index 98% rename from src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts index ab57642fd8f..0940efda51d 100644 --- a/src/main/agent-hooks/wsl-hook-relay-sentinel.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.test.ts @@ -2,7 +2,7 @@ import { EventEmitter } from 'node:events' import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { afterEach, describe, expect, it, vi } from 'vitest' -import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/protocol/relay-handshake' +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../../ssh/protocol/relay-handshake' import { MAX_STARTUP_BUFFER_BYTES, waitForWslRelaySentinel, diff --git a/src/main/agent-hooks/wsl-hook-relay-sentinel.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts similarity index 96% rename from src/main/agent-hooks/wsl-hook-relay-sentinel.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts index f70b5725281..293e4583be8 100644 --- a/src/main/agent-hooks/wsl-hook-relay-sentinel.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-sentinel.ts @@ -1,7 +1,7 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' -import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../ssh/protocol/relay-handshake' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' +import { RELAY_SENTINEL, RELAY_SENTINEL_TIMEOUT_MS } from '../../ssh/protocol/relay-handshake' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' export const MAX_STARTUP_BUFFER_BYTES = 64 * 1024 diff --git a/src/main/agent-hooks/wsl-hook-relay-state-key.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-key.ts similarity index 100% rename from src/main/agent-hooks/wsl-hook-relay-state-key.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-key.ts diff --git a/src/main/agent-hooks/wsl-hook-relay-state-machine.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-machine.ts similarity index 95% rename from src/main/agent-hooks/wsl-hook-relay-state-machine.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-machine.ts index 069a73ca434..fd5d9f6ef54 100644 --- a/src/main/agent-hooks/wsl-hook-relay-state-machine.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state-machine.ts @@ -1,9 +1,9 @@ import { WslRelayRecovery } from './wsl-hook-relay-recovery' -import type { WslHookRelayManagerDeps } from './wsl-hook-relay-deps' + import type { WslRelayDistroState, WslRelayRestartSetup } from './wsl-hook-relay-state' import { wslHookRelayStateKey } from './wsl-hook-relay-state-key' -import { FAILURE_COOLDOWN_MAX_MS } from './wsl-hook-relay-deps' -import { noteWslDistroMayHaveStopped } from '../wsl/discovery/wsl-background-distro-gate' +import { type WslHookRelayManagerDeps, FAILURE_COOLDOWN_MAX_MS } from './wsl-hook-relay-deps' +import { noteWslDistroMayHaveStopped } from '../../wsl/discovery/wsl-background-distro-gate' type RelayFailureState = { distro: string diff --git a/src/main/agent-hooks/wsl-hook-relay-state.ts b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state.ts similarity index 93% rename from src/main/agent-hooks/wsl-hook-relay-state.ts rename to src/main/agent-hooks/wsl-relay/wsl-hook-relay-state.ts index 3fc4bbbe268..69c5b27bd1d 100644 --- a/src/main/agent-hooks/wsl-hook-relay-state.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-hook-relay-state.ts @@ -1,4 +1,4 @@ -import type { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' +import type { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' export type WslRelayDistroState = { distro: string diff --git a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts similarity index 94% rename from src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts index bf93187c45e..8266372ccbe 100644 --- a/src/main/agent-hooks/wsl-opencode-settings-lifetime.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings-lifetime.test.ts @@ -4,18 +4,18 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process' import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { RelayDispatcher } from '../../wsl-guest/dispatcher' -import { PluginOverlayManager } from '../../wsl-guest/plugin-overlay' -import { createInstallPluginsHandler } from '../../wsl-guest/wsl-install-plugins-handler' +import { RelayDispatcher } from '../../../wsl-guest/dispatcher' +import { PluginOverlayManager } from '../../../wsl-guest/plugin-overlay' +import { createInstallPluginsHandler } from '../../../wsl-guest/wsl-install-plugins-handler' import { WslHookRelayManager } from './wsl-hook-relay-manager' import { REINSTALL_MIN_INTERVAL_MS } from './wsl-hook-relay-deps' -import type { MultiplexerTransport } from '../ssh/protocol/ssh-multiplexer-transport-writer' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' +import type { MultiplexerTransport } from '../../ssh/protocol/ssh-multiplexer-transport-writer' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD -} from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { WSL_HOOK_FS_METHODS } from '../../shared/wsl-hook-relay-contract' +} from '../../../shared/agent-hook-listener/transport/agent-hook-relay' +import { WSL_HOOK_FS_METHODS } from '../../../shared/wsl-hook-relay-contract' function gate() { const reached = Promise.withResolvers() diff --git a/src/main/agent-hooks/wsl-opencode-settings.test.ts b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts similarity index 90% rename from src/main/agent-hooks/wsl-opencode-settings.test.ts rename to src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts index 227cd891012..889f1867534 100644 --- a/src/main/agent-hooks/wsl-opencode-settings.test.ts +++ b/src/main/agent-hooks/wsl-relay/wsl-opencode-settings.test.ts @@ -2,12 +2,12 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' -import { RelayDispatcher } from '../../wsl-guest/dispatcher' -import { PluginOverlayManager } from '../../wsl-guest/plugin-overlay' -import { createInstallPluginsHandler } from '../../wsl-guest/wsl-install-plugins-handler' -import { SshChannelMultiplexer } from '../ssh/protocol/ssh-channel-multiplexer' -import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../shared/agent-hook-listener/transport/agent-hook-relay' +import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' +import { RelayDispatcher } from '../../../wsl-guest/dispatcher' +import { PluginOverlayManager } from '../../../wsl-guest/plugin-overlay' +import { createInstallPluginsHandler } from '../../../wsl-guest/wsl-install-plugins-handler' +import { SshChannelMultiplexer } from '../../ssh/protocol/ssh-channel-multiplexer' +import { AGENT_HOOK_INSTALL_PLUGINS_METHOD } from '../../../shared/agent-hook-listener/transport/agent-hook-relay' import { requestGuestOpenCodeOverlayDir } from './wsl-guest-plugin-install' import { maybeRerunWslRelayGuestInstall, diff --git a/src/main/amp/hook-service.ts b/src/main/amp/hook-service.ts index bff09351ee8..7674aa7c126 100644 --- a/src/main/amp/hook-service.ts +++ b/src/main/amp/hook-service.ts @@ -7,7 +7,7 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/co import { readTextFileRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' import { AMP_PLUGIN_FILE, AMP_PLUGIN_MARKER, diff --git a/src/main/antigravity/hook-script.ts b/src/main/antigravity/hook-script.ts index a75bb4b317e..b3450f0e386 100644 --- a/src/main/antigravity/hook-script.ts +++ b/src/main/antigravity/hook-script.ts @@ -1,11 +1,11 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { buildHookProcessCapture } from '../agent-hooks/hook-process-capture' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { buildHookProcessCapture } from '../agent-hooks/installation/scripts/hook-process-capture' import { buildPosixHookPayloadCapture, POSIX_HOOK_JSON_STDIN, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { ANTIGRAVITY_PRE_TOOL_USE_DECISION } from './hook-events' export function getManagedScript( diff --git a/src/main/antigravity/hook-service.test.ts b/src/main/antigravity/hook-service.test.ts index 20ae7b9d529..09d2a620568 100644 --- a/src/main/antigravity/hook-service.test.ts +++ b/src/main/antigravity/hook-service.test.ts @@ -17,7 +17,7 @@ vi.mock('os', async () => { }) import { AntigravityHookService } from './hook-service' -import { createManagedCommandMatcher } from '../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' const ANTIGRAVITY_PRE_INVOCATION_COMMAND = process.platform === 'win32' ? 'antigravity-pre-invocation.cmd' : 'antigravity-hook.sh' diff --git a/src/main/antigravity/hook-service.ts b/src/main/antigravity/hook-service.ts index 9f18556a05e..c26bd687e34 100644 --- a/src/main/antigravity/hook-service.ts +++ b/src/main/antigravity/hook-service.ts @@ -5,33 +5,31 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - getSharedManagedScriptPath, - readHooksJson, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, - type HookDefinition -} from '../agent-hooks/installer-utils' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import { WINDOWS_ANTIGRAVITY_JSON_POST_SCRIPT } from './windows-hook-json-post' import { restoreManagedScript, refreshManagedScriptIfPresent, scriptStillExists -} from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { ANTIGRAVITY_EVENTS, ANTIGRAVITY_PRE_TOOL_USE_DECISION, type AntigravityEvent } from './hook-events' import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' -import { HOOK_PARENT_CAPTURE } from '../agent-hooks/hook-process-capture' +import { HOOK_PARENT_CAPTURE } from '../agent-hooks/installation/scripts/hook-process-capture' import { getManagedScript, getWindowsWrapperScript } from './hook-script' import { buildInstalledConfig, diff --git a/src/main/antigravity/hooks-json-bundle.ts b/src/main/antigravity/hooks-json-bundle.ts index 2a1f90a671a..ed81c036623 100644 --- a/src/main/antigravity/hooks-json-bundle.ts +++ b/src/main/antigravity/hooks-json-bundle.ts @@ -1,12 +1,14 @@ import { buildManagedCommandHook, - createManagedCommandMatcher, - hookDefinitionHasManagedCommand, MANAGED_HOOK_TIMEOUT_SECONDS, - removeManagedCommands, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + hookDefinitionHasManagedCommand, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' import { ANTIGRAVITY_EVENTS, ANTIGRAVITY_HOOK_BUNDLE_NAME, diff --git a/src/main/antigravity/posix-hook-invocation.test.ts b/src/main/antigravity/posix-hook-invocation.test.ts index 1b9b2472b7a..9f1ca040701 100644 --- a/src/main/antigravity/posix-hook-invocation.test.ts +++ b/src/main/antigravity/posix-hook-invocation.test.ts @@ -9,7 +9,7 @@ import { tokenizeCommandLine } from '../../shared/agent-status/process/agent-com import { spawnProcess } from '@orca/process-host' import { AntigravityHookService } from './hook-service' import { ANTIGRAVITY_PRE_TOOL_USE_DECISION } from './hook-events' -import { wrapPosixHookCommand } from '../agent-hooks/posix-hook-command' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' import { quotePosixShell } from '../../shared/shell/launch/shell-argument-quoting' import { readAgentProcess } from '../../shared/agent-status/process/agent-process-presence-probe' import { diff --git a/src/main/antigravity/windows-hook-json-post.ts b/src/main/antigravity/windows-hook-json-post.ts index 736ae3a4fd1..5732f1ff1fd 100644 --- a/src/main/antigravity/windows-hook-json-post.ts +++ b/src/main/antigravity/windows-hook-json-post.ts @@ -2,7 +2,7 @@ import { HOOK_REQUEST_MAX_BYTES } from '../../shared/agent-hook-listener/request import { POSIX_HOOK_JSON_STDIN_FIRST_BYTE_TIMEOUT_SECONDS, POSIX_HOOK_JSON_STDIN_IDLE_TIMEOUT_SECONDS -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' // curl reads payload@- before starting its timeout; agy can keep that pipe open. export const WINDOWS_ANTIGRAVITY_JSON_POST_SCRIPT = String.raw` diff --git a/src/main/claude/agent-view/agent-view-binding-plan.ts b/src/main/claude/agent-view/agent-view-binding-plan.ts index 8a34d0b7a0a..fc71b051c6d 100644 --- a/src/main/claude/agent-view/agent-view-binding-plan.ts +++ b/src/main/claude/agent-view/agent-view-binding-plan.ts @@ -1,5 +1,5 @@ -import type { HooksConfig } from '../../agent-hooks/installer-utils' -import { isPlainObject } from '../../agent-hooks/hooks-json-read' +import type { HooksConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' +import { isPlainObject } from '../../agent-hooks/installation/configuration/hooks-json-read' import { claudeAgentViewChord, serializeClaudeAgentViewBindings } from './agent-view-keybindings' import { CLAUDE_AGENT_VIEW_COMMAND, diff --git a/src/main/claude/agent-view/agent-view-config.ts b/src/main/claude/agent-view/agent-view-config.ts index 0845be6f5a4..e34d0f6140c 100644 --- a/src/main/claude/agent-view/agent-view-config.ts +++ b/src/main/claude/agent-view/agent-view-config.ts @@ -1,7 +1,7 @@ import { dirname, join } from 'node:path' import { readFile } from 'node:fs/promises' -import { parseHooksJsonText } from '../../agent-hooks/hooks-json-read' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' +import { parseHooksJsonText } from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' import { parseClaudeAgentViewBindings, serializeClaudeAgentViewBindings diff --git a/src/main/claude/agent-view/agent-view-install.ts b/src/main/claude/agent-view/agent-view-install.ts index 191a6855a18..29190bf2665 100644 --- a/src/main/claude/agent-view/agent-view-install.ts +++ b/src/main/claude/agent-view/agent-view-install.ts @@ -11,13 +11,14 @@ import { existsSync, rmSync } from 'node:fs' import { randomUUID } from 'node:crypto' import { readFile, rm } from 'node:fs/promises' import type { SFTPWrapper } from 'ssh2' -import { writeHooksJson, type HooksConfig } from '../../agent-hooks/installer-utils' +import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' +import type { HooksConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' import { readHooksJson, parseHooksJsonText, readHooksJsonWithRaw -} from '../../agent-hooks/hooks-json-read' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' +} from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' import { claudeAgentViewChord, parseClaudeAgentViewBindings, @@ -25,10 +26,10 @@ import { } from './agent-view-keybindings' import { readHooksJsonRemote, - readTextFileRemote, - writeHooksJsonRemote, - renamePlain -} from '../../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../../agent-hooks/installation/configuration/hooks-json-remote' +import { readTextFileRemote } from '../../agent-hooks/installation/remote/hook-text-files-remote' +import { renamePlain } from '../../agent-hooks/installation/remote/hook-sftp-operations' import { CLAUDE_AGENT_VIEW_PLUGIN } from '../../../shared/claude-agent-view' // Called only after the user opts in; a surviving marker remembers deletions and edited chords. diff --git a/src/main/claude/agent-view/agent-view-keybindings.ts b/src/main/claude/agent-view/agent-view-keybindings.ts index ef312e99687..198ccfb5fbc 100644 --- a/src/main/claude/agent-view/agent-view-keybindings.ts +++ b/src/main/claude/agent-view/agent-view-keybindings.ts @@ -1,6 +1,6 @@ import { applyEdits, modify, parse, type ParseError } from 'jsonc-parser' -import type { HooksConfig } from '../../agent-hooks/installer-utils' -import { isPlainObject } from '../../agent-hooks/hooks-json-read' +import type { HooksConfig } from '../../agent-hooks/installation/configuration/hook-config-schema' +import { isPlainObject } from '../../agent-hooks/installation/configuration/hooks-json-read' import { CLAUDE_AGENT_VIEW_COMMAND, CLAUDE_AGENT_VIEW_SHORTCUTS, diff --git a/src/main/claude/agent-view/agent-view-plugin.ts b/src/main/claude/agent-view/agent-view-plugin.ts index aa8bf84b186..23ab9ce7dae 100644 --- a/src/main/claude/agent-view/agent-view-plugin.ts +++ b/src/main/claude/agent-view/agent-view-plugin.ts @@ -1,7 +1,8 @@ import { join } from 'node:path' import { createHash } from 'node:crypto' -import { writeHooksJson, writeManagedScript } from '../../agent-hooks/installer-utils' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' +import { writeHooksJson } from '../../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../../agent-hooks/installation/scripts/managed-hook-script-write' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' import { CLAUDE_AGENT_VIEW_PLUGIN } from '../../../shared/claude-agent-view' import { CLAUDE_AGENT_VIEW_MOD_SOURCE } from './agent-view-mod-source' diff --git a/src/main/claude/claude-background-wake-retention.test.ts b/src/main/claude/claude-background-wake-retention.test.ts index 6fd4c15f9bf..1cb8b52af79 100644 --- a/src/main/claude/claude-background-wake-retention.test.ts +++ b/src/main/claude/claude-background-wake-retention.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { AgentJournalSubmission } from '../../shared/agent-session/journal/agent-session-journal-types' import { structuredRunningChildWork } from '../../shared/agent-status/child-work/agent-child-work-listing' -import type { AgentHookServer } from '../agent-hooks/server' +import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server' import type { StructuredAgentSessionJournalProjections } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-journal-projection' import { StructuredAgentSessionStatusFeed } from '../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' diff --git a/src/main/claude/claude-child-work-producer-harness.test-fixture.ts b/src/main/claude/claude-child-work-producer-harness.test-fixture.ts index 6ff7f13ae09..68009ae669c 100644 --- a/src/main/claude/claude-child-work-producer-harness.test-fixture.ts +++ b/src/main/claude/claude-child-work-producer-harness.test-fixture.ts @@ -8,7 +8,7 @@ import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child import type { AgentChildWorkReconcileOutcome } from '../../shared/agent-status/child-work/agent-status-child-work-evidence-admission' import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store' import { makeStructuredAgentStatusSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../agent-hooks/server' +import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink' import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture' import { ClaudeStructuredSessionAdapter } from './structured/claude-structured-session-adapter' diff --git a/src/main/claude/claude-hook-decision-script.ts b/src/main/claude/claude-hook-decision-script.ts index 458c37b9c26..22a13224148 100644 --- a/src/main/claude/claude-hook-decision-script.ts +++ b/src/main/claude/claude-hook-decision-script.ts @@ -1,4 +1,4 @@ -import { CLAUDE_PRE_TOOL_USE_DECISION } from '../agent-hooks/agent-tool-plugin-hooks' +import { CLAUDE_PRE_TOOL_USE_DECISION } from '../agent-hooks/tool-events/agent-tool-plugin-hooks' /** * Lets Claude Code's PreToolUse hook print Orca's answer (plugins' `agent.tool.before`) instead of diff --git a/src/main/claude/claude-hook-event-versions.test.ts b/src/main/claude/claude-hook-event-versions.test.ts index 3556395417a..40e414b5188 100644 --- a/src/main/claude/claude-hook-event-versions.test.ts +++ b/src/main/claude/claude-hook-event-versions.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { runProcess } from '@orca/process-host' -import { readManagedHookDetectionResult } from '../agent-hooks/managed-hook-detection-commands' +import { readManagedHookDetectionResult } from '../agent-hooks/installation/managed-hook-detection-commands' import { getClaudeManagedHookPlan } from './claude-managed-hook-events' vi.mock('@orca/process-host', () => ({ runProcess: vi.fn() })) diff --git a/src/main/claude/claude-managed-hook-events.ts b/src/main/claude/claude-managed-hook-events.ts index c219e38bf7c..9894f5b4227 100644 --- a/src/main/claude/claude-managed-hook-events.ts +++ b/src/main/claude/claude-managed-hook-events.ts @@ -1,4 +1,4 @@ -import type { HookDefinition } from '../agent-hooks/installer-utils' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' import { claudeKnowsHookEvent, claudeKnowsStatusLine, diff --git a/src/main/claude/claude-status-line-windows.test.ts b/src/main/claude/claude-status-line-windows.test.ts index ed162281f09..95fdf8313d1 100644 --- a/src/main/claude/claude-status-line-windows.test.ts +++ b/src/main/claude/claude-status-line-windows.test.ts @@ -19,7 +19,7 @@ vi.mock('os', async (importOriginal) => { return { ...actual, homedir: homedirMock.mockImplementation(actual.homedir) } }) -import { findGitBash } from '../agent-hooks/windows-git-bash-path.test-fixture' +import { findGitBash } from '../agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture' import { ClaudeHookService } from './hook-service' import { getManagedCommand } from './hook-settings' diff --git a/src/main/claude/claude-subagent-permission-request.test.ts b/src/main/claude/claude-subagent-permission-request.test.ts index d0d9ed4ee12..59dd7c9b91e 100644 --- a/src/main/claude/claude-subagent-permission-request.test.ts +++ b/src/main/claude/claude-subagent-permission-request.test.ts @@ -13,7 +13,7 @@ import type { } from '../../shared/agent-session/journal/agent-session-journal-types' import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence' import type { AgentStatusStructuredSessionSubject } from '../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../agent-hooks/server' +import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' import type { AgentSessionJournal } from '../native-chat/agent-session-journal/journal-store' import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import { StructuredAgentSessionCurrentWork } from '../native-chat/agent-session-wire/observations/structured-agent-session-current-work' diff --git a/src/main/claude/hook-script.ts b/src/main/claude/hook-script.ts index 5761f5a9bbe..a12c2812f2e 100644 --- a/src/main/claude/hook-script.ts +++ b/src/main/claude/hook-script.ts @@ -1,10 +1,10 @@ -import { buildHookProcessCapture } from '../agent-hooks/hook-process-capture' +import { buildHookProcessCapture } from '../agent-hooks/installation/scripts/hook-process-capture' import type { AgentHookSource } from '../../shared/agent-hook-listener/transport/agent-hook-relay' -import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installer-utils' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' import { buildPosixAgentHookPostCommand, buildPosixHookMetadataCacheLines -} from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-post-command' import { buildPosixScrubSafeEnvRestoreLines, buildWindowsScrubSafeEnvRestoreLines @@ -12,17 +12,17 @@ import { import { buildPosixCursorReplayGuardLines, buildWindowsCursorReplayGuardLines -} from '../agent-hooks/cursor-replay-guard' +} from '../agent-hooks/installation/scripts/cursor-replay-guard' import { buildPosixGrokReplayGuardLines, buildWindowsGrokReplayGuardLines -} from '../agent-hooks/grok-replay-guard' +} from '../agent-hooks/installation/scripts/grok-replay-guard' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines, POSIX_HOOK_STDIN_EXEC -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { buildPosixClaudeDecisionModeLines, buildPosixClaudeDecisionPreludeLines, @@ -31,7 +31,7 @@ import { import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../agent-hooks/claude-background-job-guard' +} from '../agent-hooks/installation/scripts/claude-background-job-guard' export function getManagedScript( target: 'local' | 'posix' = 'local', diff --git a/src/main/claude/hook-service.test.ts b/src/main/claude/hook-service.test.ts index 0917a1e5548..f0f71b33051 100644 --- a/src/main/claude/hook-service.test.ts +++ b/src/main/claude/hook-service.test.ts @@ -17,7 +17,8 @@ vi.mock('../pty/shell-startup/git-bash', async (importOriginal) => ({ })) import type { SFTPWrapper } from 'ssh2' -import { createManagedCommandMatcher, WINDOWS_CMD_SAFE_PATH } from '../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { WINDOWS_CMD_SAFE_PATH } from '../agent-hooks/installation/commands/windows-hook-command' import { ClaudeHookService } from './hook-service' import { CLAUDE_EVENTS } from './claude-managed-hook-events' import { getWindowsManagedLifecycleHook, OPENCLAUDE_HOOK_SETTINGS } from './hook-settings' diff --git a/src/main/claude/hook-service.ts b/src/main/claude/hook-service.ts index f105a43645c..87ea9b9191a 100644 --- a/src/main/claude/hook-service.ts +++ b/src/main/claude/hook-service.ts @@ -10,18 +10,16 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildManagedCommandHook, - readHooksJson, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' +import { buildManagedCommandHook } from '../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { getManagedScript } from './hook-script' import { removeClaudeAgentViewRemote, diff --git a/src/main/claude/hook-settings.ts b/src/main/claude/hook-settings.ts index edfc429d4b8..acd9a23acaa 100644 --- a/src/main/claude/hook-settings.ts +++ b/src/main/claude/hook-settings.ts @@ -2,24 +2,26 @@ import { homedir } from 'node:os' import { basename, extname, join, win32 } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - isPlainObject, - isSafeUnicodeWindowsBatchHookPath, MANAGED_HOOK_TIMEOUT_SECONDS, - removeManagedCommands, - withPreviousManagedAsync, - wrapWindowsPowerShellEncodedCommand, type HookCommandConfig, type HooksConfig -} from '../agent-hooks/installer-utils' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands, + withPreviousManagedAsync +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { isSafeUnicodeWindowsBatchHookPath } from '../agent-hooks/installation/commands/windows-hook-command' +import { wrapWindowsPowerShellEncodedCommand } from '../agent-hooks/installation/commands/windows-powershell-hook-launcher' import { quotePowerShellLiteral } from '../../shared/powershell-native-argument' -import { getWindowsNativeHookAgent } from '../agent-hooks/windows-native-hook-executable' +import { getWindowsNativeHookAgent } from '../agent-hooks/installation/commands/windows-native-hook-executable' import { wrapRuntimeHomeHookCommand, wrapRuntimeHomePosixHookCommand -} from '../agent-hooks/runtime-home-hook-command' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/commands/runtime-home-hook-command' +import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import type { ClaudeManagedHookPlan } from './claude-managed-hook-events' export type ClaudeCompatibleHookSettings = { diff --git a/src/main/claude/statusline-install.ts b/src/main/claude/statusline-install.ts index bb4f6ed1b06..30d793113f2 100644 --- a/src/main/claude/statusline-install.ts +++ b/src/main/claude/statusline-install.ts @@ -1,5 +1,6 @@ import { existsSync, rmSync, writeFileSync } from 'node:fs' -import { writeManagedScript, type HooksConfig } from '../agent-hooks/installer-utils' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' import { getManagedStatusLineCommand, getManagedStatusLineScript } from './statusline-script' import { applyManagedStatusLine, diff --git a/src/main/claude/statusline-script.ts b/src/main/claude/statusline-script.ts index 0d392c5e47a..0d11d0e4344 100644 --- a/src/main/claude/statusline-script.ts +++ b/src/main/claude/statusline-script.ts @@ -1,14 +1,14 @@ import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../agent-hooks/claude-background-job-guard' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { WINDOWS_HOOK_STDIN_READER } from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/claude-background-job-guard' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { WINDOWS_HOOK_STDIN_READER } from '../agent-hooks/installation/scripts/hook-stdin-contract' import { CLAUDE_STATUSLINE_MIN_POST_INTERVAL_SECONDS, CLAUDE_STATUSLINE_PATHNAME } from '../../shared/claude-statusline-rate-limits' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import { getManagedCommand } from './hook-settings' const STATUSLINE_CLEANUP_LABEL = 'orca_statusline_cleanup' diff --git a/src/main/claude/theme-sync/claude-code-theme-ownership.ts b/src/main/claude/theme-sync/claude-code-theme-ownership.ts index c3c241a29fb..7c173455db6 100644 --- a/src/main/claude/theme-sync/claude-code-theme-ownership.ts +++ b/src/main/claude/theme-sync/claude-code-theme-ownership.ts @@ -2,9 +2,12 @@ import { readFile } from 'node:fs/promises' import { homedir } from 'node:os' import { join } from 'node:path' import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' -import { isPlainObject, parseHooksJsonText } from '../../agent-hooks/hooks-json-read' -import { writeHooksJsonAsync } from '../../agent-hooks/hooks-json-write-async' -import { withManagedHookInstallLock } from '../../agent-hooks/managed-hook-install-lock' +import { + isPlainObject, + parseHooksJsonText +} from '../../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJsonAsync } from '../../agent-hooks/installation/configuration/hooks-json-write-async' +import { withManagedHookInstallLock } from '../../agent-hooks/installation/locking/managed-hook-install-lock' /** What Orca replaced in one config dir's settings.json, so turning the sync off can put it back. */ export type ClaudeThemeOwnership = { 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 7b4233a2d8f..4bd63ebf552 100644 --- a/src/main/claude/theme-sync/claude-code-theme-sync.ts +++ b/src/main/claude/theme-sync/claude-code-theme-sync.ts @@ -2,8 +2,8 @@ import { randomUUID } from 'node:crypto' import { mkdir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import { isDefinitiveAbsence } from '../../../shared/definitive-filesystem-absence' -import { readHooksJson } from '../../agent-hooks/hooks-json-read' -import { writeHooksJson } from '../../agent-hooks/installer-utils' +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 { diff --git a/src/main/claude/windows-hook-files.test.ts b/src/main/claude/windows-hook-files.test.ts index c2a6f5aa7f2..2a79cdb3fcf 100644 --- a/src/main/claude/windows-hook-files.test.ts +++ b/src/main/claude/windows-hook-files.test.ts @@ -3,8 +3,9 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import type * as osModule from 'node:os' import { join } from 'node:path' -import * as refresh from '../agent-hooks/managed-hook-script-refresh' -import { readHooksJson, writeHooksJson } from '../agent-hooks/installer-utils' +import * as refresh from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' import { ClaudeHookService } from './hook-service' import { getWindowsManagedLifecycleHook } from './hook-settings' import { getWindowsClaudeHookEntry, getWindowsClaudeHookPayloadPath } from './windows-hook-files' diff --git a/src/main/claude/windows-hook-files.ts b/src/main/claude/windows-hook-files.ts index 64291fb2f14..7b7c9620cf2 100644 --- a/src/main/claude/windows-hook-files.ts +++ b/src/main/claude/windows-hook-files.ts @@ -2,22 +2,22 @@ import { existsSync, readFileSync, rmSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { dirname, join } from 'node:path' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { writeManagedScript } from '../agent-hooks/installer-utils' -import { getLockedExecutableAsidePath } from '../agent-hooks/locked-executable-rename' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { getLockedExecutableAsidePath } from '../agent-hooks/installation/scripts/locked-executable-rename' import { refreshManagedScriptIfPresent, restoreManagedScript, scriptStillExists -} from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { buildWindowsHookEnvironmentGuardLines, WINDOWS_HOOK_STDIN_DRAIN_COMMAND -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { resolveBundledWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_EXECUTABLE_NAME -} from '../agent-hooks/windows-native-hook-executable' -import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD } from '../agent-hooks/claude-background-job-guard' +} from '../agent-hooks/installation/commands/windows-native-hook-executable' +import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD } from '../agent-hooks/installation/scripts/claude-background-job-guard' const PAYLOAD_FILE_NAME = 'claude-hook-impl.cmd' diff --git a/src/main/claude/windows-native-hook-registration.test.ts b/src/main/claude/windows-native-hook-registration.test.ts index 05cccc35a89..c62b41fcc4a 100644 --- a/src/main/claude/windows-native-hook-registration.test.ts +++ b/src/main/claude/windows-native-hook-registration.test.ts @@ -6,7 +6,7 @@ import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { removeTreeSync } from '../../shared/windows-transient-lock-removal' -import type * as NativeHookExecutableModule from '../agent-hooks/windows-native-hook-executable' +import type * as NativeHookExecutableModule from '../agent-hooks/installation/commands/windows-native-hook-executable' vi.mock('electron', () => ({ app: { getPath: () => '/tmp/userData' } })) @@ -14,21 +14,26 @@ const { bundledHook } = vi.hoisted(() => { const bundledHook: { path: string | null } = { path: null } return { bundledHook } }) -vi.mock('../agent-hooks/windows-native-hook-executable', async (importOriginal) => ({ - ...(await importOriginal()), - resolveBundledWindowsNativeHookExecutable: () => bundledHook.path -})) +vi.mock( + '../agent-hooks/installation/commands/windows-native-hook-executable', + async (importOriginal) => ({ + ...(await importOriginal()), + resolveBundledWindowsNativeHookExecutable: () => bundledHook.path + }) +) import { createManagedCommandMatcher, - removeManagedCommands, - type HookCommandConfig, - type HookDefinition -} from '../agent-hooks/installer-utils' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import type { + HookCommandConfig, + HookDefinition +} from '../agent-hooks/installation/configuration/hook-config-schema' import { buildWindowsNativeHookExecutable, WINDOWS_NATIVE_HOOK_BUILD_TIMEOUT_MS -} from '../agent-hooks/windows-native-hook-exe.test-fixture' +} from '../agent-hooks/installation/commands/testing/windows-native-hook-exe.test-fixture' import { ClaudeHookService } from './hook-service' const CURRENT_CLAUDE = { claudeVersion: '2.1.261 (Claude Code)' } diff --git a/src/main/cli/appimage-generation-lease.ts b/src/main/cli/appimage-generation-lease.ts index fc705102c06..4918e1be8cd 100644 --- a/src/main/cli/appimage-generation-lease.ts +++ b/src/main/cli/appimage-generation-lease.ts @@ -4,7 +4,10 @@ import { readFileSync, unlinkSync } from 'node:fs' import { lstat, mkdir, readdir, readFile, rename, unlink, writeFile } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' import type { ProcessLivenessVerdict } from '../daemon/endpoint/identity/daemon-incarnation-evidence-types' -import { parseLinuxStartTicks, readBootIdentity } from '../agent-hooks/managed-hook-owner-identity' +import { + parseLinuxStartTicks, + readBootIdentity +} from '../agent-hooks/installation/locking/managed-hook-owner-identity' import { resolveAppImageGenerationOfExecutable, type AppImageGenerationLocation diff --git a/src/main/codex-accounts/service-hook-trust-test-fixtures.ts b/src/main/codex-accounts/service-hook-trust-test-fixtures.ts index 63eeeea6137..76ca11f09a8 100644 --- a/src/main/codex-accounts/service-hook-trust-test-fixtures.ts +++ b/src/main/codex-accounts/service-hook-trust-test-fixtures.ts @@ -8,7 +8,8 @@ export type CanonicalHookTrustFixture = { } export async function createCanonicalHookTrustFixture(): Promise { - const { MANAGED_HOOK_TIMEOUT_SECONDS } = await import('../agent-hooks/installer-utils') + const { MANAGED_HOOK_TIMEOUT_SECONDS } = + await import('../agent-hooks/installation/configuration/hook-config-schema') const [, { getCodexManagedHookInstallMaterial }] = await Promise.all([ import('../codex/hooks/installation/hook-service'), import('../codex/hooks/definitions/codex-hook-definition') diff --git a/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts b/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts index 63fc919ba0b..045623c71d9 100644 --- a/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts +++ b/src/main/codex/configuration/homes/sta-4823-shared-state-survives-a-failed-read.test.ts @@ -113,7 +113,7 @@ const { upsertHookTrustEntries, upsertProjectTrustLevel } = await import('../../trust/toml/config-toml-trust') const { writeCodexTrustGrantLedgerHome, getCodexTrustGrantLedgerPath } = await import('../../trust/grants/codex-trust-grant-ledger') -await import('../../../agent-hooks/hooks-json-read') +await import('../../../agent-hooks/installation/configuration/hooks-json-read') const { MAX_AGENT_STATE_FILE_BYTES } = await import('../agent-state-file-reader') const { observeCodexSettingsBaseline } = await import('../settings/config-settings-baseline') const { snapshotCodexRuntimeSettingsBaseline } = diff --git a/src/main/codex/history/index/codex-state-db-backfill-recovery.ts b/src/main/codex/history/index/codex-state-db-backfill-recovery.ts index ecc491e75a2..6f8dd5a232f 100644 --- a/src/main/codex/history/index/codex-state-db-backfill-recovery.ts +++ b/src/main/codex/history/index/codex-state-db-backfill-recovery.ts @@ -3,8 +3,8 @@ import { join } from 'node:path' import { setTimeout as delay } from 'node:timers/promises' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { parseWslUncPath } from '../../../../shared/wsl-paths' -import { withManagedHookInstallLock } from '../../../agent-hooks/managed-hook-install-lock' -import { readManagedHookHostIdentity } from '../../../agent-hooks/managed-hook-owner-identity' +import { withManagedHookInstallLock } from '../../../agent-hooks/installation/locking/managed-hook-install-lock' +import { readManagedHookHostIdentity } from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' import { resolveCodexCommand } from '../../../codex-cli/command' import type { ChildProcessHandle } from '@orca/process-host/process-spec' import { diff --git a/src/main/codex/hooks/definitions/codex-hook-definition.ts b/src/main/codex/hooks/definitions/codex-hook-definition.ts index 52055bbebe5..f59c2790cf1 100644 --- a/src/main/codex/hooks/definitions/codex-hook-definition.ts +++ b/src/main/codex/hooks/definitions/codex-hook-definition.ts @@ -2,13 +2,13 @@ import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument- import { join } from 'node:path' import { buildManagedCommandHook, - getSharedManagedScriptPath, MANAGED_HOOK_TIMEOUT_SECONDS, - writeHooksJson, type HookCommandConfig, type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/hook-stdin-contract' +} from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { getSharedManagedScriptPath } from '../../../agent-hooks/installation/scripts/managed-hook-script-path' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/installation/scripts/hook-stdin-contract' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath diff --git a/src/main/codex/hooks/definitions/codex-hook-identity.ts b/src/main/codex/hooks/definitions/codex-hook-identity.ts index e3c3050fe18..89e3e5a7a90 100644 --- a/src/main/codex/hooks/definitions/codex-hook-identity.ts +++ b/src/main/codex/hooks/definitions/codex-hook-identity.ts @@ -1,4 +1,7 @@ -import type { HookCommandConfig, HookDefinition } from '../../../agent-hooks/installer-utils' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import type { CodexEventLabel, CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { normalizeCodexHookTimeoutSec } from '../../trust/identity/codex-trust-identity' diff --git a/src/main/codex/hooks/definitions/codex-hook-script.ts b/src/main/codex/hooks/definitions/codex-hook-script.ts index 67db071b491..0ef1d101c4b 100644 --- a/src/main/codex/hooks/definitions/codex-hook-script.ts +++ b/src/main/codex/hooks/definitions/codex-hook-script.ts @@ -1,14 +1,14 @@ import { WINDOWS_CLAUDE_BACKGROUND_JOB_GUARD, buildPosixClaudeBackgroundJobGuardLines -} from '../../../agent-hooks/claude-background-job-guard' -import { buildPosixAgentHookPostCommand } from '../../../agent-hooks/hook-post-command' +} from '../../../agent-hooks/installation/scripts/claude-background-job-guard' +import { buildPosixAgentHookPostCommand } from '../../../agent-hooks/installation/scripts/hook-post-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../../../agent-hooks/hook-stdin-contract' -import { buildWindowsAgentHookCurlPostCommand } from '../../../agent-hooks/installer-utils' +} from '../../../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildWindowsAgentHookCurlPostCommand } from '../../../agent-hooks/installation/commands/windows-agent-hook-post-command' export function getManagedScript(target: 'local' | 'posix' = 'local'): string { if (target === 'local' && process.platform === 'win32') { diff --git a/src/main/codex/hooks/installation/codex-hook-local-install.ts b/src/main/codex/hooks/installation/codex-hook-local-install.ts index 12ee59f8246..3f95b4ff1ea 100644 --- a/src/main/codex/hooks/installation/codex-hook-local-install.ts +++ b/src/main/codex/hooks/installation/codex-hook-local-install.ts @@ -2,11 +2,11 @@ import { mkdirSync } from 'node:fs' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - writeManagedScript, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { syncSystemConfigIntoManagedCodexHome } from '../../configuration/settings/codex-config-mirror' import { upsertHookTrustEntries, type CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { getExplicitHomeCodexHookSourcePath as getCodexExplicitHomeHookSourcePath } from '../../trust/identity/codex-trust-identity' diff --git a/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts b/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts index 344e99597c6..251bdca2462 100644 --- a/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts +++ b/src/main/codex/hooks/installation/codex-hook-local-maintenance.ts @@ -3,8 +3,8 @@ import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-liste import { createManagedCommandMatcher, removeManagedCommands -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { syncSystemConfigIntoManagedCodexHome } from '../../configuration/settings/codex-config-mirror' import { upsertHookTrustEntries } from '../../trust/toml/config-toml-trust' import { diff --git a/src/main/codex/hooks/installation/codex-hook-remote-install.ts b/src/main/codex/hooks/installation/codex-hook-remote-install.ts index 68b2ebf5153..c726d8ac979 100644 --- a/src/main/codex/hooks/installation/codex-hook-remote-install.ts +++ b/src/main/codex/hooks/installation/codex-hook-remote-install.ts @@ -2,17 +2,19 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import { readHooksJsonRemote, + writeHooksJsonRemote +} from '../../../agent-hooks/installation/configuration/hooks-json-remote' +import { readTextFileRemote, - writeHooksJsonRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../../../agent-hooks/installer-utils-remote' +} from '../../../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../../../agent-hooks/installation/scripts/managed-script-write-remote' import { assertLoadableHookTrustConfig, type CodexTrustEntry diff --git a/src/main/codex/hooks/installation/codex-hook-service-implementation.ts b/src/main/codex/hooks/installation/codex-hook-service-implementation.ts index 184572b6ad5..d5dd7450e25 100644 --- a/src/main/codex/hooks/installation/codex-hook-service-implementation.ts +++ b/src/main/codex/hooks/installation/codex-hook-service-implementation.ts @@ -3,8 +3,8 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { normalizeRuntimePathForComparison } from '../../../../shared/cross-platform-path' import { dedupeInFlightRun } from '../../../runtime/concurrency/in-flight-run-dedupe' -import { refreshManagedScriptIfPresent } from '../../../agent-hooks/managed-hook-script-refresh' -import { writeManagedScript } from '../../../agent-hooks/installer-utils' +import { refreshManagedScriptIfPresent } from '../../../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' import { getOrcaManagedCodexHomePath } from '../../configuration/homes/codex-home-paths' import { getManagedScriptPath } from '../definitions/codex-hook-definition' import { buildCodexHookCommand as getManagedCommand } from '../definitions/codex-hook-command-form' diff --git a/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts b/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts index 191f6eec09f..d4d224e3ba2 100644 --- a/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts +++ b/src/main/codex/hooks/installation/codex-hook-wsl-runtime.ts @@ -2,11 +2,11 @@ import { win32 as pathWin32 } from 'node:path' import type { AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - writeManagedScript, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { upsertHookTrustEntries, type CodexTrustEntry } from '../../trust/toml/config-toml-trust' import '../../trust/identity/codex-trust-identity' import { @@ -17,8 +17,11 @@ import { writeCodexHooksJson } from '../definitions/codex-hook-definition' import { grantManagedCodexHookTrust } from '../../trust/grants/codex-hook-trust-grant' -import type { CodexManagedTrustGrantPlan } from '../../trust/grants/codex-managed-trust-grant-plan' -import { removeSelfComputedTrustBeforeGrant } from '../../trust/grants/codex-managed-trust-grant-plan' + +import { + type CodexManagedTrustGrantPlan, + removeSelfComputedTrustBeforeGrant +} from '../../trust/grants/codex-managed-trust-grant-plan' import { getManagedScript } from '../definitions/codex-hook-script' import { removeStaleWslRuntimeManagedHookTrustEntries, diff --git a/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts b/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts index e2980e1d5ba..ae8bbc6942c 100644 --- a/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts +++ b/src/main/codex/hooks/installation/hook-service-legacy-cleanup.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it, vi } from 'vitest' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import type * as Os from 'node:os' import { join } from 'node:path' -import '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import '../../trust/toml/config-toml-trust' import { upsertHookTrustContent as upsertHookTrustEntriesInContent } from '../../trust/toml/config-toml-hook-trust-edit' import { setupCodexHookHomes } from './hook-service-test-harness' diff --git a/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts b/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts index 54e32c9ae62..165e88a18eb 100644 --- a/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts +++ b/src/main/codex/hooks/installation/hook-service-managed-codex-hashes.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import type * as Os from 'node:os' import { join } from 'node:path' import { parse as parseToml } from 'smol-toml' -import type * as InstallerUtils from '../../../agent-hooks/installer-utils' +import type * as HooksJsonWrite from '../../../agent-hooks/installation/configuration/hooks-json-write' import type * as TrustDerivation from '../../trust/hooks/codex-hook-trust-derivation' import { setupCodexHookHomes } from './hook-service-test-harness' @@ -30,16 +30,19 @@ vi.mock('../../trust/hooks/codex-hook-trust-derivation', async (importOriginal) ...(await importOriginal()), ...codex })) -vi.mock('../../../agent-hooks/installer-utils', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeHooksJson: (...args: Parameters) => { - hooks.beforeHooksJsonWrite?.() - return actual.writeHooksJson(...args) +vi.mock( + '../../../agent-hooks/installation/configuration/hooks-json-write', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeHooksJson: (...args: Parameters) => { + hooks.beforeHooksJsonWrite?.() + return actual.writeHooksJson(...args) + } } } -}) +) import './hook-service' import { CodexHookService } from './codex-hook-service-implementation' diff --git a/src/main/codex/hooks/installation/hook-service-test-harness.ts b/src/main/codex/hooks/installation/hook-service-test-harness.ts index 496cf8ec739..ee984f10fe7 100644 --- a/src/main/codex/hooks/installation/hook-service-test-harness.ts +++ b/src/main/codex/hooks/installation/hook-service-test-harness.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, vi, type Mock } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { createManagedCommandMatcher } from '../../../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' import '../../trust/toml/config-toml-trust' import { getExplicitHomeCodexHookSourcePath as getCodexExplicitHomeHookSourcePath, diff --git a/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts b/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts index 09ef1380984..476fbbefabe 100644 --- a/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts +++ b/src/main/codex/hooks/installation/hook-service-wsl-runtime.test.ts @@ -4,8 +4,8 @@ import { spawnSync } from 'node:child_process' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../../../agent-hooks/installer-utils' -import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/hook-stdin-contract' +import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { POSIX_HOOK_STDIN_DRAIN_COMMAND } from '../../../agent-hooks/installation/scripts/hook-stdin-contract' import { readHookTrustEntries, type CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { computeCodexTrustKey as computeTrustKey, diff --git a/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts b/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts index 4429a772652..cc8b82168b3 100644 --- a/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-account-home-hook.test.ts @@ -12,7 +12,7 @@ import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' import type * as HashLookup from '../../trust/hooks/codex-hook-hash-lookup' -import type { HookDefinition } from '../../../agent-hooks/installer-utils' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' const mocks = vi.hoisted(() => { const hashes: Record = {} diff --git a/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts b/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts index fc83fcf865b..6443640bd10 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts @@ -2,12 +2,12 @@ import { existsSync, readFileSync, unlinkSync } from 'node:fs' import { join } from 'node:path' import { hookDefinitionHasManagedCommand, - removeManagedCommands, - writeHooksJson -} from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' -import { findManagedTomlBlocks } from '../../../agent-hooks/managed-toml-ownership' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' +import { findManagedTomlBlocks } from '../../../agent-hooks/installation/configuration/managed-toml-ownership' import type { CodexTrustEntry } from '../../trust/toml/config-toml-trust' import { writeTomlConfigAtomically as writeConfigAtomically } from '../../configuration/toml/config-toml-atomic-write' import { diff --git a/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts b/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts index 0c497633f92..4b1f1ae6cff 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-reconcile.test.ts @@ -13,8 +13,8 @@ import { import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' -import '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import type * as CodexCommand from '../../../codex-cli/command' import type * as TrustDerivation from '../../trust/hooks/codex-hook-trust-derivation' import type * as RealHomeInstall from './codex-real-home-hook-install' diff --git a/src/main/codex/hooks/reconciliation/codex-hook-status.ts b/src/main/codex/hooks/reconciliation/codex-hook-status.ts index f1664f3e121..06eeca77cad 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-status.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-status.ts @@ -3,8 +3,8 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../../../shared/agent-hook-listener/configuration/agent-hook-types' -import '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' + +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { assertLoadableHookTrustConfig, isCodexConfigTomlRefusedError, diff --git a/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts b/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts index 6ad455a589c..711eee6b1cf 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-sweep-per-agent-opt-out.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it, vi } from 'vitest' import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import type * as Os from 'node:os' import { join } from 'node:path' -import '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' + +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' import { setupCodexHookHomes } from '../installation/hook-service-test-harness' const { getPathMock, homedirMock } = vi.hoisted(() => ({ diff --git a/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts b/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts index 353dcf39a4c..96cfaed3939 100644 --- a/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-hook-toggle-off-wins.test.ts @@ -39,7 +39,7 @@ vi.mock('../../trust/hooks/codex-hook-trust-derivation', async (importOriginal) import { MANAGED_AGENT_HOOK_INSTALLERS, MANAGED_AGENT_HOOK_REMOVERS -} from '../../../agent-hooks/managed-agent-hook-registry' +} from '../../../agent-hooks/installation/managed-agent-hook-registry' import { _internals, startCodexHooks } from './codex-hook-reconcile' import { _internals as lookupInternals } from '../../trust/hooks/codex-hook-hash-lookup' import { diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts index 88c0ee5fc2b..bb17c069df0 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entries.test.ts @@ -16,10 +16,10 @@ import type * as NodeOs from 'node:os' import { tmpdir } from 'node:os' import { join } from 'node:path' import { isDeepStrictEqual } from 'node:util' -import type * as InstallerUtils from '../../../agent-hooks/installer-utils' +import type * as HooksJsonWrite from '../../../agent-hooks/installation/configuration/hooks-json-write' import type * as RealHomeHooksJson from './codex-real-home-hooks-json' -import type { HookDefinition } from '../../../agent-hooks/installer-utils' -import { wrapPosixHookCommand } from '../../../agent-hooks/posix-hook-command' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { wrapPosixHookCommand } from '../../../agent-hooks/installation/commands/posix-hook-command' const mocks = vi.hoisted(() => { const state: { beforeHooksJsonGuard: (() => void) | null; hooksJsonWrites: number } = { @@ -33,16 +33,19 @@ vi.mock('node:os', async () => ({ ...(await vi.importActual('node:os')), homedir: mocks.homedir })) -vi.mock('../../../agent-hooks/installer-utils', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - writeHooksJson: (...args: Parameters) => { - mocks.hooksJsonWrites += 1 - return actual.writeHooksJson(...args) +vi.mock( + '../../../agent-hooks/installation/configuration/hooks-json-write', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeHooksJson: (...args: Parameters) => { + mocks.hooksJsonWrites += 1 + return actual.writeHooksJson(...args) + } } } -}) +) vi.mock('./codex-real-home-hooks-json', async (importOriginal) => { const actual = await importOriginal() diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts index 8f6eef97edd..f8ad4cb850b 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-entry-plan.ts @@ -1,8 +1,8 @@ -import { - removeManagedCommands, - type HookCommandConfig, - type HookDefinition -} from '../../../agent-hooks/installer-utils' +import { removeManagedCommands } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { buildCodexManagedHook, CODEX_EVENT_LABEL, diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts index 92938886c0a..503aa57799b 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-install.ts @@ -1,11 +1,9 @@ -import { - createManagedCommandMatcher, - type HookDefinition, - writeHooksJson, - writeManagedScript -} from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' +import { createManagedCommandMatcher } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../../../agent-hooks/installation/scripts/managed-hook-script-write' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' import { assertHooksJsonGeneration, backupRealHomeHooksJsonOnce, diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts index 35b255287c7..9f8900b1f31 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hook-sweep.ts @@ -1,11 +1,11 @@ import { createManagedCommandMatcher, - removeManagedCommands, - writeHooksJson, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' + removeManagedCommands +} from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-write' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' import { assertHooksJsonGeneration } from './codex-real-home-hooks-json' import { getCodexManagedScriptFileName } from '../definitions/codex-hook-identity' import { diff --git a/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts b/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts index 124c95c41c4..5f6055509cb 100644 --- a/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts +++ b/src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts @@ -1,9 +1,12 @@ import { existsSync, mkdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { writeFileAtomically } from '../../../codex-accounts/fs-utils' -import type { HooksConfig } from '../../../agent-hooks/installer-utils' -import { resolveHooksJsonWritePath } from '../../../agent-hooks/hook-config-write-path' -import { isPlainObject, readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' +import type { HooksConfig } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { resolveHooksJsonWritePath } from '../../../agent-hooks/installation/configuration/hook-config-write-path' +import { + isPlainObject, + readHooksJsonWithRaw +} from '../../../agent-hooks/installation/configuration/hooks-json-read' import { getSystemCodexHomePath } from '../../configuration/homes/codex-home-paths' import '../../trust/toml/config-toml-trust' import { diff --git a/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts b/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts index c9faebb0f30..b11e147f7dc 100644 --- a/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts +++ b/src/main/codex/trust/hooks/codex-hook-approval-first-write.ts @@ -1,5 +1,4 @@ -import '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { CODEX_EVENT_NAME_BY_LABEL } from '../../hooks/definitions/codex-hook-identity' import { readHookTrustBlocks, diff --git a/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts b/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts index 287c7c59cbd..7ab93794078 100644 --- a/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts +++ b/src/main/codex/trust/hooks/codex-hook-orca-approvals.ts @@ -1,8 +1,8 @@ import { MANAGED_HOOK_TIMEOUT_SECONDS, type HooksConfig -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +} from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { readHookTrustEntries, type CodexEventLabel, diff --git a/src/main/codex/trust/hooks/codex-hook-system-trust.ts b/src/main/codex/trust/hooks/codex-hook-system-trust.ts index 2103407e789..3b1fa79cef5 100644 --- a/src/main/codex/trust/hooks/codex-hook-system-trust.ts +++ b/src/main/codex/trust/hooks/codex-hook-system-trust.ts @@ -1,4 +1,4 @@ -import type { HookDefinition } from '../../../agent-hooks/installer-utils' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' import { readHookTrustEntries, type CodexEventLabel, diff --git a/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts b/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts index fd2bbb7d9c3..b136d9fb63a 100644 --- a/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts +++ b/src/main/codex/trust/hooks/codex-hook-trust-cleanup.ts @@ -2,7 +2,7 @@ import { win32 as pathWin32 } from 'node:path' import { MANAGED_HOOK_TIMEOUT_SECONDS, type HookDefinition -} from '../../../agent-hooks/installer-utils' +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { readHookTrustEntries, removeHookTrustEntries, diff --git a/src/main/codex/trust/hooks/codex-hook-trust-memo.ts b/src/main/codex/trust/hooks/codex-hook-trust-memo.ts index 549a9c8972e..26b38cea96f 100644 --- a/src/main/codex/trust/hooks/codex-hook-trust-memo.ts +++ b/src/main/codex/trust/hooks/codex-hook-trust-memo.ts @@ -3,7 +3,7 @@ import { join } from 'node:path' import { isDeepStrictEqual } from 'node:util' import { normalizeRuntimePathForComparison as codexBinaryKey } from '../../../../shared/cross-platform-path' import { writeFileAtomically } from '../../../codex-accounts/fs-utils' -import { isPlainObject } from '../../../agent-hooks/hooks-json-read' +import { isPlainObject } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { getOrcaUserDataPath } from '../../configuration/homes/codex-home-paths' import type { CodexHookAnswer, CodexHookHashes } from './codex-hook-trust-derivation' import { CODEX_MANAGED_EVENT_LABELS } from '../../hooks/definitions/codex-hook-definition' diff --git a/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts b/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts index bbcc8f06357..ace0fc3c6c2 100644 --- a/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts +++ b/src/main/codex/trust/hooks/codex-hook-user-mirroring.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from 'node:fs' -import { removeManagedCommands, type HookDefinition } from '../../../agent-hooks/installer-utils' -import { readHooksJsonWithRaw } from '../../../agent-hooks/hooks-json-read' +import { removeManagedCommands } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJsonWithRaw } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { writeLoadableHookTrustConfig, type CodexEventLabel, diff --git a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts index e46c5b389b7..72f5d9175a6 100644 --- a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts +++ b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.test.ts @@ -3,7 +3,10 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { HookCommandConfig, HookDefinition } from '../../../agent-hooks/installer-utils' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { readHookTrustEntries, upsertHookTrustEntries, diff --git a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts index e922a9ecffc..a8d89b172c4 100644 --- a/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts +++ b/src/main/codex/trust/hooks/codex-user-hook-trust-moves.ts @@ -1,4 +1,7 @@ -import type { HookCommandConfig, HookDefinition } from '../../../agent-hooks/installer-utils' +import type { + HookCommandConfig, + HookDefinition +} from '../../../agent-hooks/installation/configuration/hook-config-schema' import { createCodexHookTrustEntry } from '../../hooks/definitions/codex-hook-identity' import { moveHookTrustEntries, type CodexTrustEntry } from '../toml/config-toml-trust' import { computeCodexTrustKey as computeTrustKey } from '../identity/codex-trust-identity' diff --git a/src/main/codex/trust/hooks/hook-trust-promotion.ts b/src/main/codex/trust/hooks/hook-trust-promotion.ts index a03c2e2e4e2..99b38d56e01 100644 --- a/src/main/codex/trust/hooks/hook-trust-promotion.ts +++ b/src/main/codex/trust/hooks/hook-trust-promotion.ts @@ -1,11 +1,9 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence' -import { - createManagedCommandMatcher, - type HookDefinition -} from '../../../agent-hooks/installer-utils' -import { readHooksJson } from '../../../agent-hooks/hooks-json-read' +import { createManagedCommandMatcher } from '../../../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HookDefinition } from '../../../agent-hooks/installation/configuration/hook-config-schema' +import { readHooksJson } from '../../../agent-hooks/installation/configuration/hooks-json-read' import { getOrcaManagedCodexHomePath, getSystemCodexHomePath diff --git a/src/main/codex/trust/toml/config-toml-hook-trust-read.ts b/src/main/codex/trust/toml/config-toml-hook-trust-read.ts index f9b2779b8c9..fa56aacb4ff 100644 --- a/src/main/codex/trust/toml/config-toml-hook-trust-read.ts +++ b/src/main/codex/trust/toml/config-toml-hook-trust-read.ts @@ -1,5 +1,5 @@ import { parse as parseToml } from 'smol-toml' -import { isPlainObject } from '../../../agent-hooks/hooks-json-read' +import { isPlainObject } from '../../../agent-hooks/installation/configuration/hooks-json-read' import type { CodexHookTrustState } from './config-toml-trust' import { normalizeCodexHookTrustLookupKey } from '../identity/codex-trust-identity' import { findAllHookTrustBlocks } from './config-toml-hook-trust-blocks' diff --git a/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts b/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts index 6d65c82ff22..2a6fdbb1850 100644 --- a/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts +++ b/src/main/codex/trust/toml/config-toml-trust-loadability.test.ts @@ -4,7 +4,9 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type { SFTPWrapper } from 'ssh2' import type * as SmolToml from 'smol-toml' -import type * as InstallerUtilsRemote from '../../../agent-hooks/installer-utils-remote' +import type * as RemoteHooksJson from '../../../agent-hooks/installation/configuration/hooks-json-remote' +import type * as RemoteHookTextFiles from '../../../agent-hooks/installation/remote/hook-text-files-remote' +import type * as ManagedScriptWriteRemote from '../../../agent-hooks/installation/scripts/managed-script-write-remote' const mocks = vi.hoisted(() => { const state: { @@ -28,23 +30,46 @@ vi.mock('smol-toml', async (importOriginal) => { } }) -vi.mock('../../../agent-hooks/installer-utils-remote', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - readHooksJsonRemote: async (_sftp: SFTPWrapper, path: string) => - JSON.parse(mocks.remoteFiles.get(path) ?? '{}'), - readTextFileRemote: async (_sftp: SFTPWrapper, path: string) => - mocks.remoteFiles.get(path) ?? null, - writeHooksJsonRemote: async (_sftp: SFTPWrapper, path: string, config: unknown) => { - mocks.remoteFiles.set(path, JSON.stringify(config)) - }, - writeManagedScriptRemote: async () => {}, - writeTextFileRemoteAtomic: async (_sftp: SFTPWrapper, path: string, content: string) => { - mocks.remoteFiles.set(path, content) +vi.mock( + '../../../agent-hooks/installation/configuration/hooks-json-remote', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readHooksJsonRemote: async (_sftp: SFTPWrapper, path: string) => + JSON.parse(mocks.remoteFiles.get(path) ?? '{}'), + writeHooksJsonRemote: async (_sftp: SFTPWrapper, path: string, config: unknown) => { + mocks.remoteFiles.set(path, JSON.stringify(config)) + } } } -}) +) + +vi.mock( + '../../../agent-hooks/installation/remote/hook-text-files-remote', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readTextFileRemote: async (_sftp: SFTPWrapper, path: string) => + mocks.remoteFiles.get(path) ?? null, + writeTextFileRemoteAtomic: async (_sftp: SFTPWrapper, path: string, content: string) => { + mocks.remoteFiles.set(path, content) + } + } + } +) + +vi.mock( + '../../../agent-hooks/installation/scripts/managed-script-write-remote', + async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + writeManagedScriptRemote: async () => {} + } + } +) import { isCodexConfigTomlRefusedError, diff --git a/src/main/command-code/command-code-managed-script.ts b/src/main/command-code/command-code-managed-script.ts index c7da611a1b8..0c3894f44c3 100644 --- a/src/main/command-code/command-code-managed-script.ts +++ b/src/main/command-code/command-code-managed-script.ts @@ -1,10 +1,10 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installer-utils' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' export type CommandCodeManagedScriptTarget = 'local' | 'posix' diff --git a/src/main/command-code/hook-service.ts b/src/main/command-code/hook-service.ts index 773eec52cab..ec0f628d160 100644 --- a/src/main/command-code/hook-service.ts +++ b/src/main/command-code/hook-service.ts @@ -7,22 +7,24 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - readHooksJson, - removeManagedCommands, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildCommandCodeManagedScript } from './command-code-managed-script' const COMMAND_CODE_EVENTS = [ diff --git a/src/main/copilot/copilot-managed-hook-definitions.ts b/src/main/copilot/copilot-managed-hook-definitions.ts index 2e5d183b3d2..d1b9f419c31 100644 --- a/src/main/copilot/copilot-managed-hook-definitions.ts +++ b/src/main/copilot/copilot-managed-hook-definitions.ts @@ -1,10 +1,8 @@ -import { - wrapPosixHookCommand, - wrapWindowsHookCommand, - type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { getWindowsSystem32Path } from '../agent-hooks/windows-powershell-hook-launcher' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsHookCommand } from '../agent-hooks/installation/commands/windows-hook-command' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' +import { wrapWindowsDirectCmdHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { getWindowsSystem32Path } from '../agent-hooks/installation/commands/windows-powershell-hook-launcher' // VS Code-compatible PascalCase names reuse the hook server's event normalization. export const COPILOT_EVENTS = [ diff --git a/src/main/copilot/copilot-managed-script.ts b/src/main/copilot/copilot-managed-script.ts index 8cd108d8409..30e6d491a9c 100644 --- a/src/main/copilot/copilot-managed-script.ts +++ b/src/main/copilot/copilot-managed-script.ts @@ -1,13 +1,11 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { - buildWindowsAgentHookPostCommand, - getSharedManagedScriptPath -} from '../agent-hooks/installer-utils' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' export function getManagedScriptFileName(): string { return process.platform === 'win32' ? 'copilot-hook.cmd' : 'copilot-hook.sh' diff --git a/src/main/copilot/copilot-remote-hook-install.ts b/src/main/copilot/copilot-remote-hook-install.ts index ece725e0f02..2ddf1168674 100644 --- a/src/main/copilot/copilot-remote-hook-install.ts +++ b/src/main/copilot/copilot-remote-hook-install.ts @@ -2,15 +2,15 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - removeManagedCommands, - wrapPosixHookCommand, - type HookDefinition -} from '../agent-hooks/installer-utils' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { COPILOT_EVENTS } from './copilot-managed-hook-definitions' import { getManagedScript } from './copilot-managed-script' diff --git a/src/main/copilot/hook-service.test.ts b/src/main/copilot/hook-service.test.ts index 35c5c97ef49..b4e09d6d560 100644 --- a/src/main/copilot/hook-service.test.ts +++ b/src/main/copilot/hook-service.test.ts @@ -3,7 +3,8 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' -import { readHooksJson, wrapWindowsHookCommand } from '../agent-hooks/installer-utils' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapWindowsHookCommand } from '../agent-hooks/installation/commands/windows-hook-command' import { COPILOT_EVENTS, getManagedCommand } from './copilot-managed-hook-definitions' import { CopilotHookService } from './hook-service' diff --git a/src/main/copilot/hook-service.ts b/src/main/copilot/hook-service.ts index 4ddabb67e76..5a1bba6e225 100644 --- a/src/main/copilot/hook-service.ts +++ b/src/main/copilot/hook-service.ts @@ -8,12 +8,12 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { createManagedCommandMatcher, - readHooksJson, - removeManagedCommands, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { COPILOT_EVENTS, definitionHasCurrentCommand, diff --git a/src/main/cursor/hook-script.ts b/src/main/cursor/hook-script.ts index bad25d52af8..c6fdceb1cd4 100644 --- a/src/main/cursor/hook-script.ts +++ b/src/main/cursor/hook-script.ts @@ -1,19 +1,17 @@ -import { - buildWindowsAgentHookPostCommand, - wrapPosixHookCommand, - buildWindowsHookPowerShellCommand, - wrapWindowsPowerShellEncodedCommand -} from '../agent-hooks/installer-utils' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { buildWindowsHookPowerShellCommand } from '../agent-hooks/installation/commands/windows-hook-command' +import { wrapWindowsPowerShellEncodedCommand } from '../agent-hooks/installation/commands/windows-powershell-hook-launcher' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { buildPosixGrokReplayGuardLines, buildWindowsGrokReplayGuardLines -} from '../agent-hooks/grok-replay-guard' +} from '../agent-hooks/installation/scripts/grok-replay-guard' import { quoteStartupArg } from '../../shared/agent-launch/startup/tui-agent-startup-shell' import { getCursorHookResponse, type CursorEvent } from './hook-events' diff --git a/src/main/cursor/hook-service.test.ts b/src/main/cursor/hook-service.test.ts index 9de920e7b73..9146476186b 100644 --- a/src/main/cursor/hook-service.test.ts +++ b/src/main/cursor/hook-service.test.ts @@ -6,7 +6,7 @@ import { dirname, join } from 'node:path' import { spawnSync } from 'node:child_process' import { createServer, type Server } from 'node:http' import { runProcess } from '@orca/process-host' -import { findGitBash } from '../agent-hooks/windows-git-bash-path.test-fixture' +import { findGitBash } from '../agent-hooks/installation/commands/testing/windows-git-bash-path.test-fixture' const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() diff --git a/src/main/cursor/hook-service.ts b/src/main/cursor/hook-service.ts index e96c479db32..5264cdaae8d 100644 --- a/src/main/cursor/hook-service.ts +++ b/src/main/cursor/hook-service.ts @@ -7,20 +7,22 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandDefinition, - createManagedCommandMatcher, - getSharedManagedScriptPath, - readHooksJson, - removeManagedCommands, - writeHooksJson, - writeManagedScript, type HookDefinition -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { CURSOR_EVENTS } from './hook-events' import { getManagedCommand, getManagedScript, getPosixManagedCommand } from './hook-script' diff --git a/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts b/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts index b9100133950..50bd696425c 100644 --- a/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts +++ b/src/main/daemon/endpoint/identity/daemon-incarnation-evidence.ts @@ -1,7 +1,7 @@ import { parseLinuxStartTicks, readBootIdentity -} from '../../../agent-hooks/managed-hook-owner-identity' +} from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' import { commandLineMatchesDaemon } from './daemon-pid-identity' import { startTimesWithinTolerance } from './daemon-process-start-time' import { diff --git a/src/main/daemon/endpoint/identity/daemon-ready-identity.ts b/src/main/daemon/endpoint/identity/daemon-ready-identity.ts index fc1c6238ed8..519783894d7 100644 --- a/src/main/daemon/endpoint/identity/daemon-ready-identity.ts +++ b/src/main/daemon/endpoint/identity/daemon-ready-identity.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs' import { parseLinuxStartTicks, readBootIdentity -} from '../../../agent-hooks/managed-hook-owner-identity' +} from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' /** Self-reported identity avoids relying on launcher PIDs that may belong to wrappers. */ export type DaemonReadyIdentity = { diff --git a/src/main/daemon/executable-host/linux/daemon-host-image.ts b/src/main/daemon/executable-host/linux/daemon-host-image.ts index 3e74561fe5b..5639f590eb5 100644 --- a/src/main/daemon/executable-host/linux/daemon-host-image.ts +++ b/src/main/daemon/executable-host/linux/daemon-host-image.ts @@ -2,7 +2,7 @@ // Probe proc metadata rather than traversing potentially wedged FUSE mounts. import { lstatSync, readFileSync, readlinkSync } from 'node:fs' import type { ParsedDaemonPid } from '../../endpoint/identity/daemon-pid-file-parse' -import { parseLinuxStartTicks } from '../../../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../../../agent-hooks/installation/locking/managed-hook-owner-identity' import { isFuseMountPoint } from './daemon-appimage-launch' import { appImageEphemeralRootOf } from '../../../../shared/appimage-ephemeral-root' diff --git a/src/main/daemon/health/daemon-liveness-report.ts b/src/main/daemon/health/daemon-liveness-report.ts index 059f03ca7be..6d8e03f6481 100644 --- a/src/main/daemon/health/daemon-liveness-report.ts +++ b/src/main/daemon/health/daemon-liveness-report.ts @@ -1,5 +1,5 @@ /** Only positive death proof earns exited; lazy respawn leaves a gap until the next terminal. */ -import { parseLinuxStartTicks } from '../../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../../agent-hooks/installation/locking/managed-hook-owner-identity' import { checkDaemonHealthWithCoverage, type DaemonHealthCheck } from './daemon-health' import { inspectProcessLiveness, diff --git a/src/main/devin/hook-config-json.ts b/src/main/devin/hook-config-json.ts index 12f15ed9678..c02db189629 100644 --- a/src/main/devin/hook-config-json.ts +++ b/src/main/devin/hook-config-json.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync } from 'node:fs' import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser' -import { isPlainObject, type HooksConfig } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' /** Devin documents config.json as JSONC; stock JSON.parse rejects comments. */ export function readDevinHooksConfig(configPath: string): HooksConfig | null { diff --git a/src/main/devin/hook-service.ts b/src/main/devin/hook-service.ts index 1df8db33575..117a9c552fd 100644 --- a/src/main/devin/hook-service.ts +++ b/src/main/devin/hook-service.ts @@ -3,23 +3,19 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' -import { - readTextFileRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { readTextFileRemote } from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeHooksJsonRemote } from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyDevinManagedHooks, DEVIN_EVENTS, diff --git a/src/main/devin/hook-settings.ts b/src/main/devin/hook-settings.ts index d77c93e44a5..3ce2693b522 100644 --- a/src/main/devin/hook-settings.ts +++ b/src/main/devin/hook-settings.ts @@ -2,14 +2,16 @@ import { homedir } from 'node:os' import { join } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - removeManagedCommands, - wrapPosixHookCommand, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' const DEVIN_SCRIPT_BASE = 'devin-hook' diff --git a/src/main/droid/hook-service.ts b/src/main/droid/hook-service.ts index ed51a9bd834..19698a6f15e 100644 --- a/src/main/droid/hook-service.ts +++ b/src/main/droid/hook-service.ts @@ -7,30 +7,32 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandHook, - createManagedCommandMatcher, - buildWindowsAgentHookPostCommand, - getSharedManagedScriptPath, - readHooksJson, - removeManagedCommands, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' // SessionStart clears prompt/tool caches on resume before the next user prompt. const DROID_EVENTS = [ diff --git a/src/main/dsh/hook-service.ts b/src/main/dsh/hook-service.ts index 3d40f6f2a6a..e36fcf4198a 100644 --- a/src/main/dsh/hook-service.ts +++ b/src/main/dsh/hook-service.ts @@ -7,23 +7,21 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { - buildWindowsAgentHookCurlPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { buildPosixScrubSafeEnvRestoreLines, buildWindowsScrubSafeEnvRestoreLines diff --git a/src/main/dsh/hook-settings.ts b/src/main/dsh/hook-settings.ts index f4e71aad5b4..6304c05e353 100644 --- a/src/main/dsh/hook-settings.ts +++ b/src/main/dsh/hook-settings.ts @@ -2,13 +2,13 @@ import { homedir } from 'node:os' import { join, posix as pathPosix } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { readManagedHookEventsFromJson } from '../agent-hooks/managed-hooks-json-events' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { readManagedHookEventsFromJson } from '../agent-hooks/installation/configuration/managed-hooks-json-events' const DSH_SCRIPT_BASE = 'dsh-hook' diff --git a/src/main/external-conversations/external-conversation-cancel.test.ts b/src/main/external-conversations/external-conversation-cancel.test.ts index 38f93088f53..adbba524b56 100644 --- a/src/main/external-conversations/external-conversation-cancel.test.ts +++ b/src/main/external-conversations/external-conversation-cancel.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import type { ConversationEvent } from './external-conversation-events' import type { ConversationKey } from './external-conversation-types' import { diff --git a/src/main/external-conversations/external-conversation-events.ts b/src/main/external-conversations/external-conversation-events.ts index 20066bc110e..47573ddd9ef 100644 --- a/src/main/external-conversations/external-conversation-events.ts +++ b/src/main/external-conversations/external-conversation-events.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import { agentMainAgentVerdict } from '../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { PendingPrompt } from '../../shared/agent-status/contracts/agent-pending-prompt' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/external-conversations/external-conversation-links.ts b/src/main/external-conversations/external-conversation-links.ts index cdb6cbb3b10..6b79d4863d9 100644 --- a/src/main/external-conversations/external-conversation-links.ts +++ b/src/main/external-conversations/external-conversation-links.ts @@ -12,7 +12,7 @@ import { import { normalizeAgentProviderSession } from '../../shared/agent-session/lifecycle/agent-session-resume' import { readAllWorktreeMetaForHost } from '../persistence/host-qualified-worktree-meta' import { folderWorkspaceKey } from '../../shared/workspace-scope' -import type { AgentPaneWorkspace } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../agent-hooks/observations/agent-transition-detector' import { readWorkspaceRecord, writeWorkspaceRecord, diff --git a/src/main/external-conversations/external-conversation-prompts.test.ts b/src/main/external-conversations/external-conversation-prompts.test.ts index fbad128ef09..996f8e57154 100644 --- a/src/main/external-conversations/external-conversation-prompts.test.ts +++ b/src/main/external-conversations/external-conversation-prompts.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import { AGENT_DONE_QUIET_MS, diff --git a/src/main/external-conversations/external-conversation-seam.test-fixture.ts b/src/main/external-conversations/external-conversation-seam.test-fixture.ts index e594e6cb4b7..dbb72d8b2d6 100644 --- a/src/main/external-conversations/external-conversation-seam.test-fixture.ts +++ b/src/main/external-conversations/external-conversation-seam.test-fixture.ts @@ -1,6 +1,6 @@ import type { GlobalSettings } from '../../shared/global-settings-types' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import { OrchestrationDb } from '../runtime/orchestration/db/orchestration-db' import { DeliveryReceipts } from './external-conversation-delivery-receipts' import { ExternalConversationSeam } from './external-conversation-seam' diff --git a/src/main/external-conversations/external-conversation-seam.ts b/src/main/external-conversations/external-conversation-seam.ts index 13262ccb78b..ec15f8050ed 100644 --- a/src/main/external-conversations/external-conversation-seam.ts +++ b/src/main/external-conversations/external-conversation-seam.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../agent-hooks/observations/agent-transition-detector' import type { PendingPrompt } from '../../shared/agent-status/contracts/agent-pending-prompt' import type { AgentStatusHooksSettings } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/external-conversations/external-conversation-start.ts b/src/main/external-conversations/external-conversation-start.ts index eb3f3de6f70..86a6edcf787 100644 --- a/src/main/external-conversations/external-conversation-start.ts +++ b/src/main/external-conversations/external-conversation-start.ts @@ -9,7 +9,7 @@ import { executeAgentLaunch } from '../agent-launch/agent-launch-executor' import { agentPaneWorkspace, type AgentPaneWorkspace -} from '../agent-hooks/agent-transition-detector' +} from '../agent-hooks/observations/agent-transition-detector' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { resolveUnlaunchedIntent } from '../runtime/rpc/methods/agent-launch/agent-launch-intent-resolution' import { agentLaunchSurfaceFactory } from '../runtime/rpc/methods/agent-launch/agent-launch-surfaces' diff --git a/src/main/external-conversations/external-conversation.test-fixture.ts b/src/main/external-conversations/external-conversation.test-fixture.ts index 5475606b7ab..6cf09de158b 100644 --- a/src/main/external-conversations/external-conversation.test-fixture.ts +++ b/src/main/external-conversations/external-conversation.test-fixture.ts @@ -8,7 +8,7 @@ import type { Repo } from '../../shared/repo-types' import type { PtyLivenessVerdict } from '../../shared/terminal/pty/lifecycle/pty-liveness-verdict' import type { RuntimeTerminalSend } from '../../shared/runtime-terminal-send-contract' import type { HostWorktreeTarget } from '../../shared/worktree/host-qualified-identity' -import type { AgentPaneWorkspace } from '../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../agent-hooks/observations/agent-transition-detector' import type { LaunchedAgentForeground } from '../runtime/terminal/wait/launched-agent-foreground' import type { ExternalConversationLinkStore } from './external-conversation-links' diff --git a/src/main/external-conversations/external-conversations-install.ts b/src/main/external-conversations/external-conversations-install.ts index 23a5c9dca00..b8daa142a97 100644 --- a/src/main/external-conversations/external-conversations-install.ts +++ b/src/main/external-conversations/external-conversations-install.ts @@ -1,5 +1,5 @@ import type { GlobalSettings } from '../../shared/global-settings-types' -import type { AgentTransitionDetector } from '../agent-hooks/agent-transition-detector' +import type { AgentTransitionDetector } from '../agent-hooks/observations/agent-transition-detector' import type { RuntimeWorktreeLifecycleEvent } from '../runtime/workspaces/lifecycle/worktree-lifecycle-event' import { DeliveryReceipts, type DeliveryReceiptDb } from './external-conversation-delivery-receipts' import type { ExternalConversationLinkStore } from './external-conversation-links' diff --git a/src/main/gemini/hook-service.ts b/src/main/gemini/hook-service.ts index 347f41b295f..7735667a9e1 100644 --- a/src/main/gemini/hook-service.ts +++ b/src/main/gemini/hook-service.ts @@ -7,30 +7,32 @@ import type { } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { buildManagedCommandHook, - createManagedCommandMatcher, - buildWindowsAgentHookPostCommand, - getSharedManagedScriptPath, MANAGED_HOOK_TIMEOUT_MILLISECONDS, - readHooksJson, - removeManagedCommands, - wrapPosixHookCommand, - writeHooksJson, - writeManagedScript, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { readHooksJson } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' // Gemini has no permission-prompt hook, so approvals cannot produce an Orca waiting state. // Gemini uses BeforeTool; remove stale Claude-style PreToolUse registrations below. diff --git a/src/main/grok/grok-hook-backup-cleanup.ts b/src/main/grok/grok-hook-backup-cleanup.ts index 1e908564b89..9eb808b1ba2 100644 --- a/src/main/grok/grok-hook-backup-cleanup.ts +++ b/src/main/grok/grok-hook-backup-cleanup.ts @@ -1,6 +1,7 @@ import { lstatSync, rmSync, writeFileSync } from 'node:fs' import { lstat, rm, writeFile } from 'node:fs/promises' -import { readHooksJsonWithRaw, type HooksConfig } from '../agent-hooks/installer-utils' +import { readHooksJsonWithRaw } from '../agent-hooks/installation/configuration/hooks-json-read' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' import { hasErrorCode } from '../daemon/endpoint/identity/daemon-process-inspection' import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' import { readGrokHookConfigSnapshot } from './grok-hook-config-file' diff --git a/src/main/grok/grok-hook-config-cleanup.ts b/src/main/grok/grok-hook-config-cleanup.ts index bdb770c421d..bda9a9f2ac7 100644 --- a/src/main/grok/grok-hook-config-cleanup.ts +++ b/src/main/grok/grok-hook-config-cleanup.ts @@ -1,9 +1,9 @@ import { createManagedCommandMatcher, hookDefinitionHasManagedCommand, - removeManagedCommands, - type HooksConfig -} from '../agent-hooks/installer-utils' + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' export type GrokHookConfigCleanup = { config: HooksConfig diff --git a/src/main/grok/grok-hook-config-file.ts b/src/main/grok/grok-hook-config-file.ts index 975b9834938..86ca41c7212 100644 --- a/src/main/grok/grok-hook-config-file.ts +++ b/src/main/grok/grok-hook-config-file.ts @@ -1,8 +1,8 @@ import { randomUUID } from 'node:crypto' import { constants } from 'node:fs' import { copyFile, lstat, open, readFile, realpath, rename, rm, stat } from 'node:fs/promises' -import { parseHooksJsonText } from '../agent-hooks/hooks-json-read' -import type { HooksConfig } from '../agent-hooks/installer-utils' +import { parseHooksJsonText } from '../agent-hooks/installation/configuration/hooks-json-read' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' export type AsyncGrokHookConfigSnapshot = { raw: string | null diff --git a/src/main/grok/grok-hook-config.ts b/src/main/grok/grok-hook-config.ts index e20a860b7ad..39c4a5a4dcc 100644 --- a/src/main/grok/grok-hook-config.ts +++ b/src/main/grok/grok-hook-config.ts @@ -1,10 +1,12 @@ import { buildManagedCommandHook, - createManagedCommandMatcher, - removeManagedCommands, type HookDefinition, type HooksConfig -} from '../agent-hooks/installer-utils' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' export const GROK_TOOL_EVENT_MATCHER = '.*' diff --git a/src/main/grok/grok-hook-remote-install.ts b/src/main/grok/grok-hook-remote-install.ts index d8e6b1af698..02d115fd0dc 100644 --- a/src/main/grok/grok-hook-remote-install.ts +++ b/src/main/grok/grok-hook-remote-install.ts @@ -1,12 +1,12 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { wrapPosixHookCommand } from '../agent-hooks/installer-utils' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' import { readHooksJsonRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' + writeHooksJsonRemote +} from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildInstalledGrokConfig } from './grok-hook-config' import { GROK_HOME_ENVELOPE_MAX_LENGTH } from './windows-grok-hook-script' diff --git a/src/main/grok/grok-hook-script.ts b/src/main/grok/grok-hook-script.ts index 411e250960e..92c8c19424f 100644 --- a/src/main/grok/grok-hook-script.ts +++ b/src/main/grok/grok-hook-script.ts @@ -1,11 +1,12 @@ -import { posixCurlCommand } from '../agent-hooks/hook-post-command' -import { getSharedManagedScriptPath, wrapPosixHookCommand } from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, POSIX_HOOK_JSON_STDIN -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { buildWindowsGrokHookScript, GROK_HOME_ENVELOPE_MAX_LENGTH diff --git a/src/main/grok/hook-service.ts b/src/main/grok/hook-service.ts index ff008c35df4..a9a5e7b9bfe 100644 --- a/src/main/grok/hook-service.ts +++ b/src/main/grok/hook-service.ts @@ -8,11 +8,11 @@ import type { import { resolveGrokHomeDir } from '../../shared/grok-session-paths' import { readHooksJson, - readHooksJsonWithRaw, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' + readHooksJsonWithRaw +} from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { isOrcaOwnedRemnant, removeManagedGrokHookEntries } from './grok-hook-config-cleanup' import { removeGrokHookBackupEntries, diff --git a/src/main/grok/windows-grok-hook-script.ts b/src/main/grok/windows-grok-hook-script.ts index ddcbfa5e5f4..0be96de50ca 100644 --- a/src/main/grok/windows-grok-hook-script.ts +++ b/src/main/grok/windows-grok-hook-script.ts @@ -1,5 +1,5 @@ -import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installer-utils' -import { buildWindowsHookEnvironmentGuardLines } from '../agent-hooks/hook-stdin-contract' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { buildWindowsHookEnvironmentGuardLines } from '../agent-hooks/installation/scripts/hook-stdin-contract' /** Matches the envelope length cap used by the POSIX grok-hook branch. */ export const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096 diff --git a/src/main/grok/windows-hook-launcher-chain.test.ts b/src/main/grok/windows-hook-launcher-chain.test.ts index 104c360a39d..9002d7e4eec 100644 --- a/src/main/grok/windows-hook-launcher-chain.test.ts +++ b/src/main/grok/windows-hook-launcher-chain.test.ts @@ -17,7 +17,8 @@ vi.mock('os', async () => { }) import { getManagedCommandForTests, GrokHookService } from './hook-service' -import { wrapWindowsHookCommand, type HooksConfig } from '../agent-hooks/installer-utils' +import { wrapWindowsHookCommand } from '../agent-hooks/installation/commands/windows-hook-command' +import type { HooksConfig } from '../agent-hooks/installation/configuration/hook-config-schema' import { buildInstalledGrokConfig } from './grok-hook-config' const GROK_EVENT_NAMES = [ diff --git a/src/main/hermes/hermes-config-comment-boundaries.test.ts b/src/main/hermes/hermes-config-comment-boundaries.test.ts index 2a8abd0af21..32493acb4e0 100644 --- a/src/main/hermes/hermes-config-comment-boundaries.test.ts +++ b/src/main/hermes/hermes-config-comment-boundaries.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { describe, expect, it, vi } from 'vitest' import { parseDocument } from 'yaml' -import { createManagedHookLocalFilesystem } from '../agent-hooks/managed-hook-local-filesystem.test-fixture' +import { createManagedHookLocalFilesystem } from '../agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture' import { disablePlugin, enablePlugin, diff --git a/src/main/hermes/hermes-config-remote-adapter.test.ts b/src/main/hermes/hermes-config-remote-adapter.test.ts index 226b93aa525..57f47e2db5f 100644 --- a/src/main/hermes/hermes-config-remote-adapter.test.ts +++ b/src/main/hermes/hermes-config-remote-adapter.test.ts @@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSyn import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createManagedHookLocalFilesystem } from '../agent-hooks/managed-hook-local-filesystem.test-fixture' +import { createManagedHookLocalFilesystem } from '../agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture' import { HermesHookService } from './hook-service' describe('Hermes remote installer through a local filesystem adapter (no SSH)', () => { diff --git a/src/main/hermes/hermes-home-filesystem.ts b/src/main/hermes/hermes-home-filesystem.ts index d4daa431c8f..09f18c55dc7 100644 --- a/src/main/hermes/hermes-home-filesystem.ts +++ b/src/main/hermes/hermes-home-filesystem.ts @@ -1,11 +1,10 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import type { ConfigParseResult, HermesConfig } from './hermes-config-yaml' -import { parseHermesConfig } from './hermes-config-yaml' +import { type ConfigParseResult, type HermesConfig, parseHermesConfig } from './hermes-config-yaml' import { getHermesHome } from './hermes-default-home' -import { resolveHooksJsonWritePath } from '../agent-hooks/hook-config-write-path' -import { writeHooksJson } from '../agent-hooks/installer-utils' +import { resolveHooksJsonWritePath } from '../agent-hooks/installation/configuration/hook-config-write-path' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' import { HERMES_PLUGIN_MARKER, HERMES_PLUGIN_NAME, diff --git a/src/main/hermes/hook-service.ts b/src/main/hermes/hook-service.ts index 9296c297f05..e4712303670 100644 --- a/src/main/hermes/hook-service.ts +++ b/src/main/hermes/hook-service.ts @@ -9,9 +9,10 @@ import { listRemoteDirectory, readTextFileRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' -import type { HermesConfig } from './hermes-config-yaml' +} from '../agent-hooks/installation/remote/hook-text-files-remote' + import { + type HermesConfig, disablePlugin, enablePlugin, getConfigEnablement, diff --git a/src/main/ipc/agent-hooks.test.ts b/src/main/ipc/agent-hooks.test.ts index fcce63080a8..d0c28dd513f 100644 --- a/src/main/ipc/agent-hooks.test.ts +++ b/src/main/ipc/agent-hooks.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as AgentHookServerModule from '../agent-hooks/server' +import type * as AgentHookServerModule from '../agent-hooks/server/agent-hook-server' import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id' // Renderer dismissals must evict persisted status as well as the live row. @@ -36,9 +36,11 @@ vi.mock('electron', () => ({ } })) -vi.mock('../agent-hooks/server', async () => { +vi.mock('../agent-hooks/server/agent-hook-server', async () => { // Use the real pane-key validator so invalid-input coverage tracks its constraints. - const actual = await vi.importActual('../agent-hooks/server') + const actual = await vi.importActual( + '../agent-hooks/server/agent-hook-server' + ) return { ...actual, agentHookServer: { @@ -55,7 +57,7 @@ vi.mock('../agent-hooks/server', async () => { } }) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => ({ +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => ({ clearMigrationUnsupportedPtysByTabPrefix, clearMigrationUnsupportedPtysForPaneKey, getMigrationUnsupportedPtySnapshot: vi.fn(() => []) diff --git a/src/main/ipc/agent-hooks.ts b/src/main/ipc/agent-hooks.ts index 4bc8d1f18bd..20f770fd93e 100644 --- a/src/main/ipc/agent-hooks.ts +++ b/src/main/ipc/agent-hooks.ts @@ -5,8 +5,8 @@ import type { } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentInterruptInferenceRequest } from '../../shared/agent-status/lifecycle/agent-interrupt-intent' import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-status/lifecycle/agent-question-answered-intent' -import { agentHookServer } from '../agent-hooks/server' -import { getMigrationUnsupportedPtySnapshot } from '../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { getMigrationUnsupportedPtySnapshot } from '../agent-hooks/observations/migration-unsupported-pty-state' import { registerAgentPaneAuthorityIpcHandlers } from './agent-pane-authority-ipc' import { registerAgentStatusRowTeardownIpcHandlers } from './agent-status-row-teardown-ipc' import { createAgentPaneAuthorityOwnership } from './agent-pane-authority-ownership' diff --git a/src/main/ipc/agent-pane-authority-ipc.ts b/src/main/ipc/agent-pane-authority-ipc.ts index 7c967178b23..4670017e32e 100644 --- a/src/main/ipc/agent-pane-authority-ipc.ts +++ b/src/main/ipc/agent-pane-authority-ipc.ts @@ -1,8 +1,8 @@ import { ipcMain } from 'electron' import { isStablePaneId } from '../../shared/workspace-layout/stable-pane-id' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isValidPaneKey } from '../agent-hooks/server/server-status-identity' -import { clearMigrationUnsupportedPtysForPaneKey } from '../agent-hooks/migration-unsupported-pty-state' +import { clearMigrationUnsupportedPtysForPaneKey } from '../agent-hooks/observations/migration-unsupported-pty-state' const MAX_PTY_ID_LENGTH = 512 diff --git a/src/main/ipc/agent-pane-retirement-ipc.test.ts b/src/main/ipc/agent-pane-retirement-ipc.test.ts index ab46d02fef4..a2db1dd1bec 100644 --- a/src/main/ipc/agent-pane-retirement-ipc.test.ts +++ b/src/main/ipc/agent-pane-retirement-ipc.test.ts @@ -12,13 +12,13 @@ vi.mock('electron', () => ({ on: (name: string, callback: (...args: unknown[]) => void) => mocks.handlers.set(name, callback) } })) -vi.mock('../agent-hooks/server', () => ({ +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { retirePaneAuthority: mocks.retire } })) vi.mock('../agent-hooks/server/server-status-identity', () => ({ isValidPaneKey: (key: string) => key.includes(':') })) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => ({ +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => ({ clearMigrationUnsupportedPtysForPaneKey: mocks.clear })) import { registerAgentPaneAuthorityIpcHandlers } from './agent-pane-authority-ipc' diff --git a/src/main/ipc/agent-status-row-teardown-ipc.ts b/src/main/ipc/agent-status-row-teardown-ipc.ts index ab2338b0300..264f44a3dc2 100644 --- a/src/main/ipc/agent-status-row-teardown-ipc.ts +++ b/src/main/ipc/agent-status-row-teardown-ipc.ts @@ -1,12 +1,12 @@ import { ipcMain } from 'electron' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isValidPaneKey } from '../agent-hooks/server/server-status-identity' import type { AgentStatusCacheIdentity } from '../../shared/agent-status/contracts/agent-status-ipc-payload' import { parseLegacyNumericPaneKey } from '../../shared/workspace-layout/stable-pane-id' import { clearMigrationUnsupportedPtysByTabPrefix, clearMigrationUnsupportedPtysForPaneKey -} from '../agent-hooks/migration-unsupported-pty-state' +} from '../agent-hooks/observations/migration-unsupported-pty-state' import { isValidAgentStatusDropTabId } from './agent-status-ipc-boundary' /** Dismissal preserves live pane caches; confirmed exits must clear latches that could revive a stale working row. */ diff --git a/src/main/ipc/pty-claude-agent-view-readiness.test.ts b/src/main/ipc/pty-claude-agent-view-readiness.test.ts index 8a3fcfe6a53..0247392ffbe 100644 --- a/src/main/ipc/pty-claude-agent-view-readiness.test.ts +++ b/src/main/ipc/pty-claude-agent-view-readiness.test.ts @@ -18,7 +18,7 @@ vi.mock('../opencode/hook-service', () => vi.mock('../mimo/hook-service', () => import('./pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../agent-hooks/server', () => +vi.mock('../agent-hooks/server/agent-hook-server', () => import('./pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../pi/titlebar-extension-service', () => @@ -42,7 +42,7 @@ vi.mock('../cli/linux-terminal-orca-cli-shim', () => vi.mock('../memory/pty-registry', () => import('./pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts b/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts index 620ca2bcb3f..b46881130cb 100644 --- a/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts +++ b/src/main/ipc/pty-degraded-fallback-single-ingest.test.ts @@ -21,7 +21,7 @@ vi.mock('../opencode/hook-service', () => vi.mock('../mimo/hook-service', () => import('./pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../agent-hooks/server', () => +vi.mock('../agent-hooks/server/agent-hook-server', () => import('./pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../pi/titlebar-extension-service', () => @@ -45,7 +45,7 @@ vi.mock('../cli/linux-terminal-orca-cli-shim', () => vi.mock('../memory/pty-registry', () => import('./pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty-spawn-saved-resume-admission.test.ts b/src/main/ipc/pty-spawn-saved-resume-admission.test.ts index bc7f682dc22..d5139e457ab 100644 --- a/src/main/ipc/pty-spawn-saved-resume-admission.test.ts +++ b/src/main/ipc/pty-spawn-saved-resume-admission.test.ts @@ -24,7 +24,7 @@ vi.mock('../opencode/hook-service', () => vi.mock('../mimo/hook-service', () => import('./pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../agent-hooks/server', () => +vi.mock('../agent-hooks/server/agent-hook-server', () => import('./pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../pi/titlebar-extension-service', () => @@ -48,7 +48,7 @@ vi.mock('../cli/linux-terminal-orca-cli-shim', () => vi.mock('../memory/pty-registry', () => import('./pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/host-env/assembly.ts b/src/main/ipc/pty/host-env/assembly.ts index 127ed52945f..8fbb59ecc82 100644 --- a/src/main/ipc/pty/host-env/assembly.ts +++ b/src/main/ipc/pty/host-env/assembly.ts @@ -8,8 +8,8 @@ import { import { applyTerminalGitCredentialPromptGuard } from '../../../../shared/shell/launch/terminal-git-credential-guard' import { ensureOpenCodeStartupPromptForLaunch } from '../../../opencode/opencode-startup-prompt-installer' import { mimoCodeHookService } from '../../../mimo/hook-service' -import { agentHookServer } from '../../../agent-hooks/server' -import { wslHookRelayManager } from '../../../agent-hooks/wsl-hook-relay-manager' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { wslHookRelayManager } from '../../../agent-hooks/wsl-relay/wsl-hook-relay-manager' import { wslInteropHealthMonitor } from '../../../wsl/execution/wsl-interop-health' import { piTitlebarExtensionService } from '../../../pi/titlebar-extension-service' import { prependOrcaCliDirToChildPath } from '../../../cli/orca-cli-child-path' diff --git a/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts b/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts index 658c0a4b087..daa8444df1d 100644 --- a/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts +++ b/src/main/ipc/pty/host-env/opencode-hook-installation.test.ts @@ -9,10 +9,10 @@ const fixture = vi.hoisted(() => ({ userData: '', guestOverlay: '' })) vi.mock('../../../../shared/app-environment', () => ({ getAppEnvironment: () => ({ getPath: () => fixture.userData, onWillQuit: vi.fn() }) })) -vi.mock('../../../agent-hooks/server', () => ({ +vi.mock('../../../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { buildPtyEnv: () => ({ ORCA_AGENT_HOOK_PORT: '12345' }) } })) -vi.mock('../../../agent-hooks/wsl-hook-relay-manager', () => ({ +vi.mock('../../../agent-hooks/wsl-relay/wsl-hook-relay-manager', () => ({ wslHookRelayManager: { ensureForDistro: vi.fn(), getGuestEndpointFilePath: () => '/guest/endpoint.json', diff --git a/src/main/ipc/pty/host-env/saved-resume-admission.ts b/src/main/ipc/pty/host-env/saved-resume-admission.ts index 1db28b59d9d..a96c8a5548b 100644 --- a/src/main/ipc/pty/host-env/saved-resume-admission.ts +++ b/src/main/ipc/pty/host-env/saved-resume-admission.ts @@ -15,7 +15,7 @@ import { agentSessionLeasePossiblyWriting, listStructuredProviderSessionOwnership } from '../../../native-chat/agent-session-wire/host/structured-provider-session-ownership' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../../shared/execution-host' import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types' import { diff --git a/src/main/ipc/pty/pane/complete-pane-adoption.ts b/src/main/ipc/pty/pane/complete-pane-adoption.ts index a2d1059cf14..baed9d5cd85 100644 --- a/src/main/ipc/pty/pane/complete-pane-adoption.ts +++ b/src/main/ipc/pty/pane/complete-pane-adoption.ts @@ -21,8 +21,8 @@ import { } from './agent-session-owners' import { seedHeadlessTerminalFromSpawnResult } from './terminal-spawn-restore' import { admitProviderReattachLaunchIdentity } from './launch-authority' -import { ensureWslHookRelayForReattach } from '../../../agent-hooks/wsl-hook-relay-reattach' -import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-bridge-pty-presence' +import { ensureWslHookRelayForReattach } from '../../../agent-hooks/wsl-relay/wsl-hook-relay-reattach' +import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-relay/wsl-bridge-pty-presence' import '../spawn-outcome' import { provenSpawnResponse } from '../../../../shared/terminal/pty/lifecycle/terminal-spawn-response' import { ptySizes } from '../delivery/visibility-state' diff --git a/src/main/ipc/pty/pane/resume-launch-identity.ts b/src/main/ipc/pty/pane/resume-launch-identity.ts index fb7645125ce..34603b6057a 100644 --- a/src/main/ipc/pty/pane/resume-launch-identity.ts +++ b/src/main/ipc/pty/pane/resume-launch-identity.ts @@ -1,4 +1,4 @@ -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { isResumableTuiAgent, normalizeAgentProviderSession diff --git a/src/main/ipc/pty/provider/bind-listeners.ts b/src/main/ipc/pty/provider/bind-listeners.ts index b8813dba24e..a9934a91fcc 100644 --- a/src/main/ipc/pty/provider/bind-listeners.ts +++ b/src/main/ipc/pty/provider/bind-listeners.ts @@ -1,5 +1,5 @@ import { isCurrentPtyExit, ptyOwnership } from './ownership-state' -import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-bridge-pty-presence' +import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-relay/wsl-bridge-pty-presence' import { localBackgroundStreamUnsub, localDataUnsub, diff --git a/src/main/ipc/pty/provider/local-configure.ts b/src/main/ipc/pty/provider/local-configure.ts index 9e9dc71a9ab..0126e7d6053 100644 --- a/src/main/ipc/pty/provider/local-configure.ts +++ b/src/main/ipc/pty/provider/local-configure.ts @@ -26,7 +26,7 @@ import { localProvider } from './registry' import { clearProviderPtyState } from './state-cleanup' import { visibleRendererPtys } from '../delivery/visibility-state' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' -import { awaitExplicitAgentPluginGuestReadiness } from '../../../agent-hooks/wsl-agent-plugin-readiness' +import { awaitExplicitAgentPluginGuestReadiness } from '../../../agent-hooks/wsl-relay/wsl-agent-plugin-readiness' import { prepareAntigravityAccountForLaunch } from '../../../antigravity/native-account-launch' export function configureLocalPtyProvider(args: { diff --git a/src/main/ipc/pty/provider/state-cleanup.ts b/src/main/ipc/pty/provider/state-cleanup.ts index 304e615ce49..59a9b1bfbe3 100644 --- a/src/main/ipc/pty/provider/state-cleanup.ts +++ b/src/main/ipc/pty/provider/state-cleanup.ts @@ -3,8 +3,8 @@ import { unregisterPty } from '../../../memory/pty-registry' import { forgetCodexPaneAccount } from '../../../codex/configuration/homes/codex-pane-account-registry' import { openCodeHookService } from '../../../opencode/hook-service' import { piTitlebarExtensionService } from '../../../pi/titlebar-extension-service' -import { agentHookServer } from '../../../agent-hooks/server' -import { clearMigrationUnsupportedPty } from '../../../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { clearMigrationUnsupportedPty } from '../../../agent-hooks/observations/migration-unsupported-pty-state' import { clearNativeWindowsConptyPty } from '../../../runtime/terminal/output/terminal-model-query-authority' import { clearHiddenRendererPtyDeliveryState, diff --git a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts index 7022d13def6..17b5a04200b 100644 --- a/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts +++ b/src/main/ipc/pty/pty-closed-pane-spawn-refusal.test.ts @@ -24,7 +24,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -48,7 +48,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-controller-ownership-routing.test.ts b/src/main/ipc/pty/pty-controller-ownership-routing.test.ts index b048a49e775..631df8b569e 100644 --- a/src/main/ipc/pty/pty-controller-ownership-routing.test.ts +++ b/src/main/ipc/pty/pty-controller-ownership-routing.test.ts @@ -17,7 +17,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -41,7 +41,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-controller-spawn-admission.test.ts b/src/main/ipc/pty/pty-controller-spawn-admission.test.ts index c528fb4adc1..5079597303f 100644 --- a/src/main/ipc/pty/pty-controller-spawn-admission.test.ts +++ b/src/main/ipc/pty/pty-controller-spawn-admission.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts b/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts index da3ff0c83fe..44f80f22199 100644 --- a/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts +++ b/src/main/ipc/pty/pty-daemon-spawn-session-identity.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => @@ -48,7 +48,7 @@ vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => vi.mock('../../codex/history/index/codex-state-db-backfill-recovery', () => import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock()) ) -vi.mock('../../agent-hooks/wsl-agent-plugin-readiness', () => ({ +vi.mock('../../agent-hooks/wsl-relay/wsl-agent-plugin-readiness', () => ({ awaitExplicitAgentPluginGuestReadiness: vi.fn(async () => true) })) diff --git a/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts b/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts index 10594388c61..42cbace177e 100644 --- a/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts +++ b/src/main/ipc/pty/pty-pane-reservation-settlement.test.ts @@ -16,7 +16,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -40,7 +40,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-pane-restart-replace.test.ts b/src/main/ipc/pty/pty-pane-restart-replace.test.ts index 16b851d9ba9..025d9c87195 100644 --- a/src/main/ipc/pty/pty-pane-restart-replace.test.ts +++ b/src/main/ipc/pty/pty-pane-restart-replace.test.ts @@ -20,7 +20,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -44,7 +44,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts b/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts index 1b8e8b59a22..a519ac4c3f2 100644 --- a/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts +++ b/src/main/ipc/pty/pty-runtime-kill-and-exit.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts b/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts index 5a6fb9eca9f..afe9e6f188b 100644 --- a/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts +++ b/src/main/ipc/pty/pty-runtime-ssh-binding-persistence.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts b/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts index 159ca4d5809..0e3c9c93970 100644 --- a/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts +++ b/src/main/ipc/pty/pty-session-liveness-and-ownership.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts b/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts index cbf3378f656..374fcd7c691 100644 --- a/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts +++ b/src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts @@ -17,7 +17,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -44,7 +44,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts b/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts index 6d69d721072..91dbd5afd6b 100644 --- a/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts +++ b/src/main/ipc/pty/pty-ssh-stop-verdict.test.ts @@ -21,7 +21,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -45,7 +45,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/pty-write-ipc-validation.test.ts b/src/main/ipc/pty/pty-write-ipc-validation.test.ts index 6766181cba9..6c4eb9da679 100644 --- a/src/main/ipc/pty/pty-write-ipc-validation.test.ts +++ b/src/main/ipc/pty/pty-write-ipc-validation.test.ts @@ -15,7 +15,7 @@ vi.mock('../../opencode/hook-service', () => vi.mock('../../mimo/hook-service', () => import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../agent-hooks/server', () => +vi.mock('../../agent-hooks/server/agent-hook-server', () => import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../pi/titlebar-extension-service', () => @@ -39,7 +39,7 @@ vi.mock('../../cli/linux-terminal-orca-cli-shim', () => vi.mock('../../memory/pty-registry', () => import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../agent-hooks/observations/migration-unsupported-pty-state', () => import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock()) ) vi.mock('../../codex/configuration/homes/codex-pane-account-registry', () => diff --git a/src/main/ipc/pty/spawn-begin.ts b/src/main/ipc/pty/spawn-begin.ts index 81449867661..bce2c924b93 100644 --- a/src/main/ipc/pty/spawn-begin.ts +++ b/src/main/ipc/pty/spawn-begin.ts @@ -10,7 +10,7 @@ import { ptyOwnership, ptyIncarnationById } from './provider/ownership-state' import { attachOnlyViewOf } from './pane/attach-only-view' import { pendingRuntimePaneCreatesByOwnerKey } from './pane/spawn-reservation' import { getConnectionExecutionHostId } from '../../../shared/execution-host' -import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-hook-relay-reattach' +import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-relay/wsl-hook-relay-reattach' export async function beginPtySpawn( ctx: PtySpawnOperationState, diff --git a/src/main/ipc/pty/spawn-commit-publication.ts b/src/main/ipc/pty/spawn-commit-publication.ts index 20c78142206..e7ea0595e92 100644 --- a/src/main/ipc/pty/spawn-commit-publication.ts +++ b/src/main/ipc/pty/spawn-commit-publication.ts @@ -1,5 +1,5 @@ -import { agentHookServer } from '../../agent-hooks/server' -import { clearMigrationUnsupportedPtysForPaneKey } from '../../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { clearMigrationUnsupportedPtysForPaneKey } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { registerPty } from '../../memory/pty-registry' import type { PtySpawnResult } from '../../providers/pty-provider-contract' import { diff --git a/src/main/ipc/pty/spawn-execute.ts b/src/main/ipc/pty/spawn-execute.ts index be3d9dffb4d..fe9fd40396a 100644 --- a/src/main/ipc/pty/spawn-execute.ts +++ b/src/main/ipc/pty/spawn-execute.ts @@ -1,6 +1,6 @@ import type { PtySpawnResult } from '../../providers/pty-provider-contract' import { ptyIncarnationById } from './provider/ownership-state' -import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-hook-relay-reattach' +import { ensureWslHookRelayForReattach } from '../../agent-hooks/wsl-relay/wsl-hook-relay-reattach' import { noteWslDistroWoken, noteWslDistrosRunning @@ -29,7 +29,7 @@ import { failPtySpawnExecute } from './spawn-execute-failure' import type { PtySpawnOperationState, PtySpawnExecutionFacts } from './spawn-operation-state' import { excludeReplacedPaneOwner } from './pane/replaced-pane-owner' import { attachViewWithoutOwner } from './pane/attach-only-view' -import { wslBridgePtyPresence } from '../../agent-hooks/wsl-bridge-pty-presence' +import { wslBridgePtyPresence } from '../../agent-hooks/wsl-relay/wsl-bridge-pty-presence' import { isWslTerminalSpawn } from './wsl-terminal-spawn' export async function executePtySpawn( diff --git a/src/main/ipc/pty/spawn-host-env.ts b/src/main/ipc/pty/spawn-host-env.ts index f6d26aa7dc3..34f34419955 100644 --- a/src/main/ipc/pty/spawn-host-env.ts +++ b/src/main/ipc/pty/spawn-host-env.ts @@ -8,7 +8,7 @@ import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent' import { isTuiAgent } from '../../../shared/agent-launch/catalog/tui-agent-config' import { addWslEnvKeys } from '../../../shared/wsl-env' import { isAgentStatusHooksEnabled } from '../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { awaitExplicitAgentPluginGuestReadiness } from '../../agent-hooks/wsl-agent-plugin-readiness' +import { awaitExplicitAgentPluginGuestReadiness } from '../../agent-hooks/wsl-relay/wsl-agent-plugin-readiness' import { ensureCodexStateDbBackfillRecoveryStarted } from '../../codex/history/index/codex-state-db-backfill-recovery' import type { CodexSessionResumePreparation } from '../../codex/history/resume/codex-session-resume-home' import type { CodexAccountSelectionTarget } from '../../codex-accounts/runtime-selection' diff --git a/src/main/ipc/settings-delayed-response.test.ts b/src/main/ipc/settings-delayed-response.test.ts index b9fede4b633..28e78d6c573 100644 --- a/src/main/ipc/settings-delayed-response.test.ts +++ b/src/main/ipc/settings-delayed-response.test.ts @@ -47,7 +47,7 @@ vi.mock('../window/desktop-integration/app-icon', () => ({ applyAppIcon: vi.fn() vi.mock('../ai-vault-search/session-search-enablement', () => ({ applySessionSearchSettingsChange: vi.fn() })) -vi.mock('../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock })) vi.mock('../workspaces/creation/worktree-root-preparation', () => ({ diff --git a/src/main/ipc/settings-ipc-test-fixture.ts b/src/main/ipc/settings-ipc-test-fixture.ts index 8dcedbbbdba..e8323477db3 100644 --- a/src/main/ipc/settings-ipc-test-fixture.ts +++ b/src/main/ipc/settings-ipc-test-fixture.ts @@ -81,7 +81,7 @@ vi.mock('../ai-vault-search/session-search-enablement', () => ({ vi.mock('../telemetry/client', () => ({ track: vi.fn() })) -vi.mock('../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock })) diff --git a/src/main/ipc/settings.ts b/src/main/ipc/settings.ts index 23a634561fe..95e191f1048 100644 --- a/src/main/ipc/settings.ts +++ b/src/main/ipc/settings.ts @@ -14,9 +14,9 @@ import { track } from '../telemetry/client' import { SETTINGS_CHANGED_WHITELIST, type SettingsChangedKey } from '../../shared/telemetry-events' import type { AgentAwakeService } from '../power/agent-awake-service' import { sanitizeFloatingWorkspaceDirectorySetting } from './floating-workspace-directory' -import { applyAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls' +import { applyAgentStatusHooksEnabled } from '../agent-hooks/installation/managed-agent-hook-controls' import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { recordManagedHookInstallFailure } from '../agent-hooks/install-telemetry' +import { recordManagedHookInstallFailure } from '../agent-hooks/installation/install-telemetry' import { applyElectronProxySettings } from '../network/proxy-settings' import { applyBrowserSessionProxies } from '../browser/sessions/browser-session-proxy' import { applyProxyToElectronUpdaterSession } from '../updater/lifecycle/electron-updater-proxy-session' diff --git a/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts b/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts index 0a6fca7614b..d6105a76212 100644 --- a/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts +++ b/src/main/ipc/worktrees/listing/authoritative-local-worktree-metadata-pruning.ts @@ -8,7 +8,7 @@ import { } from '../../../../shared/worktree/id' import type { GitWorktreeInfo } from '../../../../shared/worktree/types' import { isWslUncPath } from '../../../../shared/wsl-paths' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { Store } from '../../../persistence/loading-store/store' import type { NativeLocalWorktreeMetadataScanExpectation } from '../../../persistence/tracking-repos/missing-local-worktree-metadata-pruning' import { pruneWorkspaceCleanupScanSnapshots } from '../../../workspaces/cleanup/workspace-cleanup-scan-snapshot' diff --git a/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts b/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts index 205185384df..52c34f3fb7c 100644 --- a/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts +++ b/src/main/ipc/worktrees/listing/register-host-catalog-handlers.ts @@ -10,7 +10,7 @@ import type { DetectedWorktree } from '../../../../shared/worktree/types' import { isFolderRepo } from '../../../../shared/repo-kind' import { projectWorktreeLineageWithHostPeers } from '../../../workspaces/catalog/worktree-lineage-host-peers' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { pruneWorkspaceCleanupScanSnapshots } from '../../../workspaces/cleanup/workspace-cleanup-scan-snapshot' import { pruneWorkspaceSpaceAnalysisSnapshots } from '../../../workspaces/space-analysis/workspace-space-analysis-snapshot' import { findExactRepoOwner, hasConflictingStoredWorktreeOwner } from './worktree-host-ownership' diff --git a/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts b/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts index 37284349024..21c66b863ac 100644 --- a/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts +++ b/src/main/ipc/worktrees/metadata/register-worktree-metadata-handlers.ts @@ -10,7 +10,7 @@ import { writeWorktreeSortOrder, type WorktreeSortOrderRequest } from '../../../persistence/worktree-sort-order-write' -import { readBranchRenameFailureOutputForDisplay } from '../../../agent-hooks/branch-rename-failure-output' +import { readBranchRenameFailureOutputForDisplay } from '../../../agent-hooks/first-work/branch-rename-failure-output' import { normalizeLinkedWorkItemFields } from '../ipc-context-schemas' import { isRemovedFolderWorkspaceInstance } from '../../../workspaces/catalog/folder-workspace-meta-presence' import { resolveWorktreeMetaOwner } from '../../../persistence/host-qualified-worktree-meta' diff --git a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts index e4c9fd02783..b5bfea14861 100644 --- a/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts +++ b/src/main/ipc/worktrees/removal/worktree-removal-ownership.ts @@ -3,12 +3,12 @@ import { getLocalPtyProvider } from '../../pty/provider/registry' import { clearProviderPtyState } from '../../pty/provider/state-cleanup' import { killAllProcessesForWorktree } from '../../../runtime/workspaces/removal/worktree-teardown' import type { Store } from '../../../persistence/loading-store/store' -import { getRepoExecutionHostId } from '../../../../shared/execution-host' -import type { ExecutionHostId } from '../../../../shared/execution-host' +import { getRepoExecutionHostId, type ExecutionHostId } from '../../../../shared/execution-host' + import type { Repo } from '../../../../shared/repo-types' import { hasWorktreeRemovalRepoOwnerOnOtherHost } from '../../../workspaces/removal/worktree-removal-repo-owner' import { getRepoIdFromWorktreeId } from '../../../../shared/worktree/id' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { removeWorktreeMetaRow } from '../../../persistence/host-qualified-worktree-meta' import { pruneWorktreePRRefreshAliases } from '../../../github/pr-refresh-coordinator' import { diff --git a/src/main/ipc/wsl/wsl-move-driver-wiring.ts b/src/main/ipc/wsl/wsl-move-driver-wiring.ts index b66817c2556..68ed583e056 100644 --- a/src/main/ipc/wsl/wsl-move-driver-wiring.ts +++ b/src/main/ipc/wsl/wsl-move-driver-wiring.ts @@ -13,7 +13,7 @@ import { WSL_MOVE_PROGRESS_CHANNEL, type WslMoveProgressEvent } from '../../../shared/wsl-move/wsl-move-driver-types' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { getDaemonHistoryDir } from '../../daemon/launch/daemon-launch-paths' import { countInProcessFallbackTerminals, diff --git a/src/main/jcode/hook-config.ts b/src/main/jcode/hook-config.ts index f1c121fca2a..2a3c97c2041 100644 --- a/src/main/jcode/hook-config.ts +++ b/src/main/jcode/hook-config.ts @@ -11,7 +11,7 @@ import { parseTomlKeyPath, parseTomlTableHeaderPath } from '../codex/configuration/toml/config-toml-key-path' -import { createManagedCommandMatcher } from '../agent-hooks/installer-utils' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' import { appendJcodeHookCommand, removeJcodeHookCommand, diff --git a/src/main/jcode/hook-service.ts b/src/main/jcode/hook-service.ts index 62cd0d1e905..6297afcb36b 100644 --- a/src/main/jcode/hook-service.ts +++ b/src/main/jcode/hook-service.ts @@ -5,23 +5,21 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookPostCommand, - createManagedCommandMatcher, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +import { buildWindowsAgentHookPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildWindowsHookEnvironmentGuardLines, POSIX_HOOK_STDIN_DRAIN_COMMAND, WINDOWS_HOOK_STDIN_DRAIN_COMMAND -} from '../agent-hooks/hook-stdin-contract' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' import { applyJcodeManagedHooks, parseJcodeHooksTable, diff --git a/src/main/kimi/hook-service.ts b/src/main/kimi/hook-service.ts index 19a138a683f..c039cdc0920 100644 --- a/src/main/kimi/hook-service.ts +++ b/src/main/kimi/hook-service.ts @@ -18,26 +18,24 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { - buildWindowsAgentHookCurlPostCommand, - createManagedCommandMatcher, - getSharedManagedScriptPath, - wrapPosixHookCommand, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { posixCurlCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { posixCurlCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyManagedKimiHooks, KIMI_HOOK_EVENTS, diff --git a/src/main/kimi/kimi-hook-config-toml.ts b/src/main/kimi/kimi-hook-config-toml.ts index 64653ac100e..b9e274050f5 100644 --- a/src/main/kimi/kimi-hook-config-toml.ts +++ b/src/main/kimi/kimi-hook-config-toml.ts @@ -1,6 +1,6 @@ // Preserve user TOML while managing marker blocks and positively recognized Orca hook tables. -import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installer-utils' +import { MANAGED_HOOK_TIMEOUT_SECONDS } from '../agent-hooks/installation/configuration/hook-config-schema' import { findManagedTomlBlocks, findRecognizedManagedTables, @@ -8,7 +8,7 @@ import { type ManagedTomlMarkers, type ManagedTomlRegion, type RecognizedManagedTable -} from '../agent-hooks/managed-toml-ownership' +} from '../agent-hooks/installation/configuration/managed-toml-ownership' export const KIMI_HOOK_EVENTS = [ 'SessionStart', diff --git a/src/main/kiro/hook-service.test.ts b/src/main/kiro/hook-service.test.ts index 19282c9b7bc..89e5e79092d 100644 --- a/src/main/kiro/hook-service.test.ts +++ b/src/main/kiro/hook-service.test.ts @@ -2,8 +2,8 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { createManagedHookLocalFilesystem } from '../agent-hooks/managed-hook-local-filesystem.test-fixture' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { createManagedHookLocalFilesystem } from '../agent-hooks/installation/remote/testing/managed-hook-local-filesystem.test-fixture' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' import { KiroHookService } from './hook-service' import { getKiroManagedCommandMatcher, KIRO_HOOK_EVENTS } from './hook-settings' diff --git a/src/main/kiro/hook-service.ts b/src/main/kiro/hook-service.ts index f6975f02b04..ad62f8c3be8 100644 --- a/src/main/kiro/hook-service.ts +++ b/src/main/kiro/hook-service.ts @@ -7,25 +7,23 @@ import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { - buildWindowsAgentHookCurlPostCommand, - isPlainObject, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' import { listRemoteDirectory, readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyManagedKiroHooks, getKiroAgentsDir, diff --git a/src/main/kiro/hook-settings.ts b/src/main/kiro/hook-settings.ts index 8741ce87548..9af41894665 100644 --- a/src/main/kiro/hook-settings.ts +++ b/src/main/kiro/hook-settings.ts @@ -2,16 +2,18 @@ import { join, posix as pathPosix } from 'node:path' import { resolveKiroHomeDir } from '../../shared/kiro-home' import { createManagedCommandMatcher, - getSharedManagedScriptPath, hookDefinitionHasManagedCommand, - isPlainObject, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { MANAGED_HOOK_TIMEOUT_MILLISECONDS, MANAGED_HOOK_TIMEOUT_SECONDS, - removeManagedCommands, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' const KIRO_SCRIPT_BASE = 'kiro-hook' diff --git a/src/main/kiro/standalone-hook-settings.ts b/src/main/kiro/standalone-hook-settings.ts index a4e6daa9f9e..b1f78964147 100644 --- a/src/main/kiro/standalone-hook-settings.ts +++ b/src/main/kiro/standalone-hook-settings.ts @@ -1,6 +1,6 @@ import { join, posix as pathPosix } from 'node:path' import { resolveKiroHomeDir } from '../../shared/kiro-home' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' import { buildKiroListHook, getKiroManagedCommandMatcher, diff --git a/src/main/kiro/standalone-hooks.ts b/src/main/kiro/standalone-hooks.ts index 3c17a7106c9..f7bd127e555 100644 --- a/src/main/kiro/standalone-hooks.ts +++ b/src/main/kiro/standalone-hooks.ts @@ -4,9 +4,13 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { parseHooksJsonText, readHooksJsonWithRaw } from '../agent-hooks/hooks-json-read' -import { writeHooksJson } from '../agent-hooks/installer-utils' -import { readTextFileRemote, writeHooksJsonRemote } from '../agent-hooks/installer-utils-remote' +import { + parseHooksJsonText, + readHooksJsonWithRaw +} from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { readTextFileRemote } from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeHooksJsonRemote } from '../agent-hooks/installation/configuration/hooks-json-remote' import { buildKiroStandaloneHooksFile, getKiroStandaloneHooksFileConflict, diff --git a/src/main/muse/hook-config-json.ts b/src/main/muse/hook-config-json.ts index 31c14832d1f..cc32c7f86e0 100644 --- a/src/main/muse/hook-config-json.ts +++ b/src/main/muse/hook-config-json.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' // Muse strips nonstandard environment variables from managed hooks unless allowlisted. export const MUSE_MANAGED_HOOK_ENV_VARS = [ diff --git a/src/main/muse/hook-service.ts b/src/main/muse/hook-service.ts index e4440b7247a..71c67033071 100644 --- a/src/main/muse/hook-service.ts +++ b/src/main/muse/hook-service.ts @@ -6,23 +6,21 @@ import type { AgentHookInstallState, AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookCurlPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { readTextFileRemote, - writeManagedScriptRemote, writeTextFileRemoteAtomic -} from '../agent-hooks/installer-utils-remote' +} from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { buildMuseManagedHooksFile, getMuseConfigPath, diff --git a/src/main/muse/hook-settings.ts b/src/main/muse/hook-settings.ts index c85c1950e5f..d59edb81971 100644 --- a/src/main/muse/hook-settings.ts +++ b/src/main/muse/hook-settings.ts @@ -3,14 +3,14 @@ import { join } from 'node:path' import { readFile } from 'node:fs/promises' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { readManagedHookEventsFromJson } from '../agent-hooks/managed-hooks-json-events' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { createManagedCommandMatcher } from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { readManagedHookEventsFromJson } from '../agent-hooks/installation/configuration/managed-hooks-json-events' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' import { parseMuseSettingsText } from './hook-config-json' const MUSE_SCRIPT_BASE = 'muse-hook' diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts index 94d59e48699..f2b61430a39 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-stop-contract-test-fixture.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, vi } from 'vitest' import type { AgentStatusStructuredSessionSubject } from '../../../../../shared/agent-status/contracts/agent-status-subject' -import { AgentHookServer } from '../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { runClaudeControl } from '../../../../claude/claude-agent-sdk-control-requests' import { ClaudeStructuredSessionAdapter } from '../../../../claude/structured/claude-structured-session-adapter' import type { ClaudeStructuredSessionEvent } from '../../../../claude/structured/claude-structured-session-event' diff --git a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts b/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts index 4411c7a9902..1bb9432b0ab 100644 --- a/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts +++ b/src/main/native-chat/agent-session-wire/observations/testing/structured-agent-session-status-reentry.test.ts @@ -7,7 +7,7 @@ import type { AgentSessionExecutionLocation } from '../../../../../shared/agent- import type { AgentSessionHandleProvider } from '../../../../../shared/agent-session/lifecycle/agent-session-provider-handle' import type { AgentSessionJournal } from '../../../agent-session-journal/journal-store' import { createTrackedJournalOpener } from '../../../agent-session-journal/store-lifecycle/journal-host-database-test-support' -import { AgentHookServer } from '../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { indexedStatusFeedSession } from './structured-agent-session-status-feed-test-session' import { StructuredAgentSessionStatusFeed } from '../structured-agent-session-status-feed' diff --git a/src/main/native-chat/native-chat-open-wake.ts b/src/main/native-chat/native-chat-open-wake.ts index 8d6da959eba..ad8367aa90c 100644 --- a/src/main/native-chat/native-chat-open-wake.ts +++ b/src/main/native-chat/native-chat-open-wake.ts @@ -11,7 +11,7 @@ import { } from '../wsl/filesystem/wsl-unc-access-gate' import { wslGatedAccess } from './wsl-transcript-fs-access' import { WSL_TRANSCRIPT_RUNNING_LEASE_MS } from './wsl-transcript-running-admission' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { nativeChatTranscriptPathOnExecutionHost } from './ssh-transcript-path' type HookRow = Pick diff --git a/src/main/opencode/opencode-pty-launch.ts b/src/main/opencode/opencode-pty-launch.ts index 310c845749e..3a7b41df3a1 100644 --- a/src/main/opencode/opencode-pty-launch.ts +++ b/src/main/opencode/opencode-pty-launch.ts @@ -1,7 +1,7 @@ import { addWslEnvKeys } from '../../shared/wsl-env' import type { TuiAgent } from '../../shared/agent-launch/catalog/tui-agent' import { randomUUID, createHash } from 'node:crypto' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { tokenizeStartupCommand, type AgentStartupShell diff --git a/src/main/opencode/opencode-startup-prompt-owner.test.ts b/src/main/opencode/opencode-startup-prompt-owner.test.ts index 89d2035abc8..110175fb087 100644 --- a/src/main/opencode/opencode-startup-prompt-owner.test.ts +++ b/src/main/opencode/opencode-startup-prompt-owner.test.ts @@ -13,7 +13,7 @@ const ownership = vi.hoisted(() => ({ ptyOwnership: new Map(), ptyIncarnationById: new Map() })) -vi.mock('../agent-hooks/server', () => ({ +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { setStartupPromptClaimListener: (claim: typeof control.claim, clear: () => void) => { control.claim = claim diff --git a/src/main/opencode/opencode-startup-prompt-owner.ts b/src/main/opencode/opencode-startup-prompt-owner.ts index e7b3ed5ab40..7e44fc54981 100644 --- a/src/main/opencode/opencode-startup-prompt-owner.ts +++ b/src/main/opencode/opencode-startup-prompt-owner.ts @@ -1,5 +1,5 @@ import type { PtySpawnOutcome } from '../ipc/pty/spawn-outcome' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { IPtyProvider, PtySpawnResult } from '../providers/pty-provider-contract' import { ptyIncarnationById, ptyOwnership } from '../ipc/pty/provider/ownership-state' diff --git a/src/main/opencode/opencode-status-plugin-startup-refresh.ts b/src/main/opencode/opencode-status-plugin-startup-refresh.ts index 99978ecf045..7aad30f65a6 100644 --- a/src/main/opencode/opencode-status-plugin-startup-refresh.ts +++ b/src/main/opencode/opencode-status-plugin-startup-refresh.ts @@ -1,5 +1,5 @@ import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import type { ManagedHookDetectionSettings } from '../agent-hooks/managed-hook-detection-commands' +import type { ManagedHookDetectionSettings } from '../agent-hooks/installation/managed-hook-detection-commands' import { openCode2HookService, openCodeHookService } from './hook-service' // Refresh running OpenCode 2 services on upgrade without waiting for a pane to rewrite the plugin. diff --git a/src/main/opencode/opencode-wsl-probe-environment.test.ts b/src/main/opencode/opencode-wsl-probe-environment.test.ts index 77432f130c0..98ee5004b55 100644 --- a/src/main/opencode/opencode-wsl-probe-environment.test.ts +++ b/src/main/opencode/opencode-wsl-probe-environment.test.ts @@ -7,7 +7,9 @@ vi.mock('@orca/process-host', () => ({ runProcess: run })) vi.mock('../wsl/execution/wsl-executable-path', () => ({ resolveWslExecutablePath: () => 'wsl.exe' })) -vi.mock('../agent-hooks/server', () => ({ agentHookServer: { endpointFilePath: null } })) +vi.mock('../agent-hooks/server/agent-hook-server', () => ({ + agentHookServer: { endpointFilePath: null } +})) beforeEach(() => { run.mockReset().mockResolvedValue({ code: 0, stdout: '2.0.16', timedOut: false }) diff --git a/src/main/orcad/orcad-daemon-teardown-fixture.ts b/src/main/orcad/orcad-daemon-teardown-fixture.ts index 5b19ca45a05..bbd400bf7dc 100644 --- a/src/main/orcad/orcad-daemon-teardown-fixture.ts +++ b/src/main/orcad/orcad-daemon-teardown-fixture.ts @@ -9,7 +9,7 @@ import { type ProcessTableIndexOf } from '../../shared/process-table-index' import { removeTree } from '../../shared/windows-transient-lock-removal' -import { parseLinuxStartTicks } from '../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' import { DaemonEndpointOwnershipError } from '../daemon/launch/daemon-endpoint-adoption' import { parseLinuxProcessState } from '../daemon/endpoint/identity/daemon-incarnation-evidence' import { readDaemonPidRecord } from '../daemon/endpoint/identity/daemon-endpoint-incarnation' diff --git a/src/main/orcad/orcad-entry.ts b/src/main/orcad/orcad-entry.ts index 9a04cfa9093..b305803b629 100644 --- a/src/main/orcad/orcad-entry.ts +++ b/src/main/orcad/orcad-entry.ts @@ -90,11 +90,11 @@ async function startOrcadRuntime( const { resolveDaemonSessionScrollbackRows } = await import('../daemon/sessions/daemon-session-scrollback-window') const { collectOrcadHealth } = await import('./orcad-health') - const { agentHookServer } = await import('../agent-hooks/server') - await import('../agent-hooks/managed-agent-hook-controls') - const { agentHookRuntimeDeps } = await import('../agent-hooks/agent-hook-runtime-deps') + const { agentHookServer } = await import('../agent-hooks/server/agent-hook-server') + await import('../agent-hooks/installation/managed-agent-hook-controls') + const { agentHookRuntimeDeps } = await import('../agent-hooks/runtime/agent-hook-runtime-deps') const { installHookStatusSessionTabsRepublish } = - await import('../agent-hooks/hook-status-session-tabs-republish') + await import('../agent-hooks/runtime/hook-status-session-tabs-republish') const { startOrcadAgentHookServer, startOrcadManagedAgentHooks } = await import('./orcad-managed-agent-hooks') const { AgentStatusObservedPaneIdentities, AgentStatusObservedPaneIdentityCapture } = diff --git a/src/main/orcad/orcad-managed-agent-hooks.ts b/src/main/orcad/orcad-managed-agent-hooks.ts index eb88b9f2097..86ddef5b14f 100644 --- a/src/main/orcad/orcad-managed-agent-hooks.ts +++ b/src/main/orcad/orcad-managed-agent-hooks.ts @@ -1,18 +1,18 @@ import { getClaudeAgentViewService } from '../claude/agent-view/agent-view-service' import { getAppEnvironment } from '../../shared/app-environment' import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' -import { adoptLoginShellAgentHomes } from '../agent-hooks/agent-home-login-shell' -import { hydrateAgentCliShellPath } from '../agent-hooks/local-agent-cli-presence' +import { adoptLoginShellAgentHomes } from '../agent-hooks/installation/agent-home-login-shell' +import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { reconcileStartupManagedAgentHooks } from '../agent-hooks/managed-agent-hook-startup' +import { reconcileStartupManagedAgentHooks } from '../agent-hooks/installation/managed-agent-hook-startup' import { refreshInstalledOpenCodeStatusPlugins } from '../opencode/opencode-status-plugin-startup-refresh' import type { ProfilePreferences } from '../persistence/loading-store/profile-preferences' import type { OrcadRuntimeCleanup } from './orcad-runtime-lifetime' -import type { AgentHookServer } from '../agent-hooks/server' -import { installLocalHookRootEvidence } from '../agent-hooks/local-hook-root-evidence' +import type { AgentHookServer } from '../agent-hooks/server/agent-hook-server' +import { installLocalHookRootEvidence } from '../agent-hooks/observations/local-hook-root-evidence' /** SSH and WSL-host panes run beside this host, so it proves which agent owns each pane, from the * first record its startup replay reads. */ diff --git a/src/main/orcad/orcad-process-start-time.ts b/src/main/orcad/orcad-process-start-time.ts index ac0c91d957e..555ace95778 100644 --- a/src/main/orcad/orcad-process-start-time.ts +++ b/src/main/orcad/orcad-process-start-time.ts @@ -1,6 +1,6 @@ // Linux ticks/boot ID avoid drifting wall time; Windows uses kernel creation time. Unknown never proves exit. import { readFileSync, statSync } from 'node:fs' -import { parseLinuxStartTicks } from '../agent-hooks/managed-hook-owner-identity' +import { parseLinuxStartTicks } from '../agent-hooks/installation/locking/managed-hook-owner-identity' import { getProcessStartedAtMs, START_TIME_TOLERANCE_MS, diff --git a/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts b/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts index 2a0a8bd8ff7..1122b932b38 100644 --- a/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts +++ b/src/main/persistence/loading-store/profile-state-caller-cancellation.spec.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server' -import { clearMigrationUnsupportedPty } from '../../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' +import { clearMigrationUnsupportedPty } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { createWorkerMaintenanceFixture, maintenanceBarrier diff --git a/src/main/persistence/loading-store/store.ts b/src/main/persistence/loading-store/store.ts index 595f9b0b0fc..0deffce5565 100644 --- a/src/main/persistence/loading-store/store.ts +++ b/src/main/persistence/loading-store/store.ts @@ -2,8 +2,8 @@ import { dirname } from 'node:path' import { setMigrationUnsupportedPty, setMigrationUnsupportedPtyPersistenceListener -} from '../../agent-hooks/migration-unsupported-pty-state' -import { agentHookServer } from '../../agent-hooks/server' +} from '../../agent-hooks/observations/migration-unsupported-pty-state' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { ActiveViewPreference } from '../preferences/active-view-preference' import { registerPersistedPaneKeyAlias } from '../restoring-sessions/pane-alias-normalization' import { normalizePersistedPaneIdentityState } from '../restoring-sessions/workspace-pane-normalization' diff --git a/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts b/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts index 578a8a2f798..dd3938763d2 100644 --- a/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts +++ b/src/main/persistence/loading-store/workspace-session-snapshot-publication.ts @@ -2,7 +2,7 @@ import type { PersistedState } from '../../../shared/persisted-state-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import { sanitizeWorkspaceSessionTerminalRetirements } from '../../runtime/terminal/surface/mobile-session-terminal-persistence-retirement' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' -import { setMigrationUnsupportedPty } from '../../agent-hooks/migration-unsupported-pty-state' +import { setMigrationUnsupportedPty } from '../../agent-hooks/observations/migration-unsupported-pty-state' import { pruneLocalTerminalScrollbackBuffers } from '../../../shared/workspace-session/workspace-session-terminal-buffers' import { pruneWorkspaceSessionBrowserHistory } from '../../../shared/workspace-session/workspace-session-browser-history' import { migrateWorkspaceSessionTerminalScrollbackSnapshots } from '../../pty/scrollback/terminal-scrollback-snapshots' diff --git a/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts b/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts index 7fe3e1e1dbd..0f95c5a5574 100644 --- a/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts +++ b/src/main/persistence/moving-wsl-projects/wsl-move-gate-stub-agent-hooks.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import { collectWslMoveGateInputs, type WslMoveGateFactSources } from './wsl-move-gate-facts' import { assessWslMoveTerminals } from './wsl-move-terminal-gate' diff --git a/src/main/persistence/persistence-loading-store-extraction.test.ts b/src/main/persistence/persistence-loading-store-extraction.test.ts index 1a3ffe08b47..c0a3094804d 100644 --- a/src/main/persistence/persistence-loading-store-extraction.test.ts +++ b/src/main/persistence/persistence-loading-store-extraction.test.ts @@ -107,7 +107,7 @@ describe('loading Store extraction seams', () => { const first = await createStore() const { Store } = await import('./loading-store/store') const { setMigrationUnsupportedPty } = - await import('../agent-hooks/migration-unsupported-pty-state') + await import('../agent-hooks/observations/migration-unsupported-pty-state') const secondDataFile = join(testState.dir, 'second-profile', 'orca-data.json') const second = createSqliteTestStore(Store, { dataFile: secondDataFile }) diff --git a/src/main/persistence/restoring-sessions/pane-alias-normalization.ts b/src/main/persistence/restoring-sessions/pane-alias-normalization.ts index b3648d34b41..1e4ba6c77e4 100644 --- a/src/main/persistence/restoring-sessions/pane-alias-normalization.ts +++ b/src/main/persistence/restoring-sessions/pane-alias-normalization.ts @@ -6,7 +6,7 @@ import { parseLegacyNumericPaneKey, parsePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' export function legacyMigrationUnsupportedRowsToAliasEntries( entries: MigrationUnsupportedPtyEntry[] diff --git a/src/main/persistence/restoring-sessions/workspace-pane-normalization-index.test.ts b/src/main/persistence/restoring-sessions/workspace-pane-normalization-index.test.ts index 26b7df03e52..99092636ab5 100644 --- a/src/main/persistence/restoring-sessions/workspace-pane-normalization-index.test.ts +++ b/src/main/persistence/restoring-sessions/workspace-pane-normalization-index.test.ts @@ -10,7 +10,7 @@ const { registerPaneKeyAliasMock } = vi.hoisted(() => ({ registerPaneKeyAliasMock: vi.fn() })) -vi.mock('../../agent-hooks/server', () => ({ +vi.mock('../../agent-hooks/server/agent-hook-server', () => ({ agentHookServer: { registerPaneKeyAlias: registerPaneKeyAliasMock } diff --git a/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts b/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts index 74dee65d128..211ad36c315 100644 --- a/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts +++ b/src/main/persistence/restoring-sessions/workspace-pane-normalization.ts @@ -2,7 +2,7 @@ import type { LegacyPaneKeyAliasEntry, PersistedState } from '../../../shared/pe import type { TerminalLayoutSnapshot } from '../../../shared/workspace-layout/terminal-tab-types' import type { WorkspaceSessionState } from '../../../shared/workspace-session/workspace-session-state-types' import type { MigrationUnsupportedPtyEntry } from '../../../shared/agent-status/contracts/agent-status-ipc-payload' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { LOCAL_EXECUTION_HOST_ID, toSshExecutionHostId, diff --git a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts b/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts index 9f85ce204c2..d56ff5ea2d6 100644 --- a/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts +++ b/src/main/persistence/terminal-topology/duplicate-pty-pane-repair.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../runtime/orca-runtime' import { repairDuplicatePtyPanesOnStart } from '../../runtime/terminal/identity/moved-pane-owner-rekey' import { getDefaultWorkspaceSession } from '../../../shared/constants' diff --git a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts b/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts index b97c7b6cf11..5d7ad4d96be 100644 --- a/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts +++ b/src/main/persistence/terminal-topology/persistence-pane-alias-selective-saves.test.ts @@ -3,11 +3,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { clearMigrationUnsupportedPty, setMigrationUnsupportedPtyPersistenceListener -} from '../../agent-hooks/migration-unsupported-pty-state' +} from '../../agent-hooks/observations/migration-unsupported-pty-state' import { StateSerializationSecretHandlingOperations } from '../loading-store/state-serialization-secret-handling' import { openProfileStateDatabaseReadOnly } from '../profile-state/profile-state-database' import { profileStateDatabaseFile } from '../../../shared/profile-state-storage-paths' diff --git a/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts b/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts index 60230392d15..5e53a8e125a 100644 --- a/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts +++ b/src/main/persistence/terminal-topology/persistence-pane-identity-migration.test.ts @@ -10,7 +10,7 @@ import { rmSync, mkdtempSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import { TEST_LEAF_1, TEST_LEAF_2 } from '../persistence-session-fixtures' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ @@ -87,7 +87,7 @@ describe('Store', () => { }) await createStore() - const { agentHookServer } = await import('../../agent-hooks/server') + const { agentHookServer } = await import('../../agent-hooks/server/agent-hook-server') agentHookServer.ingestTerminalStatus({ paneKey: physicalPaneKey, tabId: 'tab-source', diff --git a/src/main/plugins/hooks/plugin-hook-participants.ts b/src/main/plugins/hooks/plugin-hook-participants.ts index d54a186fdd5..de4c50a6981 100644 --- a/src/main/plugins/hooks/plugin-hook-participants.ts +++ b/src/main/plugins/hooks/plugin-hook-participants.ts @@ -8,7 +8,7 @@ import { } from '../../../shared/plugins/workers/plugin-hook-chain' import { setPluginHookRunner, type PluginHookRunner } from './plugin-hook-dispatch' import type { PluginService } from '../plugin-service' -import { setAgentToolHookTerminalResolver } from '../../agent-hooks/agent-tool-call-reader' +import { setAgentToolHookTerminalResolver } from '../../agent-hooks/tool-events/agent-tool-call-reader' import type { PluginWorkerHandle } from '../workers/plugin-host-process' import { PLUGIN_WORKER_READY_TIMEOUT_MS } from '../../../shared/plugins/workers/plugin-host-protocol' import { pluginApprovedRevision } from '../workers/plugin-resident-worker' diff --git a/src/main/qoder/real-cli.test.ts b/src/main/qoder/real-cli.test.ts index f605e5e1ac4..15f0af89e5a 100644 --- a/src/main/qoder/real-cli.test.ts +++ b/src/main/qoder/real-cli.test.ts @@ -26,7 +26,7 @@ vi.mock('node:os', async (importOriginal) => { vi.mock('electron', () => ({ app: { getPath: () => sandbox.home } })) import { qoderHookService } from './hook-service' import { markQoderWorkspaceTrusted } from './workspace-trust' -import { AgentHookServer } from '../agent-hooks/server' +import { AgentHookServer } from '../agent-hooks/server/agent-hook-server' it.skipIf(process.env.ORCA_REAL_QODER_CLI_TEST !== '1')( 'generates and resumes a real task through managed hooks', diff --git a/src/main/qoder/workspace-trust.ts b/src/main/qoder/workspace-trust.ts index d452eb87dc0..d27233e2dd3 100644 --- a/src/main/qoder/workspace-trust.ts +++ b/src/main/qoder/workspace-trust.ts @@ -1,6 +1,10 @@ import { realpathSync } from 'node:fs' import { join } from 'node:path' -import { isPlainObject, readHooksJson, writeHooksJson } from '../agent-hooks/installer-utils' +import { + isPlainObject, + readHooksJson +} from '../agent-hooks/installation/configuration/hooks-json-read' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' // Qoder 1.1.64 writes this exact shape after accepting its folder-trust prompt. export function withQoderTrustedWorkspace( diff --git a/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts b/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts index 3e1e0df66fe..1d3c69f9dcb 100644 --- a/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts +++ b/src/main/runtime/agent-session/lifecycle/structured-codex-child-work-runtime.test.ts @@ -20,7 +20,7 @@ import { import '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import '../../orca-runtime-tests/scripted-codex-transport.test-fixture' -import { AgentHookServer } from '../../../agent-hooks/server' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { makeStructuredAgentStatusSubject } from '../../../../shared/agent-status/contracts/agent-status-subject' diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts index cb32152823f..f4082664bd6 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.test.ts @@ -24,7 +24,7 @@ vi.mock('../../../text-generation/commit-message-text-generation', async (import const actual = await importOriginal() return { ...actual, generateConversationNameFromContext: mocks.generate } }) -vi.mock('../../../agent-hooks/first-work-generation-target', () => ({ +vi.mock('../../../agent-hooks/first-work/first-work-generation-target', () => ({ resolveGenerationTarget: mocks.target })) vi.mock('../../../native-chat/agent-session-wire/host/structured-agent-session-registry', () => ({ diff --git a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts index 3994d985617..8a1e7918a54 100644 --- a/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts +++ b/src/main/runtime/agent-session/naming/structured-chat-naming-runtime.ts @@ -21,7 +21,7 @@ import { generateConversationNameFromContext, resolveTextGenerationParams } from '../../../text-generation/commit-message-text-generation' -import { resolveGenerationTarget } from '../../../agent-hooks/first-work-generation-target' +import { resolveGenerationTarget } from '../../../agent-hooks/first-work/first-work-generation-target' type StructuredChatNamingRuntime = { resolveWorkspace: ( diff --git a/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts b/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts index 11cd7840f1b..b95c20424a3 100644 --- a/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts +++ b/src/main/runtime/agent-session/records/agent-session-saved-roster.test-support.ts @@ -1,6 +1,6 @@ import { vi, type Mock, type MockInstance } from 'vitest' -import { AgentHookServer } from '../../../agent-hooks/server' -import { agentHookRuntimeDeps } from '../../../agent-hooks/agent-hook-runtime-deps' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { agentHookRuntimeDeps } from '../../../agent-hooks/runtime/agent-hook-runtime-deps' import { AgentStatusObservedPaneIdentities } from '../../terminal/identity/agent-status-observed-pane-identity' import { StructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/host/structured-agent-session-host' import { hostTestState } from '../../../native-chat/agent-session-wire/host/testing/structured-agent-session-host-test-harness' diff --git a/src/main/runtime/agent-session/structured-child-records-switch.test.ts b/src/main/runtime/agent-session/structured-child-records-switch.test.ts index 3563c3af9bc..09a232c2a74 100644 --- a/src/main/runtime/agent-session/structured-child-records-switch.test.ts +++ b/src/main/runtime/agent-session/structured-child-records-switch.test.ts @@ -14,7 +14,7 @@ import type { } from '../../codex/app-server/codex-app-server-connection-types' import type { openCodexAppServerConnection } from '../../codex/app-server/codex-app-server-connection' import { collectRuntimeWorktreeAgentSources } from '../workspaces/process-listing/runtime-worktree-agent-sources' -import { AgentHookServer, _internals } from '../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../agent-hooks/server/agent-hook-server' import { computeAgentSessionPayloadFingerprint } from '../../../shared/agent-session/lifecycle/agent-session-mutation-envelope' import { HOST_TEST_SESSION as SESSION, diff --git a/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts b/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts index 48f601a21ff..df45dff0da5 100644 --- a/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts +++ b/src/main/runtime/client/settings/runtime-client-agent-launch-rollback.test.ts @@ -21,7 +21,7 @@ vi.mock('../../../ssh/config/ssh-config-parser', () => ({ vi.mock('../../../claude/agent-view/agent-view-service', () => ({ getClaudeAgentViewService: () => ({ reconcile: async () => {} }) })) -vi.mock('../../../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: vi.fn(async () => {}) })) diff --git a/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts b/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts index 183955abe23..8fa66df5038 100644 --- a/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts +++ b/src/main/runtime/client/settings/runtime-client-agent-launch-settings-durability.test.ts @@ -17,7 +17,7 @@ vi.mock('../../../ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) -vi.mock('../../../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: hooks.apply })) void Object.fromEntries(Object.keys(tuiAgentPermissions.YOLO_TUI_AGENT_ARGS).map((id) => [id, ''])) diff --git a/src/main/runtime/client/settings/runtime-client-settings.ts b/src/main/runtime/client/settings/runtime-client-settings.ts index 6df23705be3..16b1030d13a 100644 --- a/src/main/runtime/client/settings/runtime-client-settings.ts +++ b/src/main/runtime/client/settings/runtime-client-settings.ts @@ -20,8 +20,8 @@ import { getHostDisplayLabelOverrides } from '../../../../shared/host-setting-ov import { nativeChatQueueFollowUps } from '../../../../shared/native-chat/input/native-chat-follow-up-behavior' import { nativeChatShowsCiResultLines } from '../../../../shared/native-chat/native-chat-appearance-settings' import type { TerminalQuickCommand } from '../../../../shared/terminal/quick-commands/terminal-quick-command-types' -import { recordManagedHookInstallFailure } from '../../../agent-hooks/install-telemetry' -import { applyAgentStatusHooksEnabled } from '../../../agent-hooks/managed-agent-hook-controls' +import { recordManagedHookInstallFailure } from '../../../agent-hooks/installation/install-telemetry' +import { applyAgentStatusHooksEnabled } from '../../../agent-hooks/installation/managed-agent-hook-controls' import { isWslHostOrcadProcess } from '../../../ipc/wsl-guest-windows-drive-path' import { isAgentStatusHooksEnabledForAgent } from '../../../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import type { RuntimeStore } from '../../construction/runtime-store-contract' diff --git a/src/main/runtime/construction/orca-runtime-agent-transitions.ts b/src/main/runtime/construction/orca-runtime-agent-transitions.ts index 76a1c89a1bf..bf809fb30f7 100644 --- a/src/main/runtime/construction/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/construction/orca-runtime-agent-transitions.ts @@ -1,5 +1,5 @@ import { watchMovedWorkerResumeSessions } from '../rpc/methods/orchestration/worker/worker-resume-session-capture' -import { AgentTransitionDetector } from '../../agent-hooks/agent-transition-detector' +import { AgentTransitionDetector } from '../../agent-hooks/observations/agent-transition-detector' import type { ConnectorCloud } from '../../connector-cloud/connector-cloud' import type { ExternalConversationSeam } from '../../external-conversations/external-conversation-seam' import { installExternalConversations } from '../../external-conversations/external-conversations-install' diff --git a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts index e2543fea2fa..dfd87d389f6 100644 --- a/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts +++ b/src/main/runtime/orca-runtime-test-mocks/setup.spec.ts @@ -272,7 +272,7 @@ vi.mock('../../preflight/agent-detection', () => ({ detectInstalledAgentsWithShellPathHydration: detectInstalledAgentsWithShellPathHydrationMock })) -vi.mock('../../agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock })) diff --git a/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts index 5c4c9cff6fe..e1af126a9aa 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-ps-agent-wait.spec.ts @@ -3,7 +3,7 @@ import { makePaneKey } from '../../../shared/workspace-layout/stable-pane-id' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { TEST_WORKTREE_ID, TEST_WORKTREE_PATH, store } from './orca-runtime-test-fixtures.spec' -import { AgentHookServer, _internals } from '../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../agent-hooks/server/agent-hook-server' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) diff --git a/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts b/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts index d7da23283b4..b438293f2a8 100644 --- a/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts +++ b/src/main/runtime/orca-runtime-tests/worktree-ps-structured-host.spec.ts @@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import './runtime-test-module-registration.spec' import { OrcaRuntimeService } from '../orca-runtime' import { TEST_WORKTREE_ID, store } from './orca-runtime-test-fixtures.spec' -import { AgentHookServer, _internals } from '../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../agent-hooks/server/agent-hook-server' vi.mock('../../telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../telemetry/cohort-classifier', () => ({ diff --git a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts index c6c9eee33b8..c0e79e71901 100644 --- a/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts +++ b/src/main/runtime/orchestration/mailbox/terminal-pointer/orchestration-codex-real-pty.integration.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import * as pty from 'node-pty' import { expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { getManagedScript } from '../../../../codex/hooks/definitions/codex-hook-script' import { getSyntheticAgentTerminalTitle } from '../../../../../shared/agent-status/title/synthetic-agent-title' import { extractAllOscTitles } from '../../../../../shared/agent-status/title/osc-title-extraction' diff --git a/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts b/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts index a028dffdac2..e84bf3599bf 100644 --- a/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts +++ b/src/main/runtime/orchestration/terminal-authority/opencode-finished-session-authority.test.ts @@ -12,7 +12,7 @@ import '../db/dispatch-row-writer' import '../db/attempt-outcome-projection' import { createRootDispatch } from '../db/root-dispatch-test-fixture' import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts' -import { AgentHookServer } from '../../../agent-hooks/server' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../../orca-runtime' import { makeStore } from '../../rpc/server/runtime-rpc-worktree-store-fixtures' import { spawnedPtyEnv } from '../../terminal/launch/spawned-pty-env-fixtures' diff --git a/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts b/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts index d927830bfe2..e67a0e42c38 100644 --- a/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts +++ b/src/main/runtime/orchestration/terminal-authority/release/worker-auto-release-activity.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../../agent-hooks/observations/agent-transition-detector' import type { AgentPhase } from '../../../../../shared/agent-status/lifecycle/agent-transitions' import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire' import { resolveStructuredWorkerIdentityForSession } from '../structured-sessions/structured-worker-authority' diff --git a/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts b/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts index fcfa7ce292a..91467c30a54 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/terminal-worker-turn-stops.ts @@ -1,4 +1,4 @@ -import type { AgentPaneChange } from '../../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../../agent-hooks/observations/agent-transition-detector' import { agentVerdictDisplayMark } from '../../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' import { hookRowAgentPhase } from '../../../../../shared/agent-status/lifecycle/agent-transitions' diff --git a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts index 97e870f9d36..eaf3299653e 100644 --- a/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts +++ b/src/main/runtime/orchestration/workers/turn-stops/worker-turn-stops.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -import type { AgentPaneChange } from '../../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../../agent-hooks/observations/agent-transition-detector' import type { AgentStatusIpcPayload } from '../../../../../shared/agent-status/contracts/agent-status-ipc-payload' import type { AgentSessionTurnCompletionEvent } from '../../../../../shared/agent-session/view/agent-session-turn-completion-wire' import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' diff --git a/src/main/runtime/push/notifications/terminal-agent-phone-push.ts b/src/main/runtime/push/notifications/terminal-agent-phone-push.ts index a1757d35ee7..26dc92a63be 100644 --- a/src/main/runtime/push/notifications/terminal-agent-phone-push.ts +++ b/src/main/runtime/push/notifications/terminal-agent-phone-push.ts @@ -1,6 +1,6 @@ // Push hook-agent finish/input alerts from windowless execution hosts using desktop rules. A window already pushes these phones; the phone suppresses its own visible chat. import { getConnectionExecutionHostId } from '../../../../shared/execution-host' -import type { AgentPaneChange } from '../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../agent-hooks/observations/agent-transition-detector' import { agentMainAgentVerdict } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import { buildAgentNotificationId } from '../../../../shared/agent-notification-id' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/runtime/push/notifications/terminal-agent-turn-news.ts b/src/main/runtime/push/notifications/terminal-agent-turn-news.ts index fb0a619c04c..f436af11266 100644 --- a/src/main/runtime/push/notifications/terminal-agent-turn-news.ts +++ b/src/main/runtime/push/notifications/terminal-agent-turn-news.ts @@ -1,5 +1,5 @@ // Share desktop completion/input timing and hook rows; phone/connector listeners choose wording and transport. -import type { AgentPaneChange } from '../../../agent-hooks/agent-transition-detector' +import type { AgentPaneChange } from '../../../agent-hooks/observations/agent-transition-detector' import { mainAgentTurnInterrupted } from '../../../../shared/agent-status/lifecycle/agent-lead-status-fold' import { agentTurnEndedOnPurpose } from '../../../../shared/agent-status/lifecycle/agent-main-agent-verdict' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload' diff --git a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts index 7231e3e6e85..ae80a2162bc 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/fleet-status-observed-identity.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import type { AgentStatusOrchestrationContext } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import { AgentHookServer } from '../../../../../agent-hooks/server' +import { AgentHookServer } from '../../../../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../../../orca-runtime' diff --git a/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts b/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts index 2841c1aa37e..76b1dad635f 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-claude-agent-view-method.ts @@ -5,7 +5,7 @@ import { import { defineMethod, defineStreamingMethod } from '../../core' import { bindStructuredAgentSessionStream } from '../structured-sessions/subscriptions/structured-agent-session-status-stream' import { TerminalViewClaudeAgent } from '../../../../../shared/rpc-contract/terminal-unary-params' -import { agentHookServer } from '../../../../agent-hooks/server' +import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import { assertTerminalAgentSendable } from '../../terminal-agent-send-guard' import { assertTerminalSendExactPtyBinding, diff --git a/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts b/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts index c8c07ee0e88..001bfb60da3 100644 --- a/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts +++ b/src/main/runtime/rpc/methods/terminal/terminal-send-question-answered.ts @@ -1,5 +1,5 @@ import type { z } from 'zod' -import { agentHookServer } from '../../../../agent-hooks/server' +import { agentHookServer } from '../../../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../../../orca-runtime' import type { TerminalSend } from '../../../../../shared/rpc-contract/terminal-unary-params' import { diff --git a/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts b/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts index edeb1145994..7d09650965e 100644 --- a/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts +++ b/src/main/runtime/rpc/orchestration-legacy-takeover-current-authority.test.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' import { RpcDispatcher } from './dispatcher' import { diff --git a/src/main/runtime/rpc/terminal-claude-agent-view.test.ts b/src/main/runtime/rpc/terminal-claude-agent-view.test.ts index 6e7269f1f18..c6e45cfedcb 100644 --- a/src/main/runtime/rpc/terminal-claude-agent-view.test.ts +++ b/src/main/runtime/rpc/terminal-claude-agent-view.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { agentHookServer } from '../../agent-hooks/server' +import { agentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { OrcaRuntimeService } from '../orca-runtime' import { RpcDispatcher } from './dispatcher' import { createTerminalInputReservation } from '../terminal/input/terminal-input-admission' diff --git a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts index 07b47ae9c16..50d798486ab 100644 --- a/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts +++ b/src/main/runtime/session-lifecycle/projection/runtime-mobile-session-projection.ts @@ -13,7 +13,7 @@ import type { } from '../../../../shared/runtime-session-contracts' import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' import { resolveTerminalTabTitle } from '../../../../shared/tab-title-resolution' -import { indexAgentStatusRowsByPaneKey } from '../../../agent-hooks/agent-status-pane-index' +import { indexAgentStatusRowsByPaneKey } from '../../../agent-hooks/runtime/agent-status-pane-index' import { demoteRuntimeMobileAgentStatus, renewRuntimeMobileAgentStatusFromPtyTitle, diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts index 8ec975df0c4..121339898d9 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-sidebar-temporal.ts @@ -28,7 +28,7 @@ import { parseWorktreeHostIdentity } from '../../../shared/worktree/host-qualified-identity' import { anySleepKeyNames } from '../terminal/stop/worktree-terminal-sleep-key' -import { resolveAgentWorkspaceExecutionHostId } from '../../agent-hooks/restored-status-dead-terminal-sweep' +import { resolveAgentWorkspaceExecutionHostId } from '../../agent-hooks/observations/restored-status-dead-terminal-sweep' import { WORKTREE_METADATA_DOMAINS } from '../../persistence/loading-store/worktree-identity-metadata' import { isWslMoveProjectBlocked, diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts index 4f2402ab6b8..747518ed768 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-sort-stamps.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' import { hostWorktreeTarget, diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts b/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts index 10fd38c8891..4eecc2e8cbc 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-windowless-terminal-activity.ts @@ -12,7 +12,7 @@ import { createKeyedTrailingEdgeCoalescer } from '../client/events/keyed-trailin import { agentPaneWorkspace, type AgentPaneWorkspace -} from '../../agent-hooks/agent-transition-detector' +} from '../../agent-hooks/observations/agent-transition-detector' import type { RuntimePtyWorktreeRecord } from '../terminal/records/runtime-terminal-state-records' import { isWslMoveProjectBlocked, diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts index 78863fa974d..e356416d19a 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-activity-facts.test.ts @@ -1,7 +1,7 @@ // Runs on plain Node, as orcad does: the producer and its runtime wiring import no Electron. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { RuntimeMobileSessionTabsSnapshot } from '../../../shared/runtime-session-contracts' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' vi.mock('../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true })) diff --git a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts index 91b5426aafb..5ab5dfe4ee4 100644 --- a/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts +++ b/src/main/runtime/sidebar-inputs/orca-runtime-workspace-unread.test.ts @@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { HEADLESS_RUNTIME_WINDOW_ID } from '../../../shared/runtime-session-contracts' import { folderWorkspaceKey } from '../../../shared/workspace-scope' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { OrcaRuntimeService } from '../orca-runtime' import { RpcDispatcher } from '../rpc/dispatcher' import type { RpcDispatchStreamingOptions } from '../rpc/dispatcher-stream-options' diff --git a/src/main/runtime/sidebar-inputs/sort-stamp-records.ts b/src/main/runtime/sidebar-inputs/sort-stamp-records.ts index b713a119305..b3df494b5f8 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamp-records.ts +++ b/src/main/runtime/sidebar-inputs/sort-stamp-records.ts @@ -1,5 +1,5 @@ import { getRepoRegistrationHostIds } from '../../../shared/repo-host-identity' -import type { AgentPaneWorkspace } from '../../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../../agent-hooks/observations/agent-transition-detector' import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/execution-host' import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id' import type { diff --git a/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts b/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts index a7c1ad2c86a..d6d91090e99 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/sort-stamps-producer.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { AgentStatusStoreView } from './workspace-activity-facts-producer' import '../../../shared/agent-status/contracts/agent-status-subject' @@ -11,7 +11,7 @@ import '../../../shared/sidebar-list/sort-stamps' import type { SmartStampFields } from '../../../shared/sidebar-list/sort-stamps' import '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' import type { AgentTransitionStep } from '../../../shared/agent-status/lifecycle/agent-transitions.test-fixture' -import { AgentTransitionDetector } from '../../agent-hooks/agent-transition-detector' +import { AgentTransitionDetector } from '../../agent-hooks/observations/agent-transition-detector' import '../../../shared/sidebar-list/stamp-order' import { SortStampsProducer, type StoredTierEvidence } from './sort-stamps-producer' import type { SortStampsStore } from './sort-stamp-records' diff --git a/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts b/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts index 79fbc652968..62ac2330c75 100644 --- a/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts +++ b/src/main/runtime/sidebar-inputs/sort-stamps-producer.ts @@ -19,7 +19,7 @@ import { type AgentPaneChange, type AgentPaneWorkspace, type AgentTransitionDetector -} from '../../agent-hooks/agent-transition-detector' +} from '../../agent-hooks/observations/agent-transition-detector' import { listTieredWorkspaces, readSortStamps, diff --git a/src/main/runtime/sidebar-inputs/terminal-use-producer.ts b/src/main/runtime/sidebar-inputs/terminal-use-producer.ts index 120791197ac..91f894f9d0b 100644 --- a/src/main/runtime/sidebar-inputs/terminal-use-producer.ts +++ b/src/main/runtime/sidebar-inputs/terminal-use-producer.ts @@ -3,7 +3,7 @@ import { writeWorkspaceRecord, type WorkspaceRecordStore } from './sort-stamp-records' -import type { AgentPaneWorkspace } from '../../agent-hooks/agent-transition-detector' +import type { AgentPaneWorkspace } from '../../agent-hooks/observations/agent-transition-detector' /** At most one write per workspace per minute; cleanup judges idleness in days. */ export const TERMINAL_USE_THROTTLE_MS = 60_000 diff --git a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts index c396f8b4173..e956f8c0519 100644 --- a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts +++ b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { SidebarClock } from './sidebar-clock' -import { AgentHookServer } from '../../agent-hooks/server' +import { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../shared/agent-status/contracts/agent-status-freshness' import { WorkspaceActivityFactsProducer, diff --git a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts index bf26af4845b..21445f85287 100644 --- a/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts +++ b/src/main/runtime/sidebar-inputs/workspace-activity-facts-producer.ts @@ -17,7 +17,7 @@ import { type WorkspaceActivityFacts, type WorkspaceActivityFactsSnapshot } from '../../../shared/sidebar-list/workspace-activity-facts' -import type { AgentHookServer } from '../../agent-hooks/server' +import type { AgentHookServer } from '../../agent-hooks/server/agent-hook-server' import type { SidebarClock } from './sidebar-clock' export type WorkspaceSurfaceActivity = Omit diff --git a/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts b/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts index 7b8c12b2e50..1d426772c77 100644 --- a/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts +++ b/src/main/runtime/terminal/identity/agent-status-store-wiring.test-fixture.ts @@ -1,6 +1,6 @@ -import { AgentHookServer } from '../../../agent-hooks/server' -import { agentHookRuntimeDeps } from '../../../agent-hooks/agent-hook-runtime-deps' -import { installHookStatusSessionTabsRepublish } from '../../../agent-hooks/hook-status-session-tabs-republish' +import { AgentHookServer } from '../../../agent-hooks/server/agent-hook-server' +import { agentHookRuntimeDeps } from '../../../agent-hooks/runtime/agent-hook-runtime-deps' +import { installHookStatusSessionTabsRepublish } from '../../../agent-hooks/runtime/hook-status-session-tabs-republish' import { AgentStatusObservedPaneIdentities } from './agent-status-observed-pane-identity' type WiredRuntime = { diff --git a/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts b/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts index 23446b903dd..005bad4d89d 100644 --- a/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts +++ b/src/main/runtime/terminal/identity/exported-pane-key-follow.test.ts @@ -2,7 +2,7 @@ // ORCA_PANE_KEY its env exported, so that key's agent status must follow it to the new pane. import { randomUUID } from 'node:crypto' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { PtyProcessInfo } from '../../../providers/pty-process-info' await import('../../orca-runtime-tests/runtime-test-module-registration.spec') diff --git a/src/main/runtime/terminal/identity/exported-pane-key-follow.ts b/src/main/runtime/terminal/identity/exported-pane-key-follow.ts index 2e02d0cf887..7e344a683b9 100644 --- a/src/main/runtime/terminal/identity/exported-pane-key-follow.ts +++ b/src/main/runtime/terminal/identity/exported-pane-key-follow.ts @@ -1,4 +1,4 @@ -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records' type ExportedPaneKeyPty = Pick diff --git a/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts b/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts index 467d33bf8e1..63e4edb4d22 100644 --- a/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts +++ b/src/main/runtime/terminal/identity/moved-pane-owner-rekey.ts @@ -1,4 +1,4 @@ -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' import { forgetFailedAgentLaunches } from '../../../agent-launch/agent-launch-pane-attachment' import type { Store } from '../../../persistence/loading-store/store' import { makePaneKey, parsePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' diff --git a/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts b/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts index a0d528e1bc0..83c47c0c9b0 100644 --- a/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts +++ b/src/main/runtime/terminal/input/terminal-agent-prompt-submit.ts @@ -4,7 +4,7 @@ import type { RuntimeTerminalPromptDelivery, RuntimeTerminalSend } from '../../../../shared/runtime-terminal-send-contract' -import type { AgentTransitionDetector } from '../../../agent-hooks/agent-transition-detector' +import type { AgentTransitionDetector } from '../../../agent-hooks/observations/agent-transition-detector' import { OrcaRuntimeWithWriteTerminalAgentPrompt } from './terminal-agent-prompt' import { AgentPromptPermissionReturnedError, diff --git a/src/main/runtime/terminal/output/terminal-buffer-operations.ts b/src/main/runtime/terminal/output/terminal-buffer-operations.ts index 92a911054a0..102523d2eff 100644 --- a/src/main/runtime/terminal/output/terminal-buffer-operations.ts +++ b/src/main/runtime/terminal/output/terminal-buffer-operations.ts @@ -14,7 +14,7 @@ import { } from './tail/terminal-tail-restore-seed' import { hookLeadTurnState } from '../wait/tui-idle-hook-lane' -import { agentHookServer } from '../../../agent-hooks/server' +import { agentHookServer } from '../../../agent-hooks/server/agent-hook-server' export abstract class OrcaRuntimeWithSerializeMainTerminalBuffer extends OrcaRuntimeWithNotifyRemoteTerminalViewPresenceChanged { protected abstract serializePreferredRestoredTerminalBuffer( diff --git a/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts index 5170a99dd7e..ae8621abbf0 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts @@ -1,4 +1,4 @@ -import type { AgentTransitionDetector } from '../../../agent-hooks/agent-transition-detector' +import type { AgentTransitionDetector } from '../../../agent-hooks/observations/agent-transition-detector' import { readCrewRuntimeInputs, watchCrewRuntimeSources diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts index a6c06f9ec09..25f1ab94ca1 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-agent-rows-verdict.test.ts @@ -14,7 +14,7 @@ import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import type { RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' -import { AgentHookServer, _internals } from '../../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../../agent-hooks/server/agent-hook-server' import { createTrackedJournalOpener } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import type { AgentSessionJournal } from '../../../native-chat/agent-session-journal/journal-store' import { StructuredAgentSessionStatusFeed } from '../../../native-chat/agent-session-wire/observations/structured-agent-session-status-feed' diff --git a/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts b/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts index 11c6eb83b23..2dae613aa8f 100644 --- a/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts +++ b/src/main/runtime/workspaces/process-listing/runtime-worktree-structured-agent-rows-liveness.test.ts @@ -8,7 +8,7 @@ import { StructuredAgentSessionStatusFeed } from '../../../native-chat/agent-ses import { createTrackedJournalOpener } from '../../../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' import type { AgentSessionStatusSummary } from '../../../../shared/agent-session/agent-session-wire' import type { RuntimeWorktreePsSummary } from '../../../../shared/runtime-worktree-contracts' -import { AgentHookServer, _internals } from '../../../agent-hooks/server' +import { AgentHookServer, _internals } from '../../../agent-hooks/server/agent-hook-server' import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' import { createStructuredAgentSessionLogger } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { codexProviderHandle } from '../../../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' diff --git a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts index 6334fb8480e..36045b65990 100644 --- a/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/process-listing/workspace-process-listing.ts @@ -34,8 +34,8 @@ import { } from '../../../native-chat/agent-session-wire/host/structured-agent-session-logger' import { openAgentSessionRecordStoreOnce } from '../../agent-session/records/agent-session-record-store-slot' import type { AgentSessionRecordStore } from '../../agent-session/records/agent-session-record-store' -import { maybeAutoRenameWorkspaceOnFirstStructuredTurn } from '../../../agent-hooks/first-work-structured-session-rename' -import { firstWorkRenameDeps } from '../../../agent-hooks/first-work-rename-runtime' +import { maybeAutoRenameWorkspaceOnFirstStructuredTurn } from '../../../agent-hooks/first-work/first-work-structured-session-rename' +import { firstWorkRenameDeps } from '../../../agent-hooks/first-work/first-work-rename-runtime' import { createStructuredChatNamingHandler } from '../../../native-chat/structured-chat-naming' import { structuredChatNamingDeps } from '../../agent-session/naming/structured-chat-naming-runtime' import { getProfileUserDataPath } from '../../../orca-profiles/profile-storage-paths' diff --git a/src/main/startup/agent-hooks-uninstall-preflight.ts b/src/main/startup/agent-hooks-uninstall-preflight.ts index 30946ae9841..7d9ea337188 100644 --- a/src/main/startup/agent-hooks-uninstall-preflight.ts +++ b/src/main/startup/agent-hooks-uninstall-preflight.ts @@ -54,7 +54,8 @@ export function runAgentHooksUninstallPreflight(argv: readonly string[] = proces } // Loaded only here, so ordinary startup never pays for every agent's hook module. void removeAgentHooksForUninstall(async () => { - const { removeManagedAgentHooks } = await import('../agent-hooks/managed-agent-hook-controls') + const { removeManagedAgentHooks } = + await import('../agent-hooks/installation/managed-agent-hook-controls') return removeManagedAgentHooks() }).then((code) => { clearTimeout(timeout) diff --git a/src/main/startup/branch-rename-hook.ts b/src/main/startup/branch-rename-hook.ts index bb5781a65ea..76e96b1af69 100644 --- a/src/main/startup/branch-rename-hook.ts +++ b/src/main/startup/branch-rename-hook.ts @@ -1,6 +1,6 @@ -import { maybeAutoRenameBranchOnFirstWork } from '../agent-hooks/first-work-branch-rename' -import { firstWorkRenameDeps } from '../agent-hooks/first-work-rename-runtime' -import { agentHookServer } from '../agent-hooks/server' +import { maybeAutoRenameBranchOnFirstWork } from '../agent-hooks/first-work/first-work-branch-rename' +import { firstWorkRenameDeps } from '../agent-hooks/first-work/first-work-rename-runtime' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { mainProcessState as state } from './main-process-state' /** Arms first-work rename from the hook store itself, so headless serve (no window) renames too. */ diff --git a/src/main/startup/main-process-account-services.ts b/src/main/startup/main-process-account-services.ts index 18670a8ffa2..ca19a2eefd5 100644 --- a/src/main/startup/main-process-account-services.ts +++ b/src/main/startup/main-process-account-services.ts @@ -11,7 +11,7 @@ import { readOpenCodeGoApiKey, saveOpenCodeGoApiKey } from '../opencode/opencode-go-api-key-store' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' import { browserManager } from '../browser/browser-manager' import { prewarmStructuredAgentModelCatalogs } from '../runtime/agent-session/model-catalog/structured-agent-model-catalog-wiring' diff --git a/src/main/startup/main-process-observers.ts b/src/main/startup/main-process-observers.ts index 92711003e54..473327c15a0 100644 --- a/src/main/startup/main-process-observers.ts +++ b/src/main/startup/main-process-observers.ts @@ -8,8 +8,8 @@ import { listCapableSharedControlSockets, startDesktopPresenceReporter } from '../notifications/desktop-presence-reporter' -import { agentHookServer } from '../agent-hooks/server' -import { installHookStatusSessionTabsRepublish } from '../agent-hooks/hook-status-session-tabs-republish' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { installHookStatusSessionTabsRepublish } from '../agent-hooks/runtime/hook-status-session-tabs-republish' import { initTelemetry, track } from '../telemetry/client' import { setCodexTrustGrantTelemetry } from '../codex/trust/grants/codex-trust-grant-telemetry' import { initObservability } from '../observability/index' diff --git a/src/main/startup/main-process-plugins.ts b/src/main/startup/main-process-plugins.ts index 624cf2a8c81..3b910fb8800 100644 --- a/src/main/startup/main-process-plugins.ts +++ b/src/main/startup/main-process-plugins.ts @@ -34,7 +34,7 @@ import { isUsablePluginLanguagePack } from '../../shared/plugins/languages/plugi import { rebuildAppMenu } from '../menu/register-app-menu' import { rebuildSystemTrayMenu } from '../tray/system-tray' import { logStartupMilestone } from './startup-diagnostics' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { bindPluginRuntime, createPluginAgentStatusForwarder, diff --git a/src/main/startup/main-process-pty-startup.ts b/src/main/startup/main-process-pty-startup.ts index a569f1389bf..f914308f0c1 100644 --- a/src/main/startup/main-process-pty-startup.ts +++ b/src/main/startup/main-process-pty-startup.ts @@ -25,14 +25,14 @@ import { isAgentStatusHooksEnabled, isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { agentHookServer } from '../agent-hooks/server' -import { createLocalTmuxManagedPtyResolver } from '../agent-hooks/local-tmux-managed-pty' -import { installLocalHookRootEvidence } from '../agent-hooks/local-hook-root-evidence' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { createLocalTmuxManagedPtyResolver } from '../agent-hooks/observations/local-tmux-managed-pty' +import { installLocalHookRootEvidence } from '../agent-hooks/observations/local-hook-root-evidence' import { indexPersistedPaneKeyPtyIds, resolveAgentWorkspaceExecutionHostId, retireRestoredStatusesWithDeadTerminals -} from '../agent-hooks/restored-status-dead-terminal-sweep' +} from '../agent-hooks/observations/restored-status-dead-terminal-sweep' import { startFirstWindowStartupServices } from './first-window-startup-services' import { logStartupMilestone } from './startup-diagnostics' import type { WindowsDesktopStartupServices } from './windows-desktop-shell-path-startup' diff --git a/src/main/startup/main-process-quit-pending-writer.test.ts b/src/main/startup/main-process-quit-pending-writer.test.ts index 4d27a406cf2..8906147723b 100644 --- a/src/main/startup/main-process-quit-pending-writer.test.ts +++ b/src/main/startup/main-process-quit-pending-writer.test.ts @@ -23,9 +23,11 @@ const dependencies: Record> = { }, '../ipc/ssh/ssh-shutdown-drain': { beginSshShutdown }, './main-process-connector-startup': { desktopConnectorCloud: () => null }, - '../agent-hooks/server': { agentHookServer: { stop: stopAgentHookServer } }, - '../agent-hooks/wsl-hook-relay-manager': { wslHookRelayManager: { disposeAll: idle() } }, - '../agent-hooks/managed-agent-hook-controls': { + '../agent-hooks/server/agent-hook-server': { agentHookServer: { stop: stopAgentHookServer } }, + '../agent-hooks/wsl-relay/wsl-hook-relay-manager': { + wslHookRelayManager: { disposeAll: idle() } + }, + '../agent-hooks/installation/managed-agent-hook-controls': { removeManagedAgentHooksAsync: vi.fn(async () => []) }, '../runtime/agent-session/structured-agent-session-runtime': { diff --git a/src/main/startup/main-process-quit-update-veto.test.ts b/src/main/startup/main-process-quit-update-veto.test.ts index 1cc335550b0..21b1f2f336e 100644 --- a/src/main/startup/main-process-quit-update-veto.test.ts +++ b/src/main/startup/main-process-quit-update-veto.test.ts @@ -8,9 +8,9 @@ const dependencyExports: [string, string[]][] = [ ['../ipc/pty/kill-all', ['killAllPty']], ['../daemon/providers/lifecycle/daemon-provider-state', ['disconnectDaemon', 'shutdownDaemon']], ['../ipc/ssh-shutdown-drain', ['beginSshShutdown']], - ['../agent-hooks/server', ['agentHookServer']], - ['../agent-hooks/wsl-hook-relay-manager', ['wslHookRelayManager']], - ['../agent-hooks/managed-agent-hook-controls', ['removeManagedAgentHooksAsync']], + ['../agent-hooks/server/agent-hook-server', ['agentHookServer']], + ['../agent-hooks/wsl-relay/wsl-hook-relay-manager', ['wslHookRelayManager']], + ['../agent-hooks/installation/managed-agent-hook-controls', ['removeManagedAgentHooksAsync']], [ '../runtime/agent-session/structured-agent-session-runtime', ['stopStructuredAgentSessionRuntime'] diff --git a/src/main/startup/main-process-quit.ts b/src/main/startup/main-process-quit.ts index 9c17b61a314..b02449fc599 100644 --- a/src/main/startup/main-process-quit.ts +++ b/src/main/startup/main-process-quit.ts @@ -10,9 +10,9 @@ import { shutdownDaemon } from '../daemon/providers/lifecycle/daemon-provider-state' import { beginSshShutdown } from '../ipc/ssh/ssh-shutdown-drain' -import { agentHookServer } from '../agent-hooks/server' -import { wslHookRelayManager } from '../agent-hooks/wsl-hook-relay-manager' -import { removeManagedAgentHooksAsync } from '../agent-hooks/managed-agent-hook-controls' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { wslHookRelayManager } from '../agent-hooks/wsl-relay/wsl-hook-relay-manager' +import { removeManagedAgentHooksAsync } from '../agent-hooks/installation/managed-agent-hook-controls' import { stopStructuredAgentSessionRuntime } from '../runtime/agent-session/structured-agent-session-runtime' import { setStructuredAgentSessionTeardownTrigger } from '../runtime/agent-session/structured-agent-session-runtime-teardown' import { awaitRuntimeFileWatcherUnsubscribes } from '../runtime/files/watch/file-watcher-leases' diff --git a/src/main/startup/main-process-ready-foundation.ts b/src/main/startup/main-process-ready-foundation.ts index 83c363d4128..523f4b95458 100644 --- a/src/main/startup/main-process-ready-foundation.ts +++ b/src/main/startup/main-process-ready-foundation.ts @@ -29,7 +29,7 @@ import { configureWindowsHostGitEnvironmentReadiness, setDefaultWslDistroOverride } from '../git/runner' -import { wslHookRelayManager } from '../agent-hooks/wsl-hook-relay-manager' +import { wslHookRelayManager } from '../agent-hooks/wsl-relay/wsl-hook-relay-manager' import { applyAppIcon } from '../window/desktop-integration/app-icon' import { shouldSuppressDevEducation, @@ -60,7 +60,7 @@ import { reconcileManagedWslCliRegistrations } from '../cli/wsl-cli-registration-reconciliation' import { createWslCliReconciliationStartupBarrier } from './wsl-cli-reconciliation-startup-barrier' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { isAgentStatusHooksEnabled } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' import { reportProfileStateWriteFailure } from './profile-state-write-failure' import { reportProfileStateSaveDelay } from './profile-state-save-delay' diff --git a/src/main/startup/main-process-ready-identity-write.test.ts b/src/main/startup/main-process-ready-identity-write.test.ts index 945f25eec73..10594e38a3c 100644 --- a/src/main/startup/main-process-ready-identity-write.test.ts +++ b/src/main/startup/main-process-ready-identity-write.test.ts @@ -159,7 +159,7 @@ vi.mock('../git/command-runner/wsl-command-resolution', async (importOriginal) = ...(await importOriginal>()), setDefaultWslDistroOverride: vi.fn() })) -vi.mock('../agent-hooks/wsl-hook-relay-manager', () => ({ +vi.mock('../agent-hooks/wsl-relay/wsl-hook-relay-manager', () => ({ wslHookRelayManager: { setManagedHookSettingsResolver: vi.fn() } })) vi.mock('../window/desktop-integration/app-icon', () => ({ applyAppIcon: vi.fn() })) diff --git a/src/main/startup/main-process-ready-runtime.ts b/src/main/startup/main-process-ready-runtime.ts index a50f1f4a0a9..aebdc22c647 100644 --- a/src/main/startup/main-process-ready-runtime.ts +++ b/src/main/startup/main-process-ready-runtime.ts @@ -16,9 +16,9 @@ import { recordProcessGoneCrash } from './main-window-lifecycle-flags' import { handleGpuChildCrash } from './gpu-lifecycle' import { isGpuFallbackCrashCandidate } from '../crash-reporting/gpu-crash-fallback-decision' import { startCodexHooks } from '../codex/hooks/reconciliation/codex-hook-reconcile' -import { hydrateAgentCliShellPath } from '../agent-hooks/local-agent-cli-presence' +import { hydrateAgentCliShellPath } from '../agent-hooks/installation/local-agent-cli-presence' import { isAgentStatusHooksEnabledForAgent } from '../../shared/agent-hook-listener/configuration/agent-status-hooks-setting' -import { reconcileStartupManagedAgentHooks } from '../agent-hooks/managed-agent-hook-startup' +import { reconcileStartupManagedAgentHooks } from '../agent-hooks/installation/managed-agent-hook-startup' import { shouldInstallManagedHooks } from './configure-process' import { mainProcessState as state } from './main-process-state' import { initializeMainProcessObservers } from './main-process-observers' diff --git a/src/main/startup/main-process-runtime-service.ts b/src/main/startup/main-process-runtime-service.ts index 9dbe36f1e74..c2ce77b048c 100644 --- a/src/main/startup/main-process-runtime-service.ts +++ b/src/main/startup/main-process-runtime-service.ts @@ -10,7 +10,7 @@ import { translateMain } from '../i18n/main-i18n' import { OrcaRuntimeService } from '../runtime/orca-runtime' import { getLocalPtyProvider } from '../ipc/pty/provider/registry' import { clearProviderPtyState } from '../ipc/pty/provider/state-cleanup' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import { toAgentStatusIpcPayload } from '../agent-hooks/server/server-status-identity' import { browserManager } from '../browser/browser-manager' import { browserSessionRegistry } from '../browser/sessions/browser-session-registry' @@ -19,7 +19,7 @@ import { getProfileUserDataPath } from '../orca-profiles/profile-storage-paths' import { codexAiVaultSessionResumePreparation } from '../codex/history/resume/codex-ai-vault-session-resume' import { prepareCodexPinnedLaunchHome } from './codex-session-resume-launch' import { resolveHostCodexSessionSourceHome } from '../codex/history/rollouts/codex-session-source-home' -import { agentHookRuntimeDeps } from '../agent-hooks/agent-hook-runtime-deps' +import { agentHookRuntimeDeps } from '../agent-hooks/runtime/agent-hook-runtime-deps' import { getDaemonProvider } from '../daemon/providers/lifecycle/daemon-provider-state' import type { TerminalSideEffectBatch } from '../../shared/terminal/output/terminal-side-effect-facts' import { resolveTuiAgentLaunchEnv } from '../../shared/agent-launch/choices/tui-agent-launch-defaults' diff --git a/src/main/startup/main-window-agent-status.ts b/src/main/startup/main-window-agent-status.ts index 383bf8a6725..23409edbe1f 100644 --- a/src/main/startup/main-window-agent-status.ts +++ b/src/main/startup/main-window-agent-status.ts @@ -1,6 +1,6 @@ import type { BrowserWindow } from 'electron' -import { agentHookServer } from '../agent-hooks/server' -import { setMigrationUnsupportedPtyListener } from '../agent-hooks/migration-unsupported-pty-state' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' +import { setMigrationUnsupportedPtyListener } from '../agent-hooks/observations/migration-unsupported-pty-state' import { getDashboardPopoutWindow } from '../window/dashboard-popout-window' import { stopSyntheticTitleSpinnerTimer } from './synthetic-title-runtime' import { mainProcessState as state } from './main-process-state' diff --git a/src/main/startup/synthetic-title-runtime.ts b/src/main/startup/synthetic-title-runtime.ts index ae64e518b7b..7c5d24652bb 100644 --- a/src/main/startup/synthetic-title-runtime.ts +++ b/src/main/startup/synthetic-title-runtime.ts @@ -1,5 +1,5 @@ import { registerPaneKeyTeardownListener, getPtyIdForPaneKey } from '../ipc/pty/pane/key-state' -import { agentHookServer } from '../agent-hooks/server' +import { agentHookServer } from '../agent-hooks/server/agent-hook-server' import type { AgentStatusState } from '../../shared/agent-status/contracts/agent-status-types' import { normalizeTerminalTitle } from '../../shared/agent-status/title/agent-title-status' import { diff --git a/src/main/stats/agent-session-transition-recorder.test.ts b/src/main/stats/agent-session-transition-recorder.test.ts index 53df1d4a82c..9dfaeeb3c04 100644 --- a/src/main/stats/agent-session-transition-recorder.test.ts +++ b/src/main/stats/agent-session-transition-recorder.test.ts @@ -1,13 +1,17 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Mock } from 'vitest' -import { AgentSessionTransitionRecorder } from './agent-session-transition-recorder' -import type { AgentSessionSink, AgentSessionStatusEvent } from './agent-session-transition-recorder' +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' + +import { + AgentSessionTransitionRecorder, + type AgentSessionSink, + type AgentSessionStatusEvent +} from './agent-session-transition-recorder' + import { StatsCollector } from './collector' -import { AgentHookServer, _internals } from '../agent-hooks/server' -import { PANE as STORE_PANE } from '../agent-hooks/server.test-fixtures' +import { AgentHookServer, _internals } from '../agent-hooks/server/agent-hook-server' +import { PANE as STORE_PANE } from '../agent-hooks/server/testing/server.test-fixtures' let userDataDir: string diff --git a/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts b/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts index 47e8fcbc805..b7ba94b948e 100644 --- a/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts +++ b/src/main/workspaces/creation/worktree-create-first-work-test-harness.ts @@ -3,12 +3,15 @@ import type { CreateWorktreeArgs } from '../../../shared/worktree/create-types' import type { Worktree } from '../../../shared/worktree/types' import type { WorktreeMeta } from '../../../shared/worktree/meta-types' import { getDefaultSettings } from '../../../shared/constants' -import { firstWorkRenameDeps } from '../../agent-hooks/first-work-rename-runtime' +import { firstWorkRenameDeps } from '../../agent-hooks/first-work/first-work-rename-runtime' import { maybeAutoRenameBranchOnFirstWork, resetFirstWorkBranchRenameState -} from '../../agent-hooks/first-work-branch-rename' -import { gitResponder, workingEvent } from '../../agent-hooks/first-work-branch-rename-test-harness' +} from '../../agent-hooks/first-work/first-work-branch-rename' +import { + gitResponder, + workingEvent +} from '../../agent-hooks/first-work/testing/first-work-branch-rename-test-harness' import { mergeWorktree } from '../../ipc/worktree-metadata-merge' export const typedLabelCreateRequests: Pick< diff --git a/src/main/zcode/hook-config-json.ts b/src/main/zcode/hook-config-json.ts index 1edc0ca679f..28db782e71b 100644 --- a/src/main/zcode/hook-config-json.ts +++ b/src/main/zcode/hook-config-json.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs' import { applyEdits, modify, parse as parseJsonc, type ParseError } from 'jsonc-parser' import { isDefinitiveAbsence } from '../../shared/definitive-filesystem-absence' -import { isPlainObject } from '../agent-hooks/installer-utils' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' import { isZCodeHooksEnabled, readZCodeEventMap, type ZCodeConfig } from './hook-settings' export type ZCodeConfigSource = { diff --git a/src/main/zcode/hook-service.ts b/src/main/zcode/hook-service.ts index 9a18cd37078..39539fa788b 100644 --- a/src/main/zcode/hook-service.ts +++ b/src/main/zcode/hook-service.ts @@ -1,22 +1,18 @@ import type { SFTPWrapper } from 'ssh2' import type { AgentHookInstallStatus } from '../../shared/agent-hook-listener/configuration/agent-hook-types' -import { - buildWindowsAgentHookCurlPostCommand, - writeHooksJson, - writeManagedScript -} from '../agent-hooks/installer-utils' -import { refreshManagedScriptIfPresent } from '../agent-hooks/managed-hook-script-refresh' -import { - readTextFileRemote, - writeHooksJsonRemote, - writeManagedScriptRemote -} from '../agent-hooks/installer-utils-remote' +import { buildWindowsAgentHookCurlPostCommand } from '../agent-hooks/installation/commands/windows-agent-hook-post-command' +import { writeHooksJson } from '../agent-hooks/installation/configuration/hooks-json-write' +import { writeManagedScript } from '../agent-hooks/installation/scripts/managed-hook-script-write' +import { refreshManagedScriptIfPresent } from '../agent-hooks/installation/scripts/managed-hook-script-refresh' +import { readTextFileRemote } from '../agent-hooks/installation/remote/hook-text-files-remote' +import { writeHooksJsonRemote } from '../agent-hooks/installation/configuration/hooks-json-remote' +import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote' import { buildPosixHookPayloadCapture, buildPosixHookSpoolLines, buildWindowsHookEnvironmentGuardLines -} from '../agent-hooks/hook-stdin-contract' -import { buildPosixAgentHookPostCommand } from '../agent-hooks/hook-post-command' +} from '../agent-hooks/installation/scripts/hook-stdin-contract' +import { buildPosixAgentHookPostCommand } from '../agent-hooks/installation/scripts/hook-post-command' import { applyZCodeManagedHooks, getZCodeConfigPath, diff --git a/src/main/zcode/hook-settings.ts b/src/main/zcode/hook-settings.ts index 01937f65811..63f219de024 100644 --- a/src/main/zcode/hook-settings.ts +++ b/src/main/zcode/hook-settings.ts @@ -2,15 +2,17 @@ import { homedir } from 'node:os' import { join } from 'node:path' import { buildManagedCommandHook, - createManagedCommandMatcher, - getSharedManagedScriptPath, - hookDefinitionHasManagedCommand, - isPlainObject, - removeManagedCommands, - wrapPosixHookCommand, type HookDefinition -} from '../agent-hooks/installer-utils' -import { wrapWindowsBatchHookCommand } from '../agent-hooks/windows-direct-cmd-hook-command' +} from '../agent-hooks/installation/configuration/hook-config-schema' +import { + createManagedCommandMatcher, + hookDefinitionHasManagedCommand, + removeManagedCommands +} from '../agent-hooks/installation/commands/managed-hook-command-matching' +import { getSharedManagedScriptPath } from '../agent-hooks/installation/scripts/managed-hook-script-path' +import { isPlainObject } from '../agent-hooks/installation/configuration/hooks-json-read' +import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command' +import { wrapWindowsBatchHookCommand } from '../agent-hooks/installation/commands/windows-direct-cmd-hook-command' const ZCODE_SCRIPT_BASE = 'zcode-hook' diff --git a/src/wsl-guest/agent-hook-integration.test.ts b/src/wsl-guest/agent-hook-integration.test.ts index ab29822ce6a..e96cb764a55 100644 --- a/src/wsl-guest/agent-hook-integration.test.ts +++ b/src/wsl-guest/agent-hook-integration.test.ts @@ -12,7 +12,7 @@ import { AGENT_HOOK_NOTIFICATION_METHOD, AGENT_HOOK_REQUEST_REPLAY_METHOD } from '../shared/agent-hook-listener/transport/agent-hook-relay' -import { AgentHookServer } from '../main/agent-hooks/server' +import { AgentHookServer } from '../main/agent-hooks/server/agent-hook-server' import { publishAgentHookEnvelope } from './agent-hook-envelope-publication' const LEAF_7 = '77777777-7777-4777-8777-777777777777' diff --git a/src/wsl-guest/agent-hook-server-codex-side-thread.test.ts b/src/wsl-guest/agent-hook-server-codex-side-thread.test.ts index 02c6bc4810a..ccc0b75ed9a 100644 --- a/src/wsl-guest/agent-hook-server-codex-side-thread.test.ts +++ b/src/wsl-guest/agent-hook-server-codex-side-thread.test.ts @@ -4,7 +4,7 @@ import { join } from 'node:path' import { expect, it } from 'vitest' import type { AgentHookRelayEnvelope } from '../shared/agent-hook-listener/transport/agent-hook-relay' import { RelayAgentHookServer } from './agent-hook-server' -import { AgentHookServer } from '../main/agent-hooks/server' +import { AgentHookServer } from '../main/agent-hooks/server/agent-hook-server' const PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111' diff --git a/src/wsl-guest/agent-hook-server-codex-turn-interruption.test.ts b/src/wsl-guest/agent-hook-server-codex-turn-interruption.test.ts index 0c1ad806f6f..dce3104861d 100644 --- a/src/wsl-guest/agent-hook-server-codex-turn-interruption.test.ts +++ b/src/wsl-guest/agent-hook-server-codex-turn-interruption.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import type { AgentHookRelayEnvelope } from '../shared/agent-hook-listener/transport/agent-hook-relay' import { RelayAgentHookServer } from './agent-hook-server' -import { AgentHookServer } from '../main/agent-hooks/server' +import { AgentHookServer } from '../main/agent-hooks/server/agent-hook-server' const PANE_KEY = 'tab-1:11111111-1111-4111-8111-111111111111' const line = (payload: unknown): string => `${JSON.stringify({ type: 'event_msg', payload })}\n` diff --git a/tests/e2e/host-agent-launch-preferences-work.unit.test.ts b/tests/e2e/host-agent-launch-preferences-work.unit.test.ts index 27e449e5bf9..1d0360ba553 100644 --- a/tests/e2e/host-agent-launch-preferences-work.unit.test.ts +++ b/tests/e2e/host-agent-launch-preferences-work.unit.test.ts @@ -26,7 +26,7 @@ import { AGENT_LAUNCH_CHOICES_CAPABILITY } from '../../src/shared/agent-launch/c import { structuredLaunchSeedOptions } from '../../src/shared/native-chat/input/native-chat-session-option-defaults' import { replaceRuntimeEnvironmentRevisions } from '@/runtime/rpc/environment-revisions/runtime-environment-revision' -vi.mock('../../src/main/agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../src/main/agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: vi.fn(async () => {}) })) diff --git a/tests/e2e/host-agent-launch-settings-hook-bookkeeping.unit.test.ts b/tests/e2e/host-agent-launch-settings-hook-bookkeeping.unit.test.ts index 5e44dce267b..cd3f0791522 100644 --- a/tests/e2e/host-agent-launch-settings-hook-bookkeeping.unit.test.ts +++ b/tests/e2e/host-agent-launch-settings-hook-bookkeeping.unit.test.ts @@ -21,7 +21,7 @@ vi.mock('../../src/main/ssh/config/ssh-config-parser', () => ({ loadUserSshConfig: () => ({ hosts: [] }), sshConfigHostsToTargets: () => [] })) -vi.mock('../../src/main/agent-hooks/managed-agent-hook-controls', () => ({ +vi.mock('../../src/main/agent-hooks/installation/managed-agent-hook-controls', () => ({ applyAgentStatusHooksEnabled: hooks.apply })) vi.mock( diff --git a/tests/e2e/nested-agent-idle-owner.unit.test.ts b/tests/e2e/nested-agent-idle-owner.unit.test.ts index 1aa1db8275b..7d65b58b087 100644 --- a/tests/e2e/nested-agent-idle-owner.unit.test.ts +++ b/tests/e2e/nested-agent-idle-owner.unit.test.ts @@ -3,8 +3,12 @@ import { createTestStore } from '../../src/renderer/src/store/testing/app-store- import { sleepingRecordFromEntry } from '../../src/renderer/src/store/slices/agent-status/agent-status-sleeping-records' import { getAgentResumeArgv } from '../../src/shared/agent-launch/startup/agent-resume-argv' import { readAgentProcess } from '../../src/shared/agent-status/process/agent-process-presence-probe' -import { AgentHookServer } from '../../src/main/agent-hooks/server' -import { buildBody, PANE, postHookEvent } from '../../src/main/agent-hooks/server.test-fixtures' +import { AgentHookServer } from '../../src/main/agent-hooks/server/agent-hook-server' +import { + buildBody, + PANE, + postHookEvent +} from '../../src/main/agent-hooks/server/testing/server.test-fixtures' vi.mock('../../src/main/telemetry/client', () => ({ track: vi.fn() })) vi.mock('../../src/main/telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) })) diff --git a/tests/e2e/omp-retired-host-renderer.unit.test.ts b/tests/e2e/omp-retired-host-renderer.unit.test.ts index c3d2694c582..fc06a3eaf54 100644 --- a/tests/e2e/omp-retired-host-renderer.unit.test.ts +++ b/tests/e2e/omp-retired-host-renderer.unit.test.ts @@ -1,6 +1,6 @@ import { resetAgentPaneAuthorityAliasesForTests } from '../../src/renderer/src/store/slices/agent-status/agent-pane-authority' import { afterEach, describe, expect, it, vi } from 'vitest' -import { AgentHookServer } from '../../src/main/agent-hooks/server' +import { AgentHookServer } from '../../src/main/agent-hooks/server/agent-hook-server' import { toAgentStatusIpcPayload } from '../../src/main/agent-hooks/server/server-status-identity' import type { AgentStatusIpcPayload } from '../../src/shared/agent-status/contracts/agent-status-ipc-payload' import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' diff --git a/tests/e2e/pty-folder-project-runtime-contract.unit.test.ts b/tests/e2e/pty-folder-project-runtime-contract.unit.test.ts index ecbcdf09b74..ed01cc6e0b5 100644 --- a/tests/e2e/pty-folder-project-runtime-contract.unit.test.ts +++ b/tests/e2e/pty-folder-project-runtime-contract.unit.test.ts @@ -111,7 +111,7 @@ vi.mock('../../src/main/opencode/hook-service', () => vi.mock('../../src/main/mimo/hook-service', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../src/main/agent-hooks/server', () => +vi.mock('../../src/main/agent-hooks/server/agent-hook-server', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../src/main/pi/titlebar-extension-service', () => @@ -144,7 +144,7 @@ vi.mock('../../src/main/cli/linux-terminal-orca-cli-shim', () => vi.mock('../../src/main/memory/pty-registry', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../src/main/agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../src/main/agent-hooks/observations/migration-unsupported-pty-state', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock() ) diff --git a/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts b/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts index ffac87e1637..fb26f9a592b 100644 --- a/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts +++ b/tests/e2e/pty-spawn-cwd-folder-owner.unit.test.ts @@ -32,7 +32,7 @@ vi.mock('../../src/main/opencode/hook-service', () => vi.mock('../../src/main/mimo/hook-service', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../src/main/agent-hooks/server', () => +vi.mock('../../src/main/agent-hooks/server/agent-hook-server', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../src/main/pi/titlebar-extension-service', () => @@ -65,7 +65,7 @@ vi.mock('../../src/main/cli/linux-terminal-orca-cli-shim', () => vi.mock('../../src/main/memory/pty-registry', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../src/main/agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../src/main/agent-hooks/observations/migration-unsupported-pty-state', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock() ) diff --git a/tests/e2e/terminal-agent-pane-launch.unit.test.ts b/tests/e2e/terminal-agent-pane-launch.unit.test.ts index 8afb8590e41..0667445774a 100644 --- a/tests/e2e/terminal-agent-pane-launch.unit.test.ts +++ b/tests/e2e/terminal-agent-pane-launch.unit.test.ts @@ -102,7 +102,7 @@ vi.mock('../../src/main/opencode/hook-service', () => vi.mock('../../src/main/mimo/hook-service', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock()) ) -vi.mock('../../src/main/agent-hooks/server', () => +vi.mock('../../src/main/agent-hooks/server/agent-hook-server', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock()) ) vi.mock('../../src/main/pi/titlebar-extension-service', () => @@ -130,7 +130,7 @@ vi.mock('../../src/main/cli/linux-terminal-orca-cli-shim', () => vi.mock('../../src/main/memory/pty-registry', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock()) ) -vi.mock('../../src/main/agent-hooks/migration-unsupported-pty-state', () => +vi.mock('../../src/main/agent-hooks/observations/migration-unsupported-pty-state', () => import('../../src/main/ipc/pty/pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock() ) From 2d1298f0d6c7fb6f2ffa1cbd31df71c7d1e286d7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:29:33 -0800 Subject: [PATCH 5/9] Open agent setup with the current model highlighted (#39923) * Open agent setup with the current model highlighted * Start setup on the current model only when it is a rendered, non-Arguments row; remount once defaults settle * Return the setup highlight to the current model when a model search is cleared * Scope setup highlight navigation to one event and scroll the restored model into view * Scope setup highlight navigation to the event's phases and reveal the start model when it arrives --- ...entLaunchSetupPanel.current-model.test.tsx | 138 ++++++++++++++++++ .../agent/AgentLaunchSetupPanel.tsx | 53 +++---- .../agent/agent-launch-setup-option-rows.ts | 26 +++- .../agent/use-setup-model-highlight.ts | 53 +++++++ 4 files changed, 244 insertions(+), 26 deletions(-) create mode 100644 src/renderer/src/components/agent/AgentLaunchSetupPanel.current-model.test.tsx create mode 100644 src/renderer/src/components/agent/use-setup-model-highlight.ts diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.current-model.test.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.current-model.test.tsx new file mode 100644 index 00000000000..efacd606b38 --- /dev/null +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.current-model.test.tsx @@ -0,0 +1,138 @@ +// @vitest-environment happy-dom +import { act } from 'react' +import { fireEvent } from '@testing-library/react' +import { expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { + agentPickerDraft, + type AgentPickerEntry +} from '../../../../shared/agent-launch/picker/agent-launch-picker' +import { entry, root } from './agent-launch-setup-panel-test-fixture' +import { AgentLaunchSetupPanel } from './AgentLaunchSetupPanel' + +const opencode: AgentPickerEntry = { + ...entry, + agent: 'opencode', + label: 'OpenCode', + rows: [{ agent: 'opencode', kind: 'cli', executionHostId: 'local' }], + arguments: '--model opencode/gpt-5.3-codex', + terminal: {}, + catalog: { origin: 'unknown' } +} +const listed: AgentPickerEntry = { + ...opencode, + catalog: { + origin: 'probe', + fetchedAt: 1, + models: [ + 'github-copilot/claude-fable-5', + 'github-copilot/claude-opus-5', + 'opencode/gpt-5.3-codex' + ].map((id) => ({ id, label: id, efforts: [], isDefault: false })) + } +} +const draft = agentPickerDraft(opencode) +const onUse = vi.fn(() => true) +const onDraftChange = vi.fn() +const render = (own: AgentPickerEntry, mode?: 'select') => + act(() => + root.render( + + draft} + onDraftChange={onDraftChange} + onUse={onUse} + /> + + ) + ) +const highlighted = () => + document.querySelector('[cmdk-item][data-selected="true"]')?.getAttribute('data-value') + +it('opens on the current model, not the first listed one', () => { + render(listed) + expect(highlighted()).toBe('opencode/gpt-5.3-codex') +}) + +it('keeps the current model highlighted when the catalog arrives and lists it', () => { + render(opencode) + expect(highlighted()).toBe('opencode/gpt-5.3-codex') + render(listed) + expect(highlighted()).toBe('opencode/gpt-5.3-codex') +}) + +it('starts on the resolved model when defaults settle after the panel opens', () => { + render({ ...listed, arguments: undefined, defaultsPending: true }) + render(listed) + expect(highlighted()).toBe('opencode/gpt-5.3-codex') +}) + +it('keeps an Arguments-owned text action on its default instead of the inherited model', () => { + render( + { + ...listed, + arguments: '', + terminal: { model: 'opencode/gpt-5.3-codex' }, + textGeneration: { + defaultLabel: 'Default', + modelInArguments: true, + effortInArguments: false, + modelArgumentsUnrecognized: false, + effortArgumentsUnrecognized: false, + effortInModel: false, + effortByModel: {} + } + }, + 'select' + ) + expect(highlighted()).toBe('__text_action_default__') +}) + +it('returns to the current model after a search is cleared, so Enter uses it', () => { + render(listed, 'select') + const search = document.querySelector('[cmdk-input]')! + fireEvent.change(search, { target: { value: 'opus' } }) + expect(highlighted()).toBe('github-copilot/claude-opus-5') + fireEvent.change(search, { target: { value: '' } }) + expect(highlighted()).toBe('opencode/gpt-5.3-codex') + onUse.mockClear() + onDraftChange.mockClear() + fireEvent.keyDown(search, { key: 'Enter' }) + expect(onUse).toHaveBeenCalledTimes(1) + expect(onDraftChange).not.toHaveBeenCalled() +}) + +it('returns to the current model when a search is cleared without a key, as with Cut', async () => { + render(listed) + const search = document.querySelector('[cmdk-input]')! + fireEvent.change(search, { target: { value: 'opus' } }) + fireEvent.pointerMove(search) + await act(async () => {}) + fireEvent.change(search, { target: { value: '' } }) + expect(highlighted()).toBe('opencode/gpt-5.3-codex') +}) + +it('keeps a hovered model through a rerender, so Enter picks it instead of using the current one', () => { + render(listed, 'select') + const opus = document.querySelector('[cmdk-item][data-value="github-copilot/claude-opus-5"]')! + fireEvent.pointerMove(opus) + render(listed, 'select') + expect(highlighted()).toBe('github-copilot/claude-opus-5') + onUse.mockClear() + onDraftChange.mockClear() + fireEvent.keyDown(document.querySelector('[cmdk-input]')!, { key: 'Enter' }) + expect(onUse).not.toHaveBeenCalled() + expect(onDraftChange).toHaveBeenCalledTimes(1) +}) + +it('returns to the current model after End at the last row and a keyless clear', () => { + render(listed) + const search = document.querySelector('[cmdk-input]')! + fireEvent.keyDown(search, { key: 'End' }) + fireEvent.change(search, { target: { value: 'opus' } }) + fireEvent.change(search, { target: { value: '' } }) + expect(highlighted()).toBe('opencode/gpt-5.3-codex') +}) diff --git a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx index aec35bb04c9..7e420a90701 100644 --- a/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx +++ b/src/renderer/src/components/agent/AgentLaunchSetupPanel.tsx @@ -4,9 +4,11 @@ import type { AgentLaunchSetupPanelProps } from './AgentLaunchSetupButton' import { agentLaunchSetupOptionRows, agentLaunchSetupRowGroups, - agentLaunchSetupCatalogState as catalogOf + agentLaunchSetupCatalogState as catalogOf, + agentLaunchSetupModelRows } from './agent-launch-setup-option-rows' import { useRef, useState } from 'react' +import { useSetupModelHighlight } from './use-setup-model-highlight' import { Check, ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react' import { getAgentSessionOptionLaunchCatalog } from '../../../../shared/agent-session/options/agent-session-option-catalog' import { @@ -89,6 +91,15 @@ export function AgentLaunchSetupPanel({ const { hasModels, catalogPending, catalogMessage } = catalogOf(entry, models, currentModel, mode) const modelInArguments = textActionArgumentsOwnModel(entry, draft) const modelDisabled = disabled || defaultsPending || catalogPending + const modelRows = agentLaunchSetupModelRows( + models, + currentModel, + modelQuery, + legacy, + modelInArguments + ) + const modelList = useRef(null) + const highlight = useSetupModelHighlight(modelList, modelRows.start, modelQuery) const options = agentPickerEntryOptions(entry, currentModel, draft.surface) const optionRows = agentLaunchSetupOptionRows({ options, @@ -164,6 +175,7 @@ export function AgentLaunchSetupPanel({ } }} onKeyDown={(event) => { + highlight.endKey() event.stopPropagation() if ( !disabled && @@ -179,6 +191,8 @@ export function AgentLaunchSetupPanel({ { if ( !disabled && @@ -194,6 +208,7 @@ export function AgentLaunchSetupPanel({ } }} onKeyDown={(event) => { + highlight.onKeyDown(event) if (event.key === 'Enter') { event.stopPropagation() } @@ -238,29 +253,28 @@ export function AgentLaunchSetupPanel({ {t('agentPicker.legacyModels', 'Legacy models')} ) : null} - {models - .filter( - (model) => - !model.hidden && - (model.id === currentModel || modelQuery || Boolean(model.isLegacy) === legacy) - ) - .map((model) => ( + {modelRows.rows.map((model) => { + const current = model.unlisted || (currentModel === model.id && !modelInArguments) + return ( editDraft({ kind: 'choice', patch: { model: model.id } })} + data-current={current} + onSelect={() => { + if (!model.unlisted) { + editDraft({ kind: 'choice', patch: { model: model.id } }) + } + }} > {model.label} - {currentModel === model.id && !modelInArguments ? ( - - ) : null} + {current ? : null} - ))} + ) + })} {!legacy && !modelQuery && legacyCount > 0 ? ( setLegacy(true)}> @@ -274,17 +288,6 @@ export function AgentLaunchSetupPanel({ ) : null} - {currentModel && !models.some((model) => model.id === currentModel) ? ( - {}} - data-current="true" - > - {currentModel} - - - ) : null} diff --git a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts index 7a9e07ca2d1..ba9b27772d4 100644 --- a/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts +++ b/src/renderer/src/components/agent/agent-launch-setup-option-rows.ts @@ -11,7 +11,8 @@ import type { } from '../../../../shared/agent-launch/picker/agent-launch-picker-catalog' import type { AgentPickerEntry, - AgentPickerDraft + AgentPickerDraft, + AgentPickerModel } from '../../../../shared/agent-launch/picker/agent-launch-picker' import type { agentPickerPanelArguments } from '../../../../shared/agent-launch/picker/agent-launch-picker-arguments' @@ -242,3 +243,26 @@ export function agentLaunchSetupCatalogState( : null return { hasModels, catalogPending, catalogMessage } } + +/** Visible model rows, plus the model the list starts on. */ +export function agentLaunchSetupModelRows( + models: readonly AgentPickerModel[], + currentModel: string | undefined, + query: string, + legacy: boolean, + modelInArguments: boolean +) { + const rows: { id: string; label: string; unlisted?: true }[] = models.filter( + (model) => + !model.hidden && (model.id === currentModel || query || Boolean(model.isLegacy) === legacy) + ) + // Why one keyed list: when the catalog later lists an unlisted current model, its row keeps + // its identity, so the highlight stays on it instead of jumping to the first model. + if (currentModel && !models.some((model) => model.id === currentModel)) { + rows.push({ id: currentModel, label: currentModel, unlisted: true }) + } + // An Arguments-owned text action has no current model row, so it starts on its default as before. + const start = + !modelInArguments && rows.some((row) => row.id === currentModel) ? currentModel : undefined + return { rows, start } +} diff --git a/src/renderer/src/components/agent/use-setup-model-highlight.ts b/src/renderer/src/components/agent/use-setup-model-highlight.ts new file mode 100644 index 00000000000..bd48d53d862 --- /dev/null +++ b/src/renderer/src/components/agent/use-setup-model-highlight.ts @@ -0,0 +1,53 @@ +import { useLayoutEffect, useRef, useState, type KeyboardEvent, type RefObject } from 'react' + +const NAVIGATION_KEYS = new Set(['ArrowUp', 'ArrowDown', 'Home', 'End']) + +/** + * Starts the model list's highlight on `start`, and returns to it when a search is cleared. + * Why the navigation flag: controlled cmdk reports user moves and its own first-item picks through + * the same callback; only its own picks are undone. + */ +export function useSetupModelHighlight( + root: RefObject, + start: string | undefined, + query: string +) { + const [reassert, setReassert] = useState(false) + const navigating = useRef(false) + const value = query ? undefined : start + // Why: cmdk applies `value` only when the prop changes, so after its own pick we release it for + // one render and set it again. A start that arrives or returns is brought into view. + useLayoutEffect(() => { + if (reassert) { + setReassert(false) + } else if (value !== undefined) { + root.current + ?.querySelector(`[cmdk-item][data-value="${CSS.escape(value)}"]`) + ?.scrollIntoView({ block: 'nearest' }) + } + }, [reassert, value, root]) + return { + // The flag spans one event: set before cmdk handles it, cleared once it bubbles past the list. + command: { + value: reassert ? undefined : value, + onValueChange: (next: string) => { + if (!navigating.current && value !== undefined && next !== value) { + setReassert(true) + } + }, + onPointerMoveCapture: () => { + navigating.current = true + }, + onPointerMove: () => { + navigating.current = false + } + }, + onKeyDown: (event: KeyboardEvent) => { + navigating.current = + NAVIGATION_KEYS.has(event.key) || (event.ctrlKey && 'jknp'.includes(event.key)) + }, + endKey: () => { + navigating.current = false + } + } +} From 77926605e07219e69cff1f895e17c7b5eb7029c8 Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sun, 8 Nov 2026 13:31:21 -0800 Subject: [PATCH 6/9] test: remove 2 low-value vault and restart tests (#39970) Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com> --- config/flaky-test-pattern-baseline.txt | 1 - ...session-scanner-pi-omp-shared-root.test.ts | 8 -- .../ai-vault/session-scanner-scope.test.ts | 20 +--- ...ructured-agent-session-restart-cap.test.ts | 85 --------------- .../search/use-ai-vault-search.test.tsx | 100 +----------------- 5 files changed, 4 insertions(+), 210 deletions(-) delete mode 100644 src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index c39dde57a3f..be1d0d861f9 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -224,7 +224,6 @@ 1 test-no-real-time-wait:src/main/managed-server/lifecycle/orcad-managed-tunnel-local-port.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-claude-echo-working.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-queued-quit.test.ts -1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts 1 test-no-real-time-wait:src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-target-reconcile.test.ts 1 test-no-real-time-wait:src/main/provider-process/provider-group-orphan-guard.integration.test.ts 2 test-no-real-time-wait:src/main/provider-process/provider-process-supervisor.integration.test.ts diff --git a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts index 7a743a0b37b..544622cc8a5 100644 --- a/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts +++ b/src/main/ai-vault/scanners/pi/session-scanner-pi-omp-shared-root.test.ts @@ -121,18 +121,10 @@ async function writeSharedRootTranscripts(sessionsDir: string): Promise { } describe('scanAiVaultSessions with overlapping Pi and OMP roots', () => { - const sameFolder = (sessionsDir: string): string => sessionsDir const parentFolder = (sessionsDir: string): string => join(sessionsDir, '..') it.each([ - { layout: 'the same folder', piRoot: sameFolder, scope: {} }, // PI_CODING_AGENT_DIR=: Pi walks , OMP walks /sessions. { layout: 'a parent folder', piRoot: parentFolder, scope: {} }, - // A one-row cap sends the rest through scope recovery: Pi's buckets and OMP's walk. - { - layout: 'the same folder for a workspace', - piRoot: sameFolder, - scope: { scopePaths: ['/repo/app'], limit: 1 } - }, // Scope recovery reads Pi's cwd buckets, which sit under the agent folder's sessions/. { layout: 'a parent folder for a workspace', diff --git a/src/main/ai-vault/session-scanner-scope.test.ts b/src/main/ai-vault/session-scanner-scope.test.ts index 0af9cfc9b68..13efa226630 100644 --- a/src/main/ai-vault/session-scanner-scope.test.ts +++ b/src/main/ai-vault/session-scanner-scope.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { scanAiVaultSessions } from './session-scanner' +import { isolatedScanRoots } from './session-scanner-test-fixtures' import type { AiVaultScanOptions } from './session-scanner-types' let tempRoots: string[] = [] @@ -12,27 +13,10 @@ afterEach(async () => { tempRoots = [] }) -// Isolate Claude fixtures from every other source root. function scopedScanOptions(claudeProjectsDir: string, extra: Partial) { return { + ...isolatedScanRoots(claudeProjectsDir), claudeProjectsDir, - codexSessionsDir: '/nonexistent/codex', - geminiSessionsDir: '/nonexistent/gemini', - antigravityBrainDir: '/nonexistent/antigravity', - copilotSessionsDir: '/nonexistent/copilot', - cursorProjectsDir: '/nonexistent/cursor', - opencodeStorageDir: '/nonexistent/opencode', - opencodeDbPaths: [], - grokSessionsDir: '/nonexistent/grok', - devinTranscriptsDir: '/nonexistent/devin', - hermesSessionsDir: '/nonexistent/hermes', - rovoSessionsDir: '/nonexistent/rovo', - openclawStateDir: '/nonexistent/openclaw', - openclawLegacyStateDir: '/nonexistent/openclaw-legacy', - piSessionsDir: '/nonexistent/pi', - droidSessionsDir: '/nonexistent/droid', - droidProjectsDir: '/nonexistent/droid-projects', - kimiSessionsDir: '/nonexistent/kimi', ...extra } satisfies AiVaultScanOptions } diff --git a/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts b/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts deleted file mode 100644 index 0863ed3c9af..00000000000 --- a/src/main/native-chat/agent-session-wire/recovery/testing/structured-agent-session-restart-cap.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { expect, it, vi } from 'vitest' -import { - startStructuredAgentSessionContinuation, - type StructuredAgentSessionContinuationDeps -} from '../structured-agent-session-restart-continuation' -import { - resumeStructuredAgentSessionsFromRestart, - StructuredAgentSessionResumeAdmission -} from '../structured-agent-session-restart-resume-runner' -import { marker } from './structured-agent-session-restart-resume-test-harness' -import { createStructuredAgentSessionLogger } from '../../host/structured-agent-session-logger' - -type Handover = { dispatchState: string; reason?: string | null } | undefined - -const LIMIT = 3 - -it('holds each slot from accept until handover or rejection, and frees it when the wait ends (P2-27)', async () => { - const handovers = new Map>() - let waiting = 0 - let mostWaiting = 0 - const deps = (sessionId: string): StructuredAgentSessionContinuationDeps => ({ - currentFence: () => 1, - send: vi.fn(async () => ({ ok: true, value: { submission: { dispatchState: 'pending' } } })), - awaitHandedOver: async () => { - const handover = Promise.withResolvers() - handovers.set(sessionId, handover) - waiting += 1 - mostWaiting = Math.max(mostWaiting, waiting) - try { - return await handover.promise - } finally { - waiting -= 1 - } - }, - awaitSettlement: async () => ({ dispatchState: 'accepted' }), - note: async () => undefined, - liftRestartHold: async () => undefined, - logger: createStructuredAgentSessionLogger() - }) - const sessions = Array.from({ length: 8 }, (_, index) => `session-${index}`) - const outcomes = resumeStructuredAgentSessionsFromRestart( - { - admission: new StructuredAgentSessionResumeAdmission(LIMIT), - consumeMarker: async () => true, - resume: async (sessionId) => { - const started = await startStructuredAgentSessionContinuation( - deps(sessionId), - sessionId, - marker(), - 'operation-1' - ) - if ('done' in started && started.done.outcome === 'refused') { - throw new Error(started.done.reason ?? 'refused') - } - } - }, - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the runner reads only each candidate's session id. - sessions.map((sessionId) => ({ sessionId }) as never), - 'modal' - ) - const settle = async (sessionId: string, handover: Handover) => { - await vi.waitFor(() => expect(handovers.has(sessionId)).toBe(true)) - handovers.get(sessionId)!.resolve(handover) - } - - await vi.waitFor(() => expect(waiting).toBe(LIMIT)) - // Acceptance alone must retain the startup slot until handover. - await new Promise((resolve) => setTimeout(resolve, 20)) - expect(handovers.size).toBe(LIMIT) - await settle('session-0', { dispatchState: 'pending' }) - await settle('session-1', { dispatchState: 'rejected', reason: 'Codex could not start.' }) - // An ended wait frees its slot without claiming delivery. - await settle('session-2', undefined) - for (const sessionId of sessions.slice(3)) { - await settle(sessionId, { dispatchState: 'pending' }) - } - - const results = await outcomes - expect(mostWaiting).toBe(LIMIT) - expect(results.find((result) => result.sessionId === 'session-1')).toMatchObject({ - outcome: 'refused', - reason: 'Codex could not start.' - }) - expect(results.filter((result) => result.outcome === 'resumed')).toHaveLength(7) -}) diff --git a/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx b/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx index 21fff8bd8c8..29491600d01 100644 --- a/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx +++ b/src/renderer/src/components/right-sidebar/ai-vault/search/use-ai-vault-search.test.tsx @@ -12,7 +12,6 @@ import { searchResults } from '../../../../../../shared/ai-vault/search/ai-vault-search-test-fixture' import { resetStructuredAgentSessionStatusFeedsForTests } from '@/runtime/native-chat/status/structured-agent-session-status-feed' -import type { AgentSessionStatusEvent } from '../../../../../../shared/agent-session/agent-session-wire' import { useAiVaultSearch } from './use-ai-vault-search' const mockSettings: { aiVaultSearch?: { enabled: boolean } } = {} @@ -22,10 +21,7 @@ vi.mock('@/store/index', () => ({ ) => select({ settings: mockSettings, runtimeEnvironments: [] }) })) -const feeds = vi.hoisted(() => ({ - subscribe: vi.fn(), - emit: new Map void>() -})) +const feeds = vi.hoisted(() => ({ subscribe: vi.fn() })) vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => ({ subscribeStructuredAgentSessionStatus: feeds.subscribe })) @@ -47,11 +43,7 @@ const empty: AiVaultSearchResponse = { } beforeEach(() => { resetStructuredAgentSessionStatusFeedsForTests() - feeds.emit.clear() - feeds.subscribe.mockImplementation(async (target, emit) => { - feeds.emit.set(target.environmentId ?? 'local', emit) - return { unsubscribe: vi.fn() } - }) + feeds.subscribe.mockImplementation(async () => ({ unsubscribe: vi.fn() })) vi.useFakeTimers() Object.defineProperty(window, 'api', { configurable: true, @@ -143,94 +135,6 @@ it('does not revive old results or cursors before debounce when returning from a unmount() }) -it('revalidates active search without losing hits, accepting old pages, or touching another host', async () => { - const request = { query: 'inventory' } - const owned = { - ...searchHit(), - title: 'Budget plan', - structuredSession: { sessionId: 'native', workspaceId: 'workspace' } - } - searchSessions.mockResolvedValue({ - ...searchResults(), - hits: [owned], - page: { cursor: 'old-page', hasMore: true } - }) - const a = renderHook(() => useAiVaultSearch(request, 'runtime:a', '')) - const b = renderHook(() => useAiVaultSearch(request, 'runtime:b', '')) - const summary = { - sessionId: 'native', - workspaceId: 'workspace', - agent: 'pi' as const, - latestPrompt: '', - status: null, - updatedAt: 1, - providerSession: { key: 'session_id' as const, id: '/provider' } - } - await act(async () => { - await Promise.resolve() - await Promise.resolve() - }) - await act(async () => feeds.emit.get('a')?.({ type: 'snapshot', sessions: [summary] })) - await debounce() - const baseline = searchSessions.mock.calls.length - for (const n of [10, 100]) { - await act(async () => { - for (let i = 0; i < n; i++) { - feeds.emit.get('a')?.({ - type: 'status', - session: { ...summary, updatedAt: i, toolName: `${i}` } - }) - feeds.emit.get('a')?.({ - type: 'snapshot', - sessions: [], - namingActiveSessionIds: [], - conversationNames: [{ sessionId: 'native', conversationName: `${i}` }] - }) - } - }) - expect(searchSessions).toHaveBeenCalledTimes(baseline) - } - let settlePage = (_response: AiVaultSearchResponse): void => {} - searchSessions.mockImplementationOnce( - () => - new Promise((resolve) => { - settlePage = resolve - }) - ) - act(() => a.result.current.loadMore()) - const { providerSession: _provider, ...detached } = summary - await act(async () => { - for (const id of ['/next', '/third']) { - feeds.emit.get('a')?.({ - type: 'status', - session: { - ...summary, - providerSession: { key: 'session_id', id } - } - }) - } - feeds.emit.get('a')?.({ type: 'status', session: detached }) - }) - expect(a.result.current.hits).toEqual([owned]) - const recovered = { ...searchHit(), title: 'Check inventory' } - searchSessions.mockResolvedValueOnce({ ...searchResults(), hits: [recovered] }) - await act(async () => - settlePage({ ...searchResults(), hits: [{ ...searchHit(), title: 'obsolete' }] }) - ) - expect(a.result.current.hits).toEqual([recovered]) - expect(b.result.current.hits).toEqual([owned]) - expect( - searchSessions.mock.calls.slice(baseline).map(([args, scope]) => [args.cursor, scope]) - ).toEqual([ - ['old-page', 'runtime:a'], - [undefined, 'runtime:a'] - ]) - a.unmount() - b.unmount() - await act(async () => feeds.emit.get('a')?.({ type: 'snapshot', sessions: [] })) - expect(searchSessions).toHaveBeenCalledTimes(baseline + 2) -}) - it('keeps the last hits on screen until a newer query answers, ignoring the older reply', async () => { const hit = (sessionId: string) => ({ ...searchHit(), sessionId }) let answerOld = (_response: AiVaultSearchResponse): void => {} From 1d28b8882cb432dcbc4433b29b94d748ed88d70e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:34:07 -0800 Subject: [PATCH 7/9] chore(ratchets): fail PRs that add sync fs calls on Electron main or new setInterval polls (#39930) * chore(ratchets): count sync fs calls on Electron main and setInterval calls Sync fs on main and fixed-cadence intervals that never settle were two of the most common perf fix classes since September, and no gate counted them. Both ratchets grandfather today's uses per file and fail when a file's count grows. * chore(ratchets): count every sync fs export, src/shared and node:timers intervals Review: the allow-list missed descriptor/copy APIs, src/shared helpers run on main too, and setInterval imported from node:timers escaped the timer count. * chore(ratchets): keep hosted setInterval calls beside a named timer import Review: a named node:timers import zeroed window/globalThis calls too, a destructured require was counted twice, and collector edits didn't select the timer ratchet in check:changed. * chore(ratchets): charge calls through an alias, not the alias binding Decider ruling B on review finding C6: binding a plain alias of a gated call counted as a use, so an alias refactor failed every collector-based ratchet. Conditional/fallback aliases and exported bindings stay charged. * chore(ratchets): count bare setInterval only when nothing local shadows it Review: the timer ratchet kept its own narrower binding resolver, so alias and namespace-destructure forms of an imported setInterval counted twice. Module bindings are the shared collector's; a bare call is the global only when the file declares no setInterval binding. * chore(ratchets): resolve bare setInterval calls per scope Decider ruling A: the file-wide shadow rule let an unrelated parameter or type declaration named setInterval hide every global poll in the file. Each bare call now resolves through a single-file TypeScript checker (noLib, noResolve) and counts when it binds to nothing declared in the file. * chore(ratchets): write the timer baseline exactly as --prune does * chore(ratchets): charge global timer aliases and bracket access CodeRabbit: `const schedule = setInterval; schedule(poll)` and `window['setInterval'](poll)` counted zero. Count value references to the global timer (per scope) instead of only direct calls. * chore(ratchets): charge shorthand timer escapes; skip writes, typeof and JSX tags Review: `{ setInterval }` of the global counted 0, while assignments to it, parenthesized typeof probes and a tag counted 1. * chore(ratchets): charge compound assignments to the global timer Review: `||=` and `??=` read setInterval before writing it, so only a plain `=` target is write-only. * chore(ratchets): regenerate baselines for files main moved main's SSH reorganisation moved counted files under src/main/ssh and src/main/managed-server; counts are unchanged except one sync fs call main removed. --- config/main-sync-fs-baseline.txt | 616 ++++++++++++++++++ config/performance-audit.md | 8 + config/recurring-timer-baseline.txt | 92 +++ .../check-changed-selection.mjs | 11 +- .../preflight/changed-checks/run-lint.mjs | 2 + .../check-main-sync-spawn-ratchet.test.mjs | 16 +- .../gated-call-use-collector.mjs | 33 +- .../check-main-sync-fs-ratchet.mjs | 115 ++++ .../check-recurring-timer-ratchet.mjs | 168 +++++ .../check-recurring-timer-ratchet.test.mjs | 40 ++ package.json | 2 + 11 files changed, 1094 insertions(+), 9 deletions(-) create mode 100644 config/main-sync-fs-baseline.txt create mode 100644 config/recurring-timer-baseline.txt create mode 100644 config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs create mode 100644 config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs create mode 100644 config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.test.mjs diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt new file mode 100644 index 00000000000..eb8a6f17c23 --- /dev/null +++ b/config/main-sync-fs-baseline.txt @@ -0,0 +1,616 @@ +# Synchronous node:fs calls (every *Sync export) in production src/main and src/shared, per file. +# Startup-only or one-shot uses are fine to keep; per-RPC, per-spawn, per-focus or per-poll uses are the target. +# This is a RATCHET: counts may only go DOWN. +# Prune after removing calls: pnpm check:main-sync-fs-ratchet --prune +1 src/main/agent-hooks/first-work-rename-runtime.ts +2 src/main/agent-hooks/hook-config-write-path.ts +1 src/main/agent-hooks/hooks-json-read.ts +20 src/main/agent-hooks/installer-utils.ts +6 src/main/agent-hooks/locked-executable-rename.ts +1 src/main/agent-hooks/server/server-hydration.ts +1 src/main/agent-hooks/wsl-hook-relay-deps.ts +3 src/main/agent-hooks/wsl-hook-relay-launch.ts +1 src/main/agent-launch/trust/agent-trust-ownership-ledger.ts +14 src/main/agent-launch/trust/agent-trust-presets.ts +2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts +1 src/main/agent-launch/trust/execution-host-workspace-trust.ts +4 src/main/ai-vault/parse-cache/session-parse-cache-legacy-json.ts +2 src/main/ai-vault/scan-service/session-scanner-service-entry-path.ts +1 src/main/ai-vault/scan-service/session-scanner-service-spawn.ts +1 src/main/ai-vault/scanners/omp/omp-session-root.ts +1 src/main/ai-vault/scanners/opencode/reader-transport/opencode-wsl-runtime-preparation.ts +2 src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-worker-spawn.ts +8 src/main/amp/hook-service.ts +2 src/main/amp/managed-plugin-install-status.ts +1 src/main/antigravity/antigravity-host-acp.ts +1 src/main/antigravity/native-account-launch.ts +5 src/main/antigravity/native-account-store.ts +2 src/main/antigravity/native-credential-backend.ts +7 src/main/antigravity/native-file-credentials.ts +12 src/main/artifacts/artifact-create-intent-store.ts +2 src/main/artifacts/artifact-share-record-store.ts +1 src/main/automations/external-manager-discovery.ts +7 src/main/bitbucket/credential-store.ts +1 src/main/browser-passwords/browser-password-chromium-import.ts +2 src/main/browser-passwords/browser-password-vault-file.ts +2 src/main/browser/agent-browser/agent-browser-bridge-process.ts +2 src/main/browser/agent-browser/agent-browser-dependency-binary.ts +2 src/main/browser/agent-browser/agent-browser-process-environment.ts +1 src/main/browser/agent-browser/agent-browser-session-reset.ts +2 src/main/browser/client-hosts/file-transfers/browser-client-download-relay.ts +1 src/main/browser/client-hosts/file-transfers/browser-client-upload-staging.ts +2 src/main/browser/client-hosts/leases/browser-host-client-identity.ts +1 src/main/browser/cookies/browser-cookie-import-diagnostics.ts +2 src/main/browser/cookies/chromium/chromium-cookie-path.ts +4 src/main/browser/cookies/chromium/chromium-cookie-snapshot.ts +1 src/main/browser/cookies/chromium/import-cookies.ts +3 src/main/browser/cookies/client-route/client-route-cookie-import-source-store.ts +2 src/main/browser/cookies/sources/browser-cookie-detection.ts +8 src/main/browser/cookies/sources/browser-cookie-firefox-import.ts +2 src/main/browser/cookies/sources/browser-cookie-key.ts +1 src/main/browser/cookies/sources/browser-cookie-safari-import.ts +5 src/main/browser/cookies/sources/browser-cookie-source-profiles.ts +11 src/main/browser/cookies/staging/browser-session-cookie-staging.ts +1 src/main/browser/downloads/browser-download-destination.ts +2 src/main/browser/extensions/api-runtime/browser-extension-worker-shim-source.ts +8 src/main/browser/extensions/installation/browser-extension-install-store.ts +1 src/main/browser/extensions/installation/browser-extension-load-directory.ts +1 src/main/browser/extensions/profile-sessions/browser-extension-session-loader.ts +2 src/main/browser/extensions/profile-storage/browser-extension-data-removal.ts +4 src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts +3 src/main/browser/extensions/profile-storage/browser-extension-retired-profile-storage.ts +8 src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts +1 src/main/browser/guest-lifecycle/popups/browser-popup-background-cdp-probe.ts +2 src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.ts +1 src/main/browser/identity/browser-identity-mode-record.ts +2 src/main/browser/identity/browser-identity-mode-store.ts +2 src/main/browser/network/egress/browser-route-egress-electron-launch.ts +4 src/main/browser/network/execution-routes/wsl-browser-network-relay-launch.ts +5 src/main/browser/routing/partitions/browser-route-partition-binding-file.ts +3 src/main/browser/routing/partitions/browser-route-partition-binding-store.ts +4 src/main/browser/routing/partitions/browser-route-partition-pending-deletes.ts +4 src/main/browser/sessions/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 +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 +2 src/main/claude/claude-profile-hook-target.ts +1 src/main/claude/claude-rejected-api-key.ts +1 src/main/claude/claude-rewind-transcript.ts +1 src/main/claude/hook-service.ts +3 src/main/claude/statusline-install.ts +6 src/main/claude/windows-hook-files.ts +1 src/main/cli/appimage-copy-pre-extraction.ts +3 src/main/cli/appimage-extracted-root.ts +1 src/main/cli/appimage-extraction-pruning.ts +2 src/main/cli/appimage-generation-lease.ts +4 src/main/cli/appimage-generation-residency.ts +16 src/main/cli/appimage-stable-launcher.ts +1 src/main/cli/cli-command-inspection.ts +1 src/main/cli/cli-dev-launcher.ts +3 src/main/cli/cli-install-location.ts +2 src/main/cli/linux-bare-orca-dispatcher.ts +7 src/main/cli/linux-terminal-orca-cli-shim.ts +2 src/main/cli/wsl-managed-cli.ts +2 src/main/codex-accounts/codex-account-identity.ts +3 src/main/codex-accounts/codex-account-registration.ts +4 src/main/codex-accounts/codex-config-mirror.ts +1 src/main/codex-accounts/codex-credential-absence-grace.ts +1 src/main/codex-accounts/codex-login-auth-snapshot.ts +5 src/main/codex-accounts/codex-managed-home-lifecycle.ts +6 src/main/codex-accounts/codex-managed-home-path.ts +17 src/main/codex-accounts/fs-utils.ts +1 src/main/codex-accounts/guest-codex-account-homes.ts +6 src/main/codex-accounts/host-codex-managed-home-ownership.ts +2 src/main/codex-accounts/legacy-shared-auth-migration.ts +21 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-recovery-script-harness.ts +36 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-harness.ts +6 src/main/codex-accounts/legacy-wsl-runtime-auth-drain-script-interference-shims.ts +1 src/main/codex-accounts/managed-codex-auth-readiness.ts +7 src/main/codex-accounts/runtime-home-service-auth-core.ts +5 src/main/codex-accounts/runtime-home-service-auth-provenance.ts +23 src/main/codex-accounts/runtime-home-service-auth-sync.ts +19 src/main/codex-accounts/runtime-home-service-legacy-migration.ts +1 src/main/codex-accounts/runtime-home-service-managed-home.ts +14 src/main/codex-accounts/runtime-home-service-paths.ts +1 src/main/codex-accounts/runtime-home-service-sync.ts +2 src/main/codex-accounts/runtime-home-service-wsl-core.ts +1 src/main/codex-usage/codex-session-file-discovery.ts +1 src/main/codex/configuration/codex-path-observation.ts +21 src/main/codex/configuration/homes/codex-home-paths.ts +6 src/main/codex/configuration/homes/codex-managed-home-resource-copy-marker.ts +8 src/main/codex/configuration/homes/codex-managed-home-rules.ts +5 src/main/codex/configuration/homes/codex-pane-account-registry.ts +5 src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.ts +1 src/main/codex/configuration/settings/codex-config-path-reference-rewrite.ts +1 src/main/codex/configuration/settings/config-settings-baseline.ts +5 src/main/codex/configuration/settings/config-settings-promotion-write-target.ts +3 src/main/codex/configuration/settings/config-settings-promotion.ts +1 src/main/codex/configuration/shared-server/codex-daemon-socket-path-guard.ts +8 src/main/codex/configuration/toml/config-toml-atomic-write.ts +4 src/main/codex/history/backfill/codex-session-backfill-marker.ts +17 src/main/codex/history/bridges/codex-session-bridge.ts +5 src/main/codex/history/index/codex-session-index-heal-state.ts +2 src/main/codex/history/index/codex-state-db.ts +2 src/main/codex/history/resume/codex-session-resume-home.ts +2 src/main/codex/history/rollouts/codex-account-home-discovery.ts +1 src/main/codex/history/rollouts/codex-session-file-listing.ts +2 src/main/codex/history/rollouts/codex-session-link.ts +1 src/main/codex/hooks/installation/codex-hook-local-install.ts +2 src/main/codex/hooks/installation/codex-hook-local-maintenance.ts +4 src/main/codex/hooks/reconciliation/codex-hook-legacy-cleanup.ts +2 src/main/codex/hooks/reconciliation/codex-hook-status.ts +4 src/main/codex/hooks/reconciliation/codex-real-home-hooks-json.ts +3 src/main/codex/trust/grants/codex-trust-grant-ledger.ts +2 src/main/codex/trust/hooks/codex-hook-trust-derivation.ts +1 src/main/codex/trust/hooks/codex-hook-trust-memo.ts +2 src/main/codex/trust/hooks/codex-hook-user-mirroring.ts +4 src/main/codex/trust/hooks/hook-trust-promotion.ts +1 src/main/codex/trust/identity/codex-trust-identity.ts +1 src/main/codex/trust/toml/config-toml-project-trust.ts +7 src/main/codex/trust/toml/config-toml-trust.ts +2 src/main/computer/desktop-script-provider-paths.ts +1 src/main/computer/macos-native-provider-client.ts +3 src/main/computer/macos-native-provider-paths.ts +5 src/main/computer/macos-native-provider-transport.ts +1 src/main/computer/sidecar-client.ts +3 src/main/connector-cloud/connector-turn-events.ts +1 src/main/copilot/hook-service.ts +4 src/main/crash-reporting/appimage-crashpad-handler-exit.ts +2 src/main/credentials/credential-file-protection.ts +6 src/main/credentials/encrypted-api-key-file-store.ts +10 src/main/credentials/integration-credential-file.ts +1 src/main/credentials/integration-state-file-cache.ts +1 src/main/credentials/integration-token-file-cache.ts +2 src/main/credentials/saved-credential-readability.ts +2 src/main/daemon/admission/automatic-work-run-marker-store.ts +5 src/main/daemon/admission/host-terminal-ledger.ts +1 src/main/daemon/admission/legacy-restore-records.ts +1 src/main/daemon/daemon-entry.ts +1 src/main/daemon/endpoint/identity/daemon-endpoint-incarnation.ts +3 src/main/daemon/endpoint/identity/daemon-pid-identity.ts +2 src/main/daemon/endpoint/identity/daemon-pid-record-quarantine.ts +2 src/main/daemon/endpoint/identity/daemon-process-start-time.ts +2 src/main/daemon/endpoint/identity/daemon-ready-identity.ts +3 src/main/daemon/endpoint/publication/daemon-endpoint-lifecycle.ts +7 src/main/daemon/endpoint/publication/daemon-endpoint-ownership.ts +1 src/main/daemon/endpoint/publication/daemon-endpoint-probe.ts +3 src/main/daemon/endpoint/publication/daemon-private-file-modes.ts +2 src/main/daemon/endpoint/publication/daemon-socket-endpoint-path.ts +3 src/main/daemon/executable-host/linux/daemon-appimage-generation-launch.ts +1 src/main/daemon/executable-host/linux/daemon-appimage-launch.ts +3 src/main/daemon/executable-host/linux/daemon-host-image.ts +2 src/main/daemon/executable-host/macos/macos-daemon-bundle.ts +9 src/main/daemon/executable-host/windows/daemon-host-build-inventory.ts +2 src/main/daemon/executable-host/windows/daemon-host-file-hash-cache.ts +3 src/main/daemon/executable-host/windows/daemon-host-manifest.ts +2 src/main/daemon/executable-host/windows/daemon-host-reclaim.ts +12 src/main/daemon/executable-host/windows/daemon-host-relocation.ts +4 src/main/daemon/health/daemon-health.ts +4 src/main/daemon/history/restoration/history-reader.ts +1 src/main/daemon/history/restoration/terminal-history-checkpoint-reader.ts +1 src/main/daemon/history/restoration/terminal-history-legacy-scrollback-restore.ts +1 src/main/daemon/history/storage/history-manager.ts +3 src/main/daemon/history/storage/terminal-history-metadata.ts +2 src/main/daemon/history/storage/terminal-history-permission-repair.ts +8 src/main/daemon/history/storage/terminal-history-recovery-quarantine.ts +1 src/main/daemon/history/storage/terminal-history-session-files.ts +3 src/main/daemon/history/storage/terminal-history-session-tombstone.ts +6 src/main/daemon/history/storage/terminal-history-session-writer.ts +1 src/main/daemon/launch/daemon-bundle-staleness.ts +1 src/main/daemon/launch/daemon-endpoint-adoption.ts +3 src/main/daemon/launch/daemon-generation-liveness.ts +2 src/main/daemon/launch/daemon-launch-paths.ts +1 src/main/daemon/launch/daemon-legacy-process-liveness.ts +2 src/main/daemon/launch/daemon-protocol-cleanup.ts +11 src/main/daemon/launch/daemon-spawner.ts +1 src/main/daemon/launch/daemon-stale-kill.ts +1 src/main/daemon/observability/daemon-adoption-telemetry-event.ts +1 src/main/daemon/observability/daemon-file-log.ts +3 src/main/daemon/permissions/daemon-tcc-attribution.ts +5 src/main/daemon/process-scopes/daemon-cgroup-scope.ts +1 src/main/daemon/process-scopes/daemon-user-manager-lifetime.ts +1 src/main/daemon/process-scopes/terminal-scopes-runtime.ts +2 src/main/daemon/process-scopes/terminal-scopes.ts +1 src/main/daemon/providers/adapter/daemon-pty-daemon-recovery.ts +1 src/main/daemon/providers/adapter/daemon-pty-session-inventory.ts +1 src/main/daemon/providers/routing/daemon-legacy-adapters.ts +2 src/main/daemon/pty-subprocess/spawn-preflight.ts +1 src/main/daemon/shell-readiness/shell-ready.ts +1 src/main/daemon/transport/client/daemon-client-token.ts +2 src/main/daemon/transport/stream/daemon-stream-backlog-probe.ts +4 src/main/devin/hook-config-json.ts +3 src/main/dsh/dsh-hook-packages.ts +3 src/main/dsh/hook-service.ts +1 src/main/emulator/android/android-sdk-host-discovery.ts +7 src/main/emulator/android/scrcpy-server-download.ts +1 src/main/emulator/emulator-probe.ts +2 src/main/emulator/serve-sim-detached-session.ts +7 src/main/emulator/serve-sim-execution.ts +17 src/main/emulator/serve-sim-runtime-materializer.ts +12 src/main/external-editors/external-editor-launch.ts +9 src/main/filesystem/durable-file-write.ts +2 src/main/filesystem/rolling-file-backup.ts +2 src/main/foreign-sqlite-readers/foreign-sqlite-reader-entry-path.ts +1 src/main/foreign-sqlite-readers/foreign-sqlite-reader-spawn.ts +1 src/main/foreign-sqlite-readers/readers/cursor-profile.ts +1 src/main/foreign-sqlite-readers/readers/opencode-binder-sessions.ts +1 src/main/git/huge-folder-ignore.ts +5 src/main/git/repo-detection.ts +13 src/main/git/repo-git-marker-scan.ts +3 src/main/git/worktrees/catalog/worktree-git-path.ts +1 src/main/github/client/check/check-job-log-cache-retention-child.mjs +3 src/main/grok/grok-hook-backup-cleanup.ts +3 src/main/grok/grok-hook-owners.ts +4 src/main/grok/grok-hook-symlink-cleanup-marker.ts +4 src/main/grok/hook-service.ts +4 src/main/hang-watchdog/hang-detection-marker.ts +1 src/main/hang-watchdog/hang-watchdog-worker-path.ts +1 src/main/hang-watchdog/previous-hang-detection.ts +1 src/main/hermes/hermes-default-home.ts +10 src/main/hermes/hermes-home-filesystem.ts +2 src/main/hermes/hook-service.ts +2 src/main/host/secret-protection-report.ts +1 src/main/ipc/app.ts +1 src/main/ipc/command-path/command-path-directory-worker-client.ts +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 +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/macos-keyboard-layout-snapshot.ts +1 src/main/ipc/notification-authorization-status.ts +1 src/main/ipc/pty/spawn-pane-env.ts +1 src/main/ipc/ssh/ssh-connect-flow.ts +2 src/main/ipc/worktree-remote.ts +2 src/main/ipc/wsl-guest-windows-drive-path.ts +7 src/main/jcode/hook-service.ts +8 src/main/jira/site-credential-store.ts +7 src/main/keybindings/keybinding-file-parser.ts +1 src/main/keybindings/keybinding-file.ts +13 src/main/kimi/hook-service.ts +3 src/main/kiro/hook-service.ts +1 src/main/kiro/standalone-hooks.ts +4 src/main/linear/linear-credential-paths.ts +3 src/main/linear/linear-legacy-viewer-store.ts +1 src/main/linear/linear-token-store.ts +3 src/main/linear/linear-workspace-registry.ts +1 src/main/macos-permissions/macos-tcc-prompt-notice.ts +3 src/main/managed-data-accounts/credential-capture.ts +18 src/main/managed-data-accounts/profile-removal.ts +10 src/main/managed-data-accounts/service.ts +1 src/main/managed-server/activation/orcad-held-fence-tokens.ts +1 src/main/managed-server/install/orcad-deployment-target.ts +2 src/main/managed-server/install/remote-versioned-install.ts +1 src/main/memory/darwin-process-footprint.ts +13 src/main/mimo/hook-service.ts +6 src/main/minimax/minimax-cookie-store.ts +1 src/main/muse/hook-config-json.ts +4 src/main/muse/hook-service.ts +2 src/main/native-chat/agent-session-attachments/agent-session-attachment-claims.ts +1 src/main/native-chat/agent-session-journal/database/journal-host-database.ts +1 src/main/native-chat/host-readable-transcript-path.ts +2 src/main/native-chat/wsl-transcript-fs-process-spawn.ts +1 src/main/node-runtime/appimage-bundled-node-runtime.ts +2 src/main/node-runtime/managed-runtime-release-install.ts +7 src/main/node-runtime/managed-runtime-release.ts +11 src/main/notebook/python-environments.ts +1 src/main/observability/bounded-log-file-writer.ts +2 src/main/observability/bundle.ts +6 src/main/observability/local-file-sink.ts +14 src/main/opencode/hook-service.ts +1 src/main/opencode/legacy-plugin-acl-retry.ts +2 src/main/opencode/opencode-overlay-manifest.ts +1 src/main/opencode/opencode-plugin-config-writer.ts +1 src/main/opencode/opencode-private-server.ts +1 src/main/opencode/opencode-wsl-text-task.ts +2 src/main/orca-profiles/new-profile-state.ts +3 src/main/orca-profiles/other-profile-workspace-catalog.ts +3 src/main/orca-profiles/profile-artifact-cloud-cleanup.ts +1 src/main/orca-profiles/profile-cloud-index.ts +4 src/main/orca-profiles/profile-cloud-session-store.ts +12 src/main/orca-profiles/profile-index-store.ts +5 src/main/orca-profiles/profile-legacy-state-import.ts +4 src/main/orca-profiles/profile-project-move-intent.ts +3 src/main/orca-profiles/profile-project-move-record.ts +4 src/main/orca-profiles/profile-project-state-file.ts +2 src/main/orcad/launcher.ts +7 src/main/orcad/node-pty-prebuilt-slot.ts +2 src/main/orcad/node-pty-precondition.ts +2 src/main/orcad/orcad-agent-browser-binary.ts +1 src/main/orcad/orcad-app-paths.ts +1 src/main/orcad/orcad-artifact-identity.ts +2 src/main/orcad/orcad-artifact-materializer.ts +12 src/main/orcad/orcad-bundled-runtime.ts +2 src/main/orcad/orcad-cli-launcher.ts +1 src/main/orcad/orcad-command-arguments.ts +1 src/main/orcad/orcad-completed-stop-receipt.ts +2 src/main/orcad/orcad-daemon-slot-pins.ts +2 src/main/orcad/orcad-data-root-locality.ts +3 src/main/orcad/orcad-data-root-privacy.ts +4 src/main/orcad/orcad-host-account-launch-env-store.ts +1 src/main/orcad/orcad-host-adapters.ts +2 src/main/orcad/orcad-idle-stop-record.ts +3 src/main/orcad/orcad-instance-lock-hold.ts +16 src/main/orcad/orcad-instance-lock-reclaim.ts +4 src/main/orcad/orcad-instance-lock.ts +7 src/main/orcad/orcad-local-serve-selection.ts +1 src/main/orcad/orcad-lock-clone-machine.ts +1 src/main/orcad/orcad-managed-stop-cancellation.ts +3 src/main/orcad/orcad-managed-stop-decision.ts +2 src/main/orcad/orcad-managed-stop-request.ts +4 src/main/orcad/orcad-plaintext-credential-migration.ts +5 src/main/orcad/orcad-process-start-time.ts +11 src/main/orcad/orcad-secret-key-record.ts +3 src/main/orcad/orcad-stale-lock-reclaim.ts +1 src/main/orcad/orcad-stop-request-listener.ts +1 src/main/orcad/orcad-wsl-holder-release.ts +2 src/main/orcad/orcad-wsl-host-claude-profile-refresh.ts +1 src/main/orcad/serve-profile-ssh-targets.ts +6 src/main/persistence/atomic-snapshot-writer.ts +6 src/main/persistence/loading-store/user-data-path.ts +3 src/main/persistence/loading-store/write-flush-barriers.ts +9 src/main/persistence/migrating-orcad-catalog/migration-journal-directory.ts +4 src/main/persistence/migrating-orcad-catalog/orcad-migration-blob-installers.ts +3 src/main/persistence/migrating-orcad-catalog/orcad-migration-blob-staging.ts +17 src/main/persistence/migrating-orcad-catalog/orcad-migration-staged-file.ts +1 src/main/persistence/migrating-orcad-catalog/orcad-scrollback-snapshot-transfer.ts +11 src/main/persistence/migrating-orcad-catalog/orcad-shell-history-installer.ts +7 src/main/persistence/migrating-orcad-catalog/orcad-terminal-history-installer.ts +1 src/main/persistence/migrating-orcad-catalog/orcad-terminal-restore-hint-store.ts +1 src/main/persistence/moving-wsl-projects/wsl-move-orchestration-history-rewrite.ts +1 src/main/persistence/moving-wsl-projects/wsl-move-orchestrator-store.ts +6 src/main/persistence/moving-wsl-projects/wsl-move-slept-scrollback.ts +2 src/main/persistence/moving-wsl-projects/wsl-move-slept-spool-sweep.ts +5 src/main/persistence/preferences/active-view-preference.ts +4 src/main/persistence/profile-state/legacy-json/profile-state-authority-exports.ts +2 src/main/persistence/profile-state/legacy-json/profile-state-export-path.ts +1 src/main/persistence/profile-state/legacy-json/profile-state-legacy-backup-path.ts +2 src/main/persistence/profile-state/legacy-json/profile-state-legacy-import.ts +8 src/main/persistence/profile-state/legacy-json/profile-state-recovery.ts +6 src/main/persistence/profile-state/legacy-json/profile-state-versioned-export.ts +5 src/main/persistence/profile-state/profile-state-access-identity.ts +12 src/main/persistence/profile-state/profile-state-access-owner.ts +3 src/main/persistence/profile-state/profile-state-access.ts +2 src/main/persistence/profile-state/profile-state-active-location.ts +5 src/main/persistence/profile-state/profile-state-authority-bootstrap.ts +1 src/main/persistence/profile-state/profile-state-authority-marker.ts +2 src/main/persistence/profile-state/profile-state-backup-path.ts +2 src/main/persistence/profile-state/profile-state-backup-worker.ts +5 src/main/persistence/profile-state/profile-state-database-quarantine.ts +9 src/main/persistence/profile-state/profile-state-database-recovery.ts +2 src/main/persistence/profile-state/profile-state-database.ts +4 src/main/persistence/profile-state/profile-state-migration.ts +6 src/main/persistence/profile-state/profile-state-offline-settings.ts +6 src/main/persistence/profile-state/profile-state-recovery-command.ts +8 src/main/persistence/profile-state/profile-state-recovery-copy.ts +2 src/main/persistence/profile-state/profile-state-recovery-crash-process.ts +1 src/main/persistence/profile-state/profile-state-recovery-required.ts +2 src/main/persistence/profile-state/profile-state-section-repair.ts +2 src/main/persistence/profile-state/profile-state-sqlite-authority.ts +1 src/main/persistence/profile-state/profile-state-startup-recovery-dialog.ts +2 src/main/persistence/profile-state/profile-state-storage-classification.ts +1 src/main/persistence/profile-state/profile-state-writer-worker-path.ts +2 src/main/persistence/restoring-sessions/floating-workspace-normalization.ts +1 src/main/persistence/tracking-repos/worktree-metadata-normalization.ts +1 src/main/persistence/window-save-divergence.ts +8 src/main/pi/legacy-omp-overlay-migration.ts +5 src/main/pi/titlebar-extension-service.ts +3 src/main/plugins/appearance/plugin-appearance-service.ts +2 src/main/plugins/installation/plugin-install-staging.ts +1 src/main/plugins/installation/plugin-install.ts +1 src/main/plugins/panels/plugin-frame-guest-sessions.ts +1 src/main/plugins/panels/plugin-source-transpile-client.ts +2 src/main/plugins/plugin-dev-watcher.ts +3 src/main/plugins/plugin-secrets-store.ts +3 src/main/plugins/plugin-storage-store.ts +1 src/main/plugins/testing/plugin-editor-static-check.ts +1 src/main/plugins/workers/plugin-host-process.ts +3 src/main/plugins/workers/plugin-worker-source-hooks.ts +8 src/main/ports/darwin-port-scan-lock.ts +1 src/main/ports/port-scan-command-client.ts +1 src/main/ports/port-scan-command-execution.ts +2 src/main/provider-process/provider-executable-missing.ts +5 src/main/providers/local-pty/local-pty-executable-spawn.ts +1 src/main/providers/local-pty/local-pty-session-operations.ts +1 src/main/providers/local-pty/local-pty-shell-ready-wrapper-root.ts +1 src/main/providers/macos-login-session-pty-probe.ts +3 src/main/providers/macos-tcc-login-shell.ts +3 src/main/providers/windows-powershell-executable.ts +2 src/main/providers/working-directory-validation.ts +4 src/main/pty/history/fish-history-session.ts +4 src/main/pty/history/terminal-history-deletion.ts +2 src/main/pty/history/terminal-history-paths.ts +5 src/main/pty/history/terminal-history.ts +1 src/main/pty/process-retirement/posix-pty-process-table.ts +12 src/main/pty/scrollback/overlay-mirror.ts +1 src/main/pty/scrollback/terminal-scrollback-snapshot-nonblocking-reads.ts +11 src/main/pty/scrollback/terminal-scrollback-snapshots.ts +2 src/main/pty/shell-startup/codex-shell-launch-preflight.ts +7 src/main/pty/shell-startup/git-bash.ts +3 src/main/pty/shell-startup/legacy-terminal-posix-tombstone.ts +9 src/main/pty/shell-startup/legacy-terminal-shim-dir.ts +1 src/main/pty/shell-startup/managed-ssh-host-login-shell.ts +1 src/main/pty/shell-startup/powershell-profile-env.ts +3 src/main/pty/shell-startup/shell-startup-env.ts +5 src/main/pty/shell-startup/shell-wrapper-file-writer.ts +6 src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts +2 src/main/pty/shell-startup/zsh-wrapper-dir-ownership.ts +1 src/main/qoder/workspace-trust.ts +4 src/main/rate-limits/cursor-auth.ts +2 src/main/rate-limits/grok-auth.ts +3 src/main/rate-limits/hidden-probe-cwd.ts +2 src/main/rate-limits/opencode-go-api-key-source.ts +1 src/main/rate-limits/zcode-usage-credentials.ts +3 src/main/ripgrep/bundled-ripgrep-path.ts +8 src/main/runtime/agent-session/ownership/agent-session-claim-identity.ts +1 src/main/runtime/agent-session/records/agent-session-record-store-slot.ts +7 src/main/runtime/agent-session/records/agent-session-runtime-end-record.ts +1 src/main/runtime/agent-session/structured-agent-session-attachment-wiring.ts +1 src/main/runtime/client/navigation/desktop-chat-creation-history.ts +4 src/main/runtime/hosts/platform-probe/host-descriptor.ts +5 src/main/runtime/mobile-cloud-relay/relay-region-preference.ts +2 src/main/runtime/mobile-cloud-relay/relay-revoke-outbox.ts +1 src/main/runtime/orchestration/db/runtime-orchestration-database-access.ts +1 src/main/runtime/push/notifications/mobile-notification-dismissal-store.ts +2 src/main/runtime/push/push-unregister-outbox.ts +2 src/main/runtime/rpc/methods/mobile-delivery/bundled-mobile-web-bundle.ts +1 src/main/runtime/rpc/server/network-source-policy-store.ts +2 src/main/runtime/rpc/server/pairing/device-registry-corruption.ts +2 src/main/runtime/rpc/server/pairing/device-registry-disk-merge.ts +1 src/main/runtime/rpc/server/pairing/device-registry-file-read.ts +3 src/main/runtime/rpc/server/pairing/e2ee-keypair.ts +3 src/main/runtime/rpc/server/runtime-metadata.ts +2 src/main/runtime/rpc/server/runtime-rpc-socket-metadata.ts +5 src/main/runtime/rpc/unix-socket-transport.ts +3 src/main/runtime/rpc/ws-fallback-port-store.ts +2 src/main/runtime/terminal/launch/claude-agent-teams-shim-env.ts +1 src/main/runtime/workspaces/persisted-surfaces/crew-operations.ts +1 src/main/server/serve-pairing-output.ts +2 src/main/speech/model-cache-path.ts +9 src/main/speech/model-manager.ts +10 src/main/speech/openai-api-key-store.ts +2 src/main/speech/speech-model-download-cleanup.ts +1 src/main/speech/speech-model-download-transport.ts +2 src/main/speech/speech-model-http-download.ts +1 src/main/speech/stt-worker-model-config.ts +2 src/main/speech/stt-worker-paths.ts +2 src/main/sqlite/harden-database-files.ts +1 src/main/sqlite/sync-database.ts +1 src/main/sqlite/versioned-cache-database.ts +1 src/main/ssh/authentication/ssh-auth-resolution.ts +2 src/main/ssh/config/ssh-config-alias-claim.ts +5 src/main/ssh/config/ssh-config-include-expander.ts +1 src/main/ssh/config/ssh-config-parser.ts +1 src/main/ssh/config/ssh-g-config-resolution.ts +3 src/main/ssh/system-transport/file-transfer/system-ssh-sftp-transfer.ts +3 src/main/ssh/system-transport/ssh-control-socket.ts +3 src/main/ssh/system-transport/system-ssh-binary.ts +3 src/main/startup/cli-launch-redirect.ts +2 src/main/startup/configure-process.ts +4 src/main/startup/gpu-fallback-marker.ts +2 src/main/startup/http1-compatibility-marker.ts +5 src/main/startup/http1-compatibility-profile-state.ts +1 src/main/startup/linux-dev-shm-policy.ts +4 src/main/startup/linux-realtime-scheduling-guard.ts +1 src/main/startup/linux-rttime-limit.ts +2 src/main/startup/profile-state-recovery-preflight.ts +1 src/main/startup/startup-diagnostics.ts +1 src/main/startup/windows-app-data-path.ts +5 src/main/startup/windows-install-dir-acl-poison-marker.ts +1 src/main/startup/windows-install-dir-acl-probe.ts +1 src/main/startup/windows-install-dir-package-acl-grant.ts +4 src/main/startup/windows-install-dir-package-acl-repair.ts +3 src/main/startup/windows-renderer-runtime-files.ts +3 src/main/startup/windows-user-data-acl.ts +6 src/main/startup/x-display-artifacts.ts +2 src/main/stats/stats-file-loader.ts +2 src/main/text-generation/source-control-prompt-files.ts +1 src/main/updater/lifecycle/windows-update-install-directory.ts +9 src/main/updater/linux-package/appimage-runtime-identity.ts +1 src/main/updater/linux-package/linux-package-install-command.ts +1 src/main/updater/linux-package/linux-update-package-type.ts +6 src/main/updater/serve-update-handoff.ts +2 src/main/usage/usage-provider-store-lifecycle.ts +1 src/main/usage/usage-scan-worker-spawn.ts +1 src/main/warp-themes/discovery.ts +1 src/main/window/desktop-integration/custom-app-icon.ts +3 src/main/window/desktop-integration/macos-press-and-hold-default.ts +1 src/main/windows/windows-administrator-restart.ts +1 src/main/windows/windows-command-paths.ts +1 src/main/windows/windows-process-table.ts +1 src/main/worker-thread-child-process/worker-thread-child-process.ts +2 src/main/worker-threads/forked-child-entry-path.ts +4 src/main/workspace-hooks/hooks.ts +10 src/main/workspace-hooks/issue-command-file.ts +4 src/main/workspace-hooks/worktree-runner-script.ts +1 src/main/workspaces/catalog/folder-repo-git-conversion.ts +2 src/main/workspaces/catalog/folder-upgrade-worktree-path.ts +3 src/main/workspaces/execution-host/project-runtime-git-router.ts +1 src/main/workspaces/space-analysis/workspace-space-scan-worker-client.ts +1 src/main/wsl/execution/wsl-executable-path.ts +1 src/main/wsl/execution/wsl-interop-spawn-directory.ts +1 src/main/wsl/execution/wsl-node-runtime-prefetch.ts +3 src/main/wsl/filesystem/wsl-drive-project-new-default.ts +10 src/main/wsl/filesystem/wsl-drive-unc-conversion-stores.ts +2 src/main/wsl/host-lifecycle/wsl-host-automation-wake-store.ts +4 src/main/wsl/host-lifecycle/wsl-host-e2e-fake-connector.ts +1 src/main/wsl/host-lifecycle/wsl-host-early-wake.ts +1 src/main/wsl/host-lifecycle/wsl-orphan-holder-release.ts +1 src/main/zcode/hook-config-json.ts +12 src/main/zcode/zcode-plan-api-key-store.ts +6 src/shared/agent-hook-listener/claude-session-continuation.ts +4 src/shared/agent-hook-listener/reverse-file-region-scan.ts +3 src/shared/agent-hook-listener/transcript-reader.ts +3 src/shared/agent-hook-listener/transport/agent-hook-endpoint-temp-cleanup.ts +13 src/shared/agent-hook-listener/transport/agent-hook-spool.ts +5 src/shared/agent-hook-listener/transport/endpoint-publication.ts +4 src/shared/agent-launch/startup/omp-fresh-config.ts +2 src/shared/appimage-cache-identity.ts +2 src/shared/bundled-web-client-manifest.ts +3 src/shared/bundled-web-client-root.ts +5 src/shared/cli-fs-reads.ts +3 src/shared/cli-runtime-pairing-inputs.ts +9 src/shared/codex-rollout-jsonl-cursor.ts +1 src/shared/codex-subagent-roster.ts +4 src/shared/ephemeral-vm-recipe-doctor.ts +1 src/shared/ephemeral-vm-recipe-runner.ts +1 src/shared/ephemeral-vm-runtime-feature-store.ts +1 src/shared/ephemeral-vm-runtime-store.ts +6 src/shared/file-content/node-bounded-file-reader.ts +5 src/shared/file-content/node-file-content-equality.ts +6 src/shared/file-content/node-source-copy-content-equality.ts +3 src/shared/grok-session-paths.ts +2 src/shared/jcode-session-files.ts +1 src/shared/muse-session-log.ts +1 src/shared/opencode-installed-plugin.ts +10 src/shared/opencode-plugin-atomic-write.ts +5 src/shared/opencode-tui-config-registration.ts +1 src/shared/opencode-tui-plugin-install.ts +2 src/shared/orcad-build-identity.ts +1 src/shared/plugins/declarative/testing/orca-testing.ts +2 src/shared/real-path-sync.ts +1 src/shared/remote-runtime/e2ee/node/remote-runtime-e2ee-v2-host-latch.ts +1 src/shared/remote-runtime/host-store/runtime-e2ee-keypair-file.ts +1 src/shared/remote-runtime/host-store/runtime-environment-sidecar.ts +2 src/shared/remote-runtime/host-store/runtime-environment-store-read-cache.ts +2 src/shared/remote-runtime/host-store/runtime-environment-store-records.ts +1 src/shared/remote-runtime/host-store/wsl-host-deployment-store.ts +13 src/shared/secure-storage/secure-file.ts +1 src/shared/secure-storage/secure-path-metadata-snapshot.ts +1 src/shared/secure-storage/secure-path-windows-acl.ts +3 src/shared/serve-abort-park.ts +7 src/shared/serve-bundle-park.ts +1 src/shared/serve-user-data-path.ts +3 src/shared/source-scan/source-tree-scan.ts +5 src/shared/startup-command-staging.ts +1 src/shared/terminal/pty/native-process/pty-process-ceiling-state.ts +8 src/shared/windows-breakaway-launcher.ts +3 src/shared/windows-console-input.ts +2 src/shared/windows-interactive-login-spawn.ts +2 src/shared/windows-retry-file-operations.ts +2 src/shared/windows-security-addon.ts +1 src/shared/windows-transient-lock-removal.ts diff --git a/config/performance-audit.md b/config/performance-audit.md index 3a11b03e7e8..e414cb79ba2 100644 --- a/config/performance-audit.md +++ b/config/performance-audit.md @@ -54,3 +54,11 @@ identity, queue-admission or retained-memory oracle. Confirm it fails with the old behavior. Use controlled, counterbalanced benchmark samples for timings; avoid new machine-dependent millisecond gates in the normal unit suite. A green source scan and these contracts cannot establish that the whole app is fast. + +Two count ratchets (counts per file may only fall) cover classes the audit only warns about: +`pnpm check:main-sync-fs-ratchet` counts synchronous `node:fs` calls (every `*Sync` export) in production `src/main` and `src/shared` +(`config/main-sync-fs-baseline.txt`), and `pnpm check:recurring-timer-ratchet` counts `setInterval` +calls in production `src/main`, `src/renderer`, `src/shared` and `src/cli` +(`config/recurring-timer-baseline.txt`). Both run in `check:ratchets` on every non-draft PR that runs static analysis. A new use either +moves off the hot path (async fs or a stat-fingerprint cache; a push signal, a visibility-gated or +backing-off timer) or raises its file's count with reviewer sign-off. diff --git a/config/recurring-timer-baseline.txt b/config/recurring-timer-baseline.txt new file mode 100644 index 00000000000..4f313845137 --- /dev/null +++ b/config/recurring-timer-baseline.txt @@ -0,0 +1,92 @@ +# setInterval calls (global, or imported from node:timers / node:timers/promises) in production src/main, +# src/renderer, src/shared and src/cli, per file. Bare calls are resolved per scope; imported bindings follow the shared +# collector (file-wide). Not counted: destructuring off a global object, a self-rescheduling setTimeout (it must back off or pause while hidden). +# This is a RATCHET: counts may only go DOWN. +# Prune after removing intervals: pnpm check:recurring-timer-ratchet --prune +1 src/cli/handlers/orchestration/check-keepalive.ts +1 src/cli/runtime/mac-app-update-bundle.ts +1 src/cli/runtime/serve-supervised-service.ts +1 src/main/agent-hooks/server/server-opencode-binder.ts +1 src/main/automations/retained-run-reconciliation.ts +1 src/main/automations/service.ts +1 src/main/browser/extensions/native-messaging/browser-extension-native-ports.ts +1 src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts +1 src/main/claude/agent-view/agent-view-bridge.ts +1 src/main/cli/appimage-serve-preparation.ts +1 src/main/codex-accounts/codex-login-session.ts +1 src/main/codex/configuration/homes/codex-windows-sandbox-read-grant.ts +1 src/main/crash-reporting/pre-gone-host-memory.ts +1 src/main/crash-reporting/process-gone-diagnostics.ts +1 src/main/crash-reporting/renderer-heap-allocation-profile.ts +1 src/main/daemon/admission/host-terminal-ledger.ts +1 src/main/daemon/admission/host-terminal-policy.ts +1 src/main/daemon/endpoint/publication/daemon-endpoint-lifecycle.ts +1 src/main/daemon/transport/stream/daemon-stream-backlog-probe.ts +1 src/main/diagnostics/event-loop-delay-probe.ts +1 src/main/diagnostics/main-thread-churn-probe.ts +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 +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 +1 src/main/ipc/wsl/wsl-host-automation-wake-wiring.ts +1 src/main/native-chat/agent-session-attachments/agent-session-attachment-sweep.ts +1 src/main/native-chat/agent-session-wire/host/structured-agent-session-lease-renewer.ts +1 src/main/native-chat/agent-session-wire/recovery/structured-agent-session-usage-limit-continue.ts +1 src/main/native-chat/agent-session-wire/termination/structured-agent-session-idle-sweep.ts +1 src/main/notifications/desktop-presence-reporter.ts +1 src/main/orcad/orcad-browser-install-park.ts +1 src/main/orcad/orcad-lock-clone-machine.ts +1 src/main/orcad/orcad-stop-request-listener.ts +1 src/main/plugins/catalog/plugin-auto-updater.ts +1 src/main/plugins/catalog/plugin-kill-list-service.ts +1 src/main/plugins/installation/plugin-git-repository.ts +1 src/main/plugins/plugin-service-housekeeping.ts +1 src/main/rate-limits/service/service-polling.ts +1 src/main/runtime/agent-state-rules/agent-state-rules-live-update.ts +1 src/main/runtime/mobile-cloud-relay/desktop-relay-service.ts +2 src/main/runtime/mobile-cloud-relay/relay-control-liveness.ts +1 src/main/runtime/rpc/methods/orchestration/messaging/check-run.ts +1 src/main/runtime/rpc/mobile-socket-wiring.ts +1 src/main/runtime/rpc/remote-runtime-server-heartbeat.ts +1 src/main/runtime/rpc/server/runtime-metadata-ownership-watch.ts +1 src/main/runtime/rpc/unix-socket-transport.ts +1 src/main/runtime/sidebar-inputs/paired-server-rows-producer.ts +1 src/main/runtime/terminal/input/agent-prompt-permission-hold.ts +1 src/main/runtime/terminal/output/terminal-derived-agent-facts.ts +1 src/main/runtime/terminal/wait/terminal-idle-polls.ts +1 src/main/ssh/legacy-relay/bridge/legacy-relay-daily-activity.ts +1 src/main/ssh/legacy-relay/cli/legacy-relay-cli-call-limits.ts +1 src/main/ssh/port-forwarding/ssh-tcp-forwarding-probe.ts +1 src/main/ssh/protocol/ssh-channel-multiplexer.ts +1 src/main/startup/configure-process.ts +1 src/main/startup/event-loop-stall-probe.ts +1 src/main/startup/synthetic-title-runtime.ts +1 src/main/telemetry/wsl-usage-reporter.ts +1 src/main/wsl/host-lifecycle/wsl-hosts-policy-live-update.ts +1 src/main/wsl/orcad/wsl-orcad-connect-stop-fence.ts +1 src/renderer/src/app-shell/use-app-session-persistence.ts +1 src/renderer/src/components/browser-pane/browser-client-page-position-driver.ts +1 src/renderer/src/components/contextual-tours/use-contextual-tour.ts +1 src/renderer/src/components/editor/setup-contextual-copy.ts +1 src/renderer/src/components/right-sidebar/plugin-panels/health/plugin-panel-watchdog.ts +1 src/renderer/src/components/sidebar/SeveredTerminalDaemonBanner.tsx +1 src/renderer/src/components/sidebar/StalledTerminalDaemonBanner.tsx +1 src/renderer/src/components/sidebar/workspace-card/activity/prompt-cache-countdown-clock.ts +1 src/renderer/src/components/status-bar/use-resource-memory-snapshot.ts +1 src/renderer/src/components/status-bar/use-runtime-host-resources.ts +1 src/renderer/src/components/tab-bar/tab-strip-drag-scroll.ts +1 src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.ts +1 src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/recovery/RemoteRuntimeRecoveryCard.tsx +1 src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.ts +1 src/renderer/src/hooks/use-now.ts +1 src/renderer/src/lib/agent-session/hibernation/agent-hibernation-coordinator.ts +1 src/renderer/src/lib/crash-diagnostics.ts +1 src/renderer/src/lib/window-visibility-interval.ts +1 src/renderer/src/lib/worker-auto-close.ts +1 src/renderer/src/runtime/hosts/wsl/wsl-refused-read-watch.ts +1 src/shared/remote-runtime/remote-runtime-socket-liveness.ts +1 src/shared/tmux-agent-hook-owner.ts diff --git a/config/scripts/preflight/changed-checks/check-changed-selection.mjs b/config/scripts/preflight/changed-checks/check-changed-selection.mjs index 14eae82cea5..3bf510cc912 100644 --- a/config/scripts/preflight/changed-checks/check-changed-selection.mjs +++ b/config/scripts/preflight/changed-checks/check-changed-selection.mjs @@ -35,8 +35,15 @@ const RATCHET_INPUTS = { 'check-host-list-render-ratchet.mjs': ['src/renderer/src/'], 'check-id-only-store-write-ratchet.mjs': ['src/main/persistence/'], 'check-layout-writer-ratchets.mjs': ['src/main/', 'src/renderer/src/'], + 'check-main-sync-fs-ratchet.mjs': ['src/main/', 'src/shared/'], 'check-main-sync-spawn-ratchet.mjs': ['src/main/'], 'check-react-compiler-compat-ratchet.mjs': ['src/renderer/src/'], + 'check-recurring-timer-ratchet.mjs': [ + 'src/main/', + 'src/renderer/src/', + 'src/shared/', + 'src/cli/' + ], 'check-render-path-translate-ratchet.mjs': ['src/renderer/src/'], 'check-repo-host-read-ratchet.mjs': ['src/cli/', 'src/main/', 'src/shared/'], 'check-runtime-electron-ratchet.mjs': ['src/main/', 'src/cli/', 'src/shared/'], @@ -258,7 +265,9 @@ export function selectTypecheckProjects(files) { const RATCHET_SHARED_MODULES = { 'config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs': [ 'check-daemon-blocking-call-ratchet.mjs', - 'check-main-sync-spawn-ratchet.mjs' + 'check-main-sync-fs-ratchet.mjs', + 'check-main-sync-spawn-ratchet.mjs', + 'check-recurring-timer-ratchet.mjs' ], 'config/scripts/static-analysis/ratchets/react-compiler/react-compiler-hazards.mjs': [ 'check-react-compiler-compat-ratchet.mjs' diff --git a/config/scripts/preflight/changed-checks/run-lint.mjs b/config/scripts/preflight/changed-checks/run-lint.mjs index 7b3d7be3632..0a2bbe3c723 100644 --- a/config/scripts/preflight/changed-checks/run-lint.mjs +++ b/config/scripts/preflight/changed-checks/run-lint.mjs @@ -41,6 +41,8 @@ export const LINT_STEPS = [ 'check:workspace-record-read-ratchet', 'check:unproven-pty-retirement-ratchet', 'check:daemon-blocking-call-ratchet', + 'check:main-sync-fs-ratchet', + 'check:recurring-timer-ratchet', 'check:node-runtime-pin', 'check:path-literal-ratchet', 'check:host-list-render-ratchet', diff --git a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs index 01fce47e89b..15c416efd14 100644 --- a/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs +++ b/config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.test.mjs @@ -77,12 +77,12 @@ describe('main sync-spawn ratchet', () => { ], [ "const { execSync } = require('child_process')\nconst run = execSync\nrun('a')", - 2, + 1, ['execSync'] ], [ "function f() { const run = cp.execSync; run('a') }\nconst cp = require('child_process')", - 2, + 1, ['execSync'] ], [ @@ -91,10 +91,18 @@ describe('main sync-spawn ratchet', () => { ['execFileSync'] ], [ - "import { runProcessSync } from '@orca/process-host'\nconst run = runProcessSync", + "import { runProcessSync } from '@orca/process-host'\nconst run = runProcessSync\nrun(a)", 1, ['runProcessSync'] - ] + ], + // Binding an alias is setup; each call through it is a use, so an alias refactor keeps the count. + [ + "import { execSync } from 'child_process'\nconst run = execSync\nrun('a')\nrun('b')", + 2, + ['execSync'] + ], + ["import { execSync } from 'child_process'\nexport const run = execSync", 1, ['execSync']], + ["import { execSync } from 'child_process'\nconst out = execSync('a')", 1, ['execSync']] ])('counts %s', (source, count, symbols) => { expect(uses(source)).toEqual({ count, symbols }) }) diff --git a/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs b/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs index da92736ba0a..e17bb894adf 100644 --- a/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs +++ b/config/scripts/static-analysis/process-boundaries/gated-call-use-collector.mjs @@ -38,6 +38,15 @@ function isValueReference(node) { ) } +function isExportedDeclaration(declaration) { + const statement = declaration.parent?.parent + return ( + !!statement && + ts.isVariableStatement(statement) && + !!statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) + ) +} + /** * Each family lists module specifiers (packages, or repo paths without extension) and the gated * exports to count, each with advice for the failure message. @@ -72,7 +81,7 @@ export function createGatedCallCollector(families, ratchetName) { ) } - // Count each gated value reference, alias use and re-export; imports alone do not count. + // Count each gated value reference, alias use and re-export; imports and plain alias bindings alone do not count. // File-wide, not scope-aware: computed specifiers/members and non-const holder flows are unresolved; local wrappers are not traced. function collectUses(file, contents) { // Escaped spellings and relative imports inside gated modules still need the full analysis. @@ -197,7 +206,7 @@ export function createGatedCallCollector(families, ratchetName) { identifiers.push(node) } else if (ts.isVariableDeclaration(node) && node.initializer) { if (ts.isIdentifier(node.name)) { - aliases.push({ name: node.name.text, initializer: node.initializer }) + aliases.push({ name: node.name.text, initializer: node.initializer, declaration: node }) } else if (ts.isObjectBindingPattern(node.name)) { destructures.push(node) } @@ -236,14 +245,30 @@ export function createGatedCallCollector(families, ratchetName) { } } } + // Binding a tracked alias is setup, not a use: its calls are charged instead, so an alias refactor + // keeps the count. Conditional/fallback aliases and exported bindings stay charged (conservative). + const aliasSetup = new Set() + for (const { name, initializer, declaration } of aliases) { + const target = unwrap(initializer) + if ( + functions.has(name) && + (ts.isIdentifier(target) || + ts.isPropertyAccessExpression(target) || + ts.isElementAccessExpression(target)) && + gatedFunction(target) && + !isExportedDeclaration(declaration) + ) { + aliasSetup.add(target) + } + } for (const node of members) { const name = propertyName(node) - if (moduleSymbols(node.expression)?.has(name)) { + if (!aliasSetup.has(node) && moduleSymbols(node.expression)?.has(name)) { recordUse(name) } } for (const node of identifiers) { - const name = functions.get(node.text) + const name = aliasSetup.has(node) ? null : functions.get(node.text) if (name) { recordUse(name) } diff --git a/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs new file mode 100644 index 00000000000..82ad501f702 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs @@ -0,0 +1,115 @@ +import process from 'node:process' +import { pathToFileURL } from 'node:url' +import { createGatedCallCollector } from '../../process-boundaries/gated-call-use-collector.mjs' +import { readTrackedSources, runCountRatchet } from '../../ratchet-baseline/ratchet-baseline.mjs' +import { isTestOnlySourcePath } from '../../process-boundaries/test-only-source-path.mjs' + +// Sync fs on Electron main stalls every window (and in the daemon/orcad, every terminal); per-spawn/RPC/focus stat and read sweeps were a recurring lag source (#39805, #35967, #38481). + +const BASELINE_PATH = 'config/main-sync-fs-baseline.txt' +// src/shared runs on main too; leaving it out would let a helper move bypass the gate. +const SCAN_ROOTS = ['src/main', 'src/shared'] +const ADVICE = + 'use node:fs/promises, or cache the result on a stat fingerprint outside the hot path' +// Every *Sync export of node:fs (descriptor and copy APIs included), listed so the baseline doesn't depend on the runtime. +const SYNC_FS = [ + 'accessSync', + 'appendFileSync', + 'chmodSync', + 'chownSync', + 'closeSync', + 'copyFileSync', + 'cpSync', + 'existsSync', + 'fchmodSync', + 'fchownSync', + 'fdatasyncSync', + 'fstatSync', + 'fsyncSync', + 'ftruncateSync', + 'futimesSync', + 'globSync', + 'lchmodSync', + 'lchownSync', + 'linkSync', + 'lstatSync', + 'lutimesSync', + 'mkdirSync', + 'mkdtempDisposableSync', + 'mkdtempSync', + 'openSync', + 'opendirSync', + 'readFileSync', + 'readSync', + 'readdirSync', + 'readlinkSync', + 'readvSync', + 'realpathSync', + 'renameSync', + 'rmSync', + 'rmdirSync', + 'statSync', + 'statfsSync', + 'symlinkSync', + 'truncateSync', + 'unlinkSync', + 'utimesSync', + 'writeFileSync', + 'writeSync', + 'writevSync' +] +const collector = createGatedCallCollector( + [ + { + modules: ['fs', 'node:fs', 'original-fs', 'graceful-fs'], + advice: Object.fromEntries(SYNC_FS.map((name) => [name, ADVICE])) + } + ], + 'main sync-fs' +) + +function isScannedPath(rel) { + return /\.[cm]?[jt]sx?$/.test(rel) && !rel.endsWith('.d.ts') && !isTestOnlySourcePath(rel) +} + +export function countSyncFsCalls(rel, source) { + return collector.collectUses(rel, source).count +} + +export function collectMainSyncFsCounts(root = process.cwd()) { + const counts = new Map() + for (const [rel, source] of readTrackedSources(root, SCAN_ROOTS, isScannedPath)) { + const count = countSyncFsCalls(rel, source) + if (count > 0) { + counts.set(rel, count) + } + } + return counts +} + +export function main(root = process.cwd(), arg = undefined) { + return runCountRatchet( + { + name: 'main-sync-fs', + baselinePath: BASELINE_PATH, + header: [ + '# Synchronous node:fs calls (every *Sync export) in production src/main and src/shared, per file.', + '# Startup-only or one-shot uses are fine to keep; per-RPC, per-spawn, per-focus or per-poll uses are the target.', + '# This is a RATCHET: counts may only go DOWN.', + '# Prune after removing calls: pnpm check:main-sync-fs-ratchet --prune' + ], + collect: collectMainSyncFsCounts, + unit: 'sync fs call(s)', + fix: [ + `Sync fs blocks the thread it runs on: Electron main (every window) or the daemon/orcad loop (every terminal). ${ADVICE}.`, + `A one-shot startup or shutdown use may raise the file's count in ${BASELINE_PATH} with reviewer sign-off.` + ] + }, + root, + arg + ) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit(main(process.cwd(), process.argv[2])) +} diff --git a/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs new file mode 100644 index 00000000000..e038949c153 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs @@ -0,0 +1,168 @@ +import process from 'node:process' +import { pathToFileURL } from 'node:url' +import ts from 'typescript-api' +import { createGatedCallCollector } from '../../process-boundaries/gated-call-use-collector.mjs' +import { readTrackedSources, runCountRatchet } from '../../ratchet-baseline/ratchet-baseline.mjs' +import { isTestOnlySourcePath } from '../../process-boundaries/test-only-source-path.mjs' + +// Fixed-cadence polls that never back off, settle or pause while hidden were the most common perf fix class (#39734, #38902, #33829, #39650). + +const BASELINE_PATH = 'config/recurring-timer-baseline.txt' +const SCAN_ROOTS = ['src/main', 'src/renderer/src', 'src/shared', 'src/cli'] +const TIMER_HOSTS = new Set(['window', 'globalThis', 'self', 'global']) +const TIMER_MODULES = ['timers', 'node:timers', 'timers/promises', 'node:timers/promises'] +const timerImports = createGatedCallCollector( + [ + { + modules: TIMER_MODULES, + advice: { setInterval: 'prefer a push signal or a backing-off timer' } + } + ], + 'recurring-timer' +) + +function isScannedPath(rel) { + return /\.[cm]?[jt]sx?$/.test(rel) && !rel.endsWith('.d.ts') && !isTestOnlySourcePath(rel) +} + +function isHostInterval(node) { + if (!ts.isIdentifier(node.expression) || !TIMER_HOSTS.has(node.expression.text)) { + return false + } + if (ts.isPropertyAccessExpression(node)) { + return node.name.text === 'setInterval' + } + return ( + ts.isElementAccessExpression(node) && + ts.isStringLiteralLike(node.argumentExpression) && + node.argumentExpression.text === 'setInterval' + ) +} + +// Skips transparent wrappers so `typeof (setInterval)` and `(setInterval) = x` read like the bare forms. +function outerExpression(node) { + let current = node + while (ts.isParenthesizedExpression(current.parent)) { + current = current.parent + } + return current +} + +// Reads the timer value: not a plain `=` target (compound assignments read it), a `typeof` probe or a JSX tag name. +function isRuntimeRead(node) { + const outer = outerExpression(node) + const parent = outer.parent + return !( + ts.isTypeOfExpression(parent) || + (ts.isBinaryExpression(parent) && + parent.left === outer && + parent.operatorToken.kind === ts.SyntaxKind.EqualsToken) || + ((ts.isJsxOpeningElement(parent) || + ts.isJsxSelfClosingElement(parent) || + ts.isJsxClosingElement(parent)) && + parent.tagName === node) + ) +} + +// A value reference to the identifier, not a declaration, member name or key. +function isBareValueReference(node) { + const parent = node.parent + return ( + isRuntimeRead(node) && + !( + (ts.isPropertyAccessExpression(parent) && parent.name === node) || + (ts.isPropertyAssignment(parent) && parent.name === node) || + ts.isImportSpecifier(parent) || + ts.isExportSpecifier(parent) || + (ts.isBindingElement(parent) && (parent.name === node || parent.propertyName === node)) || + (ts.isVariableDeclaration(parent) && parent.name === node) || + (ts.isParameter(parent) && parent.name === node) || + ((ts.isFunctionDeclaration(parent) || ts.isMethodDeclaration(parent)) && parent.name === node) + ) + ) +} + +const SCOPE_OPTIONS = { noLib: true, noResolve: true, allowJs: true, types: [] } + +// Counts references, not calls, to the global timer, so `const every = setInterval; every(f)` and +// `window['setInterval']` are charged once. A bare name is the global when it binds to nothing +// declared in this file (resolved per scope); module bindings and their aliases are the collector's. +function countGlobalTimerReferences(source) { + const host = ts.createCompilerHost(SCOPE_OPTIONS) + host.getSourceFile = (name) => (name === source.fileName ? source : undefined) + const checker = ts.createProgram([source.fileName], SCOPE_OPTIONS, host).getTypeChecker() + let count = 0 + const visit = (node) => { + if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) { + return + } + if ( + (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && + isHostInterval(node) && + isRuntimeRead(node) + ) { + count += 1 + } else if (ts.isIdentifier(node) && node.text === 'setInterval' && isBareValueReference(node)) { + // A shorthand `{ setInterval }` names the property; its value is the binding being read. + const symbol = ts.isShorthandPropertyAssignment(node.parent) + ? checker.getShorthandAssignmentValueSymbol(node.parent) + : checker.getSymbolAtLocation(node) + const declarations = symbol?.declarations ?? [] + if (!declarations.some((declaration) => declaration.getSourceFile() === source)) { + count += 1 + } + } + ts.forEachChild(node, visit) + } + visit(source) + return count +} + +export function countRecurringTimers(rel, source) { + if (!source.includes('setInterval')) { + return 0 + } + const file = ts.createSourceFile(rel, source, ts.ScriptTarget.Latest, true) + return countGlobalTimerReferences(file) + timerImports.collectUses(rel, source).count +} + +export function collectRecurringTimerCounts(root = process.cwd()) { + const counts = new Map() + for (const [rel, source] of readTrackedSources(root, SCAN_ROOTS, isScannedPath)) { + const count = countRecurringTimers(rel, source) + if (count > 0) { + counts.set(rel, count) + } + } + return counts +} + +export function main(root = process.cwd(), arg = undefined) { + return runCountRatchet( + { + name: 'recurring-timer', + baselinePath: BASELINE_PATH, + header: [ + '# setInterval calls (global, or imported from node:timers / node:timers/promises) in production src/main,', + '# src/renderer, src/shared and src/cli, per file. Bare calls are resolved per scope; imported bindings follow the shared', + '# collector (file-wide). Not counted: destructuring off a global object, a self-rescheduling setTimeout (it must back off or pause while hidden).', + '# This is a RATCHET: counts may only go DOWN.', + '# Prune after removing intervals: pnpm check:recurring-timer-ratchet --prune' + ], + collect: collectRecurringTimerCounts, + unit: 'setInterval call(s)', + fix: [ + 'A fixed-cadence interval keeps working when nothing changes, the window is hidden or its dependency keeps failing.', + 'Prefer a push signal; otherwise use installWindowVisibilityInterval (renderer) or a timer that backs off and stops when idle.', + 'Rewriting it as a self-rescheduling setTimeout at the same fixed cadence is the same bug; review will treat it so.', + `An interval whose cadence is the feature (a clock, a heartbeat with a stop) may raise the file's count in ${BASELINE_PATH} with reviewer sign-off.` + ] + }, + root, + arg + ) +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exit(main(process.cwd(), process.argv[2])) +} diff --git a/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.test.mjs b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.test.mjs new file mode 100644 index 00000000000..51223986d45 --- /dev/null +++ b/config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.test.mjs @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import { countRecurringTimers } from './check-recurring-timer-ratchet.mjs' + +describe('recurring-timer ratchet', () => { + it.each([ + ['setInterval(poll, 1000)', 1], + ['window.setInterval(poll, 1)\nglobalThis.setInterval(poll, 1)\nobj.setInterval(1)', 2], + [ + "import { setInterval } from 'node:timers'\nsetInterval(poll, 1)\nwindow.setInterval(poll, 1)", + 2 + ], + ["const { setInterval } = require('node:timers')\nsetInterval(poll, 1)", 1], + ["import { setInterval as every } from 'node:timers/promises'\nevery(5000)", 1], + // Alias and destructure forms of an imported timer count once, like the direct call. + [ + "import * as timers from 'node:timers'\nconst setInterval = timers.setInterval\nsetInterval(poll, 1)", + 1 + ], + [ + "const timers = require('node:timers')\nconst { setInterval } = timers\nsetInterval(poll, 1)", + 1 + ], + ["const { setInterval } = await import('node:timers')\nsetInterval(poll, 1)", 1], + // An unrelated local binding must not hide a global poll elsewhere in the file. + ['function configure(setInterval) {\n return setInterval\n}\nsetInterval(poll, 1000)', 1], + ['type Configure = (setInterval: number) => void\nsetInterval(poll, 1000)', 1], + ['function a(setInterval) { setInterval(f) }\nfunction b() { setInterval(g, 1) }', 1], + ['function setInterval(f) {}\nsetInterval(poll)', 0], + // Aliases and bracket access of the global timer are charged at the reference. + ['const schedule = setInterval\nschedule(poll, 1000)', 1], + ["window['setInterval'](poll, 1000)", 1], + ['const every = window.setInterval\nevery(poll, 1)', 1], + ["if (typeof setInterval === 'function') {}\ntype T = typeof setInterval", 0], + ['const deps = { setInterval, clearInterval }\ndeps.setInterval(poll, 1)', 1], + ["setInterval = replacement\nwindow['setInterval'] = replacement\ntypeof (setInterval)", 0], + ['(window.setInterval ||= fallback)(poll, 1000)', 1] + ])('counts %s', (source, count) => { + expect(countRecurringTimers('src/main/example.ts', source)).toBe(count) + }) +}) diff --git a/package.json b/package.json index 283d28dcd45..4014ada5610 100644 --- a/package.json +++ b/package.json @@ -226,6 +226,8 @@ "build:packages": "node config/scripts/workspace-package-build/build-workspace-packages.mjs", "check:process-host-imports": "node config/scripts/static-analysis/process-boundaries/check-process-host-imports.mjs", "check:main-sync-spawn-ratchet": "node config/scripts/static-analysis/process-boundaries/check-main-sync-spawn-ratchet.mjs", + "check:main-sync-fs-ratchet": "node config/scripts/static-analysis/ratchets/runtime-lifecycle/check-main-sync-fs-ratchet.mjs", + "check:recurring-timer-ratchet": "node config/scripts/static-analysis/ratchets/runtime-lifecycle/check-recurring-timer-ratchet.mjs", "check:compat-boundary-imports": "node config/scripts/static-analysis/process-boundaries/check-compat-boundary-imports.mjs", "check:import-boundaries": "bun config/scripts/static-analysis/process-boundaries/check-import-boundaries.mjs" }, From c463effa5aaf1a3167aba656a3e8d7872732d25b Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:34:29 -0800 Subject: [PATCH 8/9] test(perf): render and identity contracts for agent status, sidebar, tab strip and chat (#39954) * test(perf): render and identity contracts for agent status, sidebar, tab strip and chat Twelve operation, render and identity contracts at the production seams of the hottest UI paths, each driven at N and 10N with one hardcoded bound and shown to fail with its regression restored. Registers them in the contract list and fixes the perf workflow's path filter, which had drifted to 12 of 19 contracts. Removes test-only production exports nothing reads. * test(perf): prove composer typing lands; drop dead rebuild counter Review: the composer contract never checked the draft reached the composer, and its transcript control could not fail; the live-index rebuild counter and a bucket constant had no readers after the test exports went. --- .github/workflows/performance-contracts.yml | 17 +- .../agent-status-hot-path-benchmark.ts | 74 ++------ config/vitest.performance.config.ts | 15 +- ...se-runtime-graph-sync.performance.test.tsx | 58 ++++++ ...se-agent-pane-threads.performance.test.tsx | 98 +++++++++++ ...hatMarkdown.streaming.performance.test.tsx | 66 +++++++ ...ssion.composer-typing.performance.test.tsx | 166 ++++++++++++++++++ ...tiveChatStructuredSession.test-harness.tsx | 3 + ...MessageList.windowing.performance.test.tsx | 50 ++++++ .../markdown-parse-meter.test-fixture.ts | 51 ------ ...wn-top-level-blocks-legacy.test-fixture.ts | 103 ----------- ...ktree-activity-status.performance.test.tsx | 76 ++++++++ ...e-worktree-agent-rows.performance.test.tsx | 63 +++++++ .../worktree-agent-live-index-patch.ts | 9 - .../activity/worktree-agent-row-selectors.ts | 4 +- ...use-visible-worktrees.performance.test.tsx | 97 ++++++++++ ...-agent-types-by-tab-id.performance.test.ts | 63 +++++++ ...terminal-tab-activity.performance.test.tsx | 77 ++++++++ .../agent-status-projection.ts | 13 -- .../agent-status-batch.performance.test.ts | 34 ++++ .../agent-status-scale.test-fixture.ts | 91 ++++++++++ 21 files changed, 980 insertions(+), 248 deletions(-) create mode 100644 src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx create mode 100644 src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx create mode 100644 src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx create mode 100644 src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx create mode 100644 src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx delete mode 100644 src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts delete mode 100644 src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts create mode 100644 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx create mode 100644 src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx create mode 100644 src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx create mode 100644 src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts create mode 100644 src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx create mode 100644 src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts create mode 100644 src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index 8af9f5342b2..cd3ba1dfa3a 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -12,22 +12,29 @@ on: - 'config/oxlint-performance-audit.json' - 'config/oxlint-plugins/*performance.mjs' - 'config/oxlint-plugins/quadratic-buffer-concat.mjs' - - 'config/scripts/*-plugin.test.mjs' - - '!config/scripts/static-analysis/oxlint-contracts/renderer-scrollbar-style-plugin.test.mjs' - # Keep in sync with the contract list in config/vitest.performance.config.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' + - '**/*.performance.test.ts' + - '**/*.performance.test.tsx' + # Contracts without the .performance suffix. Keep in sync with config/vitest.performance.config.ts; # without these a rename lands green and only breaks the next nightly. - - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' + - 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts' - 'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts' + - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' + - 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts' + - 'src/main/runtime/rpc/methods/projects/repo.test.ts' + - 'src/renderer/src/components/tab-bar/use-new-tab-agent-menu-host-preferences.test.tsx' - 'src/main/sqlite/sync-database.test.ts' - 'src/main/runtime/orchestration/db/row-column-lists.test.ts' - - 'src/shared/native-chat/tools/native-chat-tool-pairing.performance.test.ts' - 'src/main/codex-usage/codex-rollout-file-lifetime.test.ts' - 'src/main/codex-usage/scanner-incremental-append.test.ts' - 'src/main/usage/jsonl-file-reader.test.ts' - 'src/main/usage/jsonl-file-snapshot.test.ts' - 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts' + - 'src/renderer/src/store/diagnostics/store-identity-churn-probe.test.ts' - 'src/main/claude-usage/scanner-incremental-append.test.ts' - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' + - 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx' permissions: contents: read diff --git a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts b/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts index dd2ddb8fa18..774c2411787 100644 --- a/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts +++ b/config/scripts/performance/agent-lineage/agent-status-hot-path-benchmark.ts @@ -9,23 +9,17 @@ import type { AppState } from '@/store/types' import type { AgentStatusBatchUpdate } from '@/store/slices/agent-status/agent-status-contract' import '@/store/slices/agent-status/agent-status' import { MAX_LIVE_AGENT_STATUSES } from '@/store/slices/agent-status/agent-status-capacity-eviction' -import { createTestStore } from '@/store/testing/app-store-test-fixture' -import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' -import { makeUnifiedTab } from '@/store/slices/tabs/tab-group.test-fixture' -import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' -import { TEST_REPO } from '@/store/repos/repo.test-fixture' -import { makePaneKey } from '../../../../src/shared/workspace-layout/stable-pane-id' -import { getDefaultSettings } from '../../../../src/shared/constants' +import type { createTestStore } from '@/store/testing/app-store-test-fixture' import { createAgentStatusPaneRoutingIndex, resolvePaneKeyFromRoutingIndex } from '@/hooks/ipc-events/agent-status-pane-routing-index' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' import { resolvePaneKey } from '@/hooks/ipc-events/agent-status-routing' const WORKTREES = 423 const EVENTS = 1_000 const BATCH_SIZE = 8 -const LEAF_ID = '11111111-1111-4111-8111-111111111111' const BASE_TIME = 2_000_000_000 const counters = { maps: 0, sets: 0, tabComparisons: 0 } @@ -58,62 +52,16 @@ function withAllocationCounting(run: () => T): T { } } -/** Tab list whose iteration is observable, so the nested-loop resolver's comparisons are countable. */ -class CountingTabList extends Array { - [Symbol.iterator](): ArrayIterator { - const iterator = super[Symbol.iterator]() - const next = iterator.next.bind(iterator) - iterator.next = (...args) => { - const result = next(...args) - if (!result.done) { - counters.tabComparisons += 1 - } - return result - } - return iterator - } -} - function buildFixture(countTabIteration: boolean) { - const store = createTestStore() - const settings = store.getState().settings ?? getDefaultSettings(tmpdir()) - const tabsByWorktree: AppState['tabsByWorktree'] = {} - const unifiedTabsByWorktree: AppState['unifiedTabsByWorktree'] = {} - const worktrees: ReturnType[] = [] - const paneKeys: string[] = [] - const owners: { tabId: string; worktreeId: string }[] = [] - for (let index = 0; index < WORKTREES; index += 1) { - const worktreeId = `wt-${index}` - worktrees.push(makeWorktree({ id: worktreeId, repoId: TEST_REPO.id })) - const tabs: ReturnType[] = [] - const unified: ReturnType[] = [] - for (let tab = 0; tab < (index % 2 === 0 ? 1 : 2); tab += 1) { - const tabId = `tab-${index}-${tab}` - tabs.push(makeTab({ id: tabId, worktreeId, title: `Terminal ${index}-${tab}` })) - unified.push( - makeUnifiedTab({ - id: tabId, - worktreeId, - groupId: `group-${index}`, - label: `Label ${index}` - }) - ) - paneKeys.push(makePaneKey(tabId, LEAF_ID)) - owners.push({ tabId, worktreeId }) - } - tabsByWorktree[worktreeId] = countTabIteration ? CountingTabList.from(tabs) : tabs - unifiedTabsByWorktree[worktreeId] = unified - } - store.setState({ - repos: [TEST_REPO], - worktreesByRepo: { [TEST_REPO.id]: worktrees }, - tabsByWorktree, - unifiedTabsByWorktree, - terminalLayoutsByTabId: {}, - setGeneratedTabTitlesFromAgentPrompts: () => {}, - settings: { ...settings, tabAutoGenerateTitle: false } - }) - return { store, paneKeys, owners } + const fixture = buildAgentStatusScaleFixture( + countTabIteration + ? () => { + counters.tabComparisons += 1 + } + : undefined + ) + fixture.store.setState({ setGeneratedTabTitlesFromAgentPrompts: () => {} }) + return fixture } function measure(run: () => void): number { diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index 764857f9fe3..3d058e384c9 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -23,7 +23,20 @@ const contracts = [ 'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs', 'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs', 'src/main/claude-usage/scanner-incremental-append.test.ts', - 'src/main/claude-usage/store-checkpoint-persistence.test.ts' + 'src/main/claude-usage/store-checkpoint-persistence.test.ts', + // Renderer hot paths: render, identity and publication counts at N and 10N (agent status, sidebar, tab strip, chat). + 'src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts', + 'src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx', + 'src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx', + 'src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx', + 'src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx', + 'src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts', + 'src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx', + 'src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx', + 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx', + 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx', + 'src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx', + 'src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx' ] for (const contract of contracts) { if (!existsSync(resolve(contract))) { diff --git a/src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx b/src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx new file mode 100644 index 00000000000..4e34214bf13 --- /dev/null +++ b/src/renderer/src/app-shell/use-runtime-graph-sync.performance.test.tsx @@ -0,0 +1,58 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '../store' +import { makeAgentStatusEntry } from '../runtime/sync-runtime-graph/testing/sync-runtime-graph-test-harness' +import { scheduleRuntimeGraphSync } from '../runtime/sync-runtime-graph/graph-sync-scheduler' +import { useRuntimeGraphSync } from './use-runtime-graph-sync' + +vi.mock('../runtime/sync-runtime-graph/graph-sync-scheduler', () => ({ + scheduleRuntimeGraphSync: vi.fn(), + setRuntimeGraphStoreStateGetter: vi.fn(), + setRuntimeGraphSyncEnabled: vi.fn() +})) +const initialState = useAppStore.getInitialState() +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.clearAllMocks() +}) +// Same-bucket heartbeats change no mobile data; a state transition requires one publication. +describe('runtime graph heartbeat publication contract', () => { + it.each([50, 500])('does not schedule heartbeats at %i panes', (count) => { + useAppStore.setState(initialState, true) + const entries = Object.fromEntries( + Array.from({ length: count }, (_, index) => { + const paneKey = `tab-${index}:11111111-1111-4111-8111-111111111111` + return [ + paneKey, + makeAgentStatusEntry({ paneKey, updatedAt: 1_800_000, stateStartedAt: 1_800_000 }) + ] + }) + ) + useAppStore.setState({ agentStatusByPaneKey: entries }) + renderHook(() => useRuntimeGraphSync()) + vi.mocked(scheduleRuntimeGraphSync).mockClear() + const key = Object.keys(entries)[9] + for (let tick = 1; tick <= 20; tick += 1) { + act(() => + useAppStore.setState({ + agentStatusByPaneKey: { + ...useAppStore.getState().agentStatusByPaneKey, + [key]: { ...entries[key], updatedAt: 1_800_000 + tick * 1_000 } + } + }) + ) + expect(scheduleRuntimeGraphSync).toHaveBeenCalledTimes(0) + } + act(() => + useAppStore.setState({ + agentStatusByPaneKey: { + ...useAppStore.getState().agentStatusByPaneKey, + [key]: { ...useAppStore.getState().agentStatusByPaneKey[key], state: 'blocked' } + } + }) + ) + expect(scheduleRuntimeGraphSync).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx b/src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx new file mode 100644 index 00000000000..16b9950055c --- /dev/null +++ b/src/renderer/src/components/activity/use-agent-pane-threads.performance.test.tsx @@ -0,0 +1,98 @@ +// @vitest-environment happy-dom +import { act, cleanup, renderHook } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' +import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id' +import { useAppStore } from '@/store' +import { + LEAF_ID, + makeRepo, + makeTabWithIds, + makeWorktree +} from './ActivityPrototypePage-test-fixtures' + +import { useAgentPaneThreads } from './use-agent-pane-threads' + +vi.mock('@/store', async () => { + const { createTestStore } = await import('@/store/testing/app-store-test-fixture') + return { useAppStore: createTestStore() } +}) + +afterEach(() => { + cleanup() + vi.restoreAllMocks() +}) + +function installPanes(count: number): string[] { + vi.spyOn(Date, 'now').mockReturnValue(100_000) + const repo = makeRepo() + const worktree = makeWorktree() + const tabs = Array.from({ length: count }, (_, index) => + makeTabWithIds(`tab-${index}`, worktree.id) + ) + const entries: Record = {} + for (const tab of tabs) { + const paneKey = makePaneKey(tab.id, LEAF_ID) + entries[paneKey] = { + paneKey, + state: 'working', + prompt: `Task ${tab.id}`, + agentType: 'claude', + updatedAt: 100_000, + stateStartedAt: 99_000, + stateHistory: [] + } + } + useAppStore.setState({ + agentStatusByPaneKey: entries, + retainedAgentsByPaneKey: {}, + migrationUnsupportedByPtyId: {}, + runtimeAgentOrchestrationByPaneKey: {}, + acknowledgedAgentsByPaneKey: {}, + activityClearedAtByPaneKey: {}, + repos: [repo], + worktreesByRepo: { [repo.id]: [worktree] }, + folderWorkspaces: [], + detectedWorktreesByRepo: {}, + tabsByWorktree: { [worktree.id]: tabs }, + unifiedTabsByWorktree: {}, + agentsVisibleHostIds: null, + agentsFilterRepoIds: [] + }) + return Object.keys(entries) +} + +describe('agent thread list reuse', () => { + it.each([40, 400])('rebuilds only the pinged thread among %i panes', (count) => { + const panes = installPanes(count) + const activity = renderHook(() => + useAgentPaneThreads({ + query: '', + readFilter: 'all', + groupBy: 'none', + selectedPaneKey: null, + showChildAgents: true + }) + ) + const before = activity.result.current.allThreads + expect(before).toHaveLength(count) + const pinged = panes[9] + + act(() => { + const entries = useAppStore.getState().agentStatusByPaneKey + useAppStore.setState({ + agentStatusByPaneKey: { + ...entries, + [pinged]: { ...entries[pinged], prompt: 'Follow-up prompt' } + } + }) + }) + + const after = activity.result.current.allThreads + expect(after.map((thread) => thread.paneKey)).toEqual(before.map((thread) => thread.paneKey)) + // Memoized rows compare thread identity; only the pinged pane's row may see a new object. + const rebuilt = after.filter((thread, index) => thread !== before[index]) + expect(rebuilt.map((thread) => thread.paneKey)).toEqual([pinged]) + expect(rebuilt[0]?.currentAgentEntry?.prompt).toBe('Follow-up prompt') + }) +}) diff --git a/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx b/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx new file mode 100644 index 00000000000..809968ac7ce --- /dev/null +++ b/src/renderer/src/components/native-chat/markdown/NativeChatMarkdown.streaming.performance.test.tsx @@ -0,0 +1,66 @@ +// @vitest-environment happy-dom +import { cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type * as ReactMarkdownModule from 'react-markdown' + +const markdownInput = vi.hoisted(() => ({ chars: 0 })) +vi.mock('react-markdown', async (importOriginal) => { + const actual = await importOriginal() + const { createElement } = await import('react') + return { + ...actual, + default: (props: Parameters[0]) => { + markdownInput.chars += typeof props.children === 'string' ? props.children.length : 0 + return createElement(actual.default, props) + } + } +}) +vi.mock('@/store/index', () => ({ + useAppStore: (selector: (state: { settings: { theme: string } }) => unknown) => + selector({ settings: { theme: 'light' } }) +})) + +import { NativeChatMarkdown } from './NativeChatMarkdown' +import { TooltipProvider } from '@/components/ui/tooltip' + +const BLOCK_CHARS = 200 +const TOKEN = ' tick' + +function paragraphs(count: number): string { + return Array.from({ length: count }, (_, index) => + `Paragraph ${index} ${'lorem '.repeat(BLOCK_CHARS)}`.slice(0, BLOCK_CHARS) + ).join('\n\n') +} + +function reply(content: string): React.JSX.Element { + return ( + + + + ) +} + +afterEach(cleanup) + +describe('streaming native chat markdown parse budget', () => { + it.each([10, 100])( + 'hands react-markdown only the tail of a %i-block reply per append', + (blocks) => { + let content = paragraphs(blocks) + const { container, rerender } = render(reply(content)) + const firstParagraph = container.querySelector('p') + expect(firstParagraph).not.toBeNull() + let widestAppend = 0 + for (let tick = 0; tick < 20; tick += 1) { + content += TOKEN + markdownInput.chars = 0 + rerender(reply(content)) + widestAppend = Math.max(widestAppend, markdownInput.chars) + } + // Only the unsettled tail: two 200-char blocks, the last grown by 20 x 5-char tokens, plus a separator. + expect(widestAppend).toBeLessThanOrEqual(505) + expect(container.querySelector('p')).toBe(firstParagraph) + expect(container.textContent).toContain(TOKEN.repeat(20).trim()) + } + ) +}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx new file mode 100644 index 00000000000..45c9f87c2d2 --- /dev/null +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.composer-typing.performance.test.tsx @@ -0,0 +1,166 @@ +// @vitest-environment happy-dom + +import type * as LaunchRegistry from '@/lib/agent-session/launch/structured-agent-session-launch-registry' +import type * as LaunchOptions from '@/lib/agent-session/launch/structured-agent-session-launch-options' +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types' + +const { mocks, moduleFactories, resetStructuredSessionMocks, launchModule } = await vi.hoisted( + async () => { + const setup = ( + await import('./NativeChatStructuredSession.test-harness') + ).createStructuredSessionMocks() + return { + ...setup, + launchModule: setup.moduleFactories.structuredAgentSessionLaunch() + } + } +) + +vi.mock('@/lib/agent-session/launch/structured-agent-session-launch', () => ({ + retryStructuredAgentSessionLaunch: launchModule.retryStructuredAgentSessionLaunch, + relaunchFailedStructuredAgentSessionForMessage: + launchModule.relaunchFailedStructuredAgentSessionForMessage +})) +vi.mock( + '@/lib/agent-session/launch/structured-agent-session-launch-registry', + async (importOriginal) => ({ + ...(await importOriginal()), + getStructuredAgentSessionLaunchLifecycle: launchModule.getStructuredAgentSessionLaunchLifecycle, + getStructuredAgentSessionLaunchResumes: launchModule.getStructuredAgentSessionLaunchResumes, + useStructuredAgentSessionLaunchLifecycle: launchModule.useStructuredAgentSessionLaunchLifecycle, + useStructuredAgentSessionLaunchFailure: launchModule.useStructuredAgentSessionLaunchFailure + }) +) +vi.mock( + '@/lib/agent-session/launch/structured-agent-session-launch-options', + async (importOriginal) => ({ + ...(await importOriginal()), + useStructuredAgentSessionLaunchSelection: launchModule.useStructuredAgentSessionLaunchSelection + }) +) +vi.mock('@/lib/agent-session/launch/structured-agent-session-launch-message', () => + moduleFactories.structuredAgentSessionLaunchMessage() +) +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-call', () => + moduleFactories.structuredAgentSessionCall() +) +vi.mock('../../../../runtime/native-chat/requests/structured-agent-session-subscriptions', () => + moduleFactories.structuredAgentSessionSubscriptions() +) +vi.mock('@/components/machine-identity/use-published-machine-name', () => ({ + usePublishedMachineName: () => null +})) +vi.mock('../../session/structured/use-structured-agent-session', () => + moduleFactories.useStructuredAgentSession() +) +vi.mock('../../appearance/use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize()) +vi.mock('../../links/actions/use-native-chat-file-link-context', () => + moduleFactories.useNativeChatFileLinkContext() +) +vi.mock('../../pane/ownership/use-native-chat-tab-owner', () => + moduleFactories.useNativeChatTabOwner() +) +vi.mock('../../links/actions/use-native-chat-file-link-click', () => + moduleFactories.useNativeChatFileLinkClick() +) +vi.mock('../../NativeChatMessageList', () => moduleFactories.nativeChatMessageList()) +vi.mock('../../host-access/NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState()) +vi.mock('../../prompts/NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard()) +vi.mock('../../prompts/NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) +vi.mock('@/runtime/hosts/installation/use-managed-runtime-install', () => ({ + useManagedRuntimeInstall: () => ({ kind: 'inactive' }) +})) + +import { NativeChatStructuredSession } from '../../NativeChatStructuredSession' +import { clearNativeChatComposerDraftsForTests } from '../../drafts/native-chat-draft-reset' +import { hydrateNativeChatComposerDrafts } from '../../drafts/native-chat-composer-draft-load' +import { updateNativeChatComposerDraft } from '../../drafts/native-chat-composer-draft-store' +import { structuredAgentSessionDraftScopeKey } from '../../drafts/native-chat-draft-scope' +import { TooltipProvider } from '@/components/ui/tooltip' +import { promptTextContent } from '../../composer/editor/native-chat-prompt-document-text' +import { + createMemoryNativeChatComposerDraftStorage, + setNativeChatComposerDraftStorageForTests +} from '../../drafts/native-chat-composer-draft-storage' +import { useAppStore } from '@/store' + +afterEach(() => { + cleanup() + resetStructuredSessionMocks() + clearNativeChatComposerDraftsForTests() +}) + +function journalMessage(index: number): AgentJournalRenderItem { + return { + itemId: `message-${index}`, + revision: 1, + sequence: index + 1, + observedAt: index + 1, + body: { + kind: 'message', + role: index % 2 === 0 ? 'user' : 'assistant', + blocks: [{ type: 'text', text: `Message ${index}` }] + } + } +} + +function session(): React.JSX.Element { + return ( + + + + ) +} + +describe('structured session composer typing', () => { + it.each([50, 500])( + 'renders no transcript while typing beside %i journal items', + async (count) => { + clearNativeChatComposerDraftsForTests() + setNativeChatComposerDraftStorageForTests(createMemoryNativeChatComposerDraftStorage()) + await hydrateNativeChatComposerDrafts() + mocks.journalItems = Array.from({ length: count }, (_, index) => journalMessage(index)) + mocks.messages = mocks.journalItems.map((item) => ({ + id: item.itemId, + role: 'assistant', + source: 'transcript', + timestamp: item.observedAt, + blocks: [{ type: 'text', text: item.itemId }] + })) + render(session()) + await screen.findByRole('textbox') + const scopeKey = structuredAgentSessionDraftScopeKey('session-1') + let storePublications = 0 + const unsubscribe = useAppStore.subscribe(() => { + storePublications += 1 + }) + const rendersBefore = mocks.messageListRenders + expect(rendersBefore).toBeGreaterThan(0) + let text = '' + for (let keystroke = 0; keystroke < 20; keystroke += 1) { + text += 'a' + act(() => { + updateNativeChatComposerDraft( + scopeKey, + { text, document: promptTextContent(text) }, + 'deferred' + ) + }) + } + unsubscribe() + // Typing reached the composer, through its own scope store; the transcript never heard it. + expect(screen.getByRole('textbox').textContent).toContain('a'.repeat(20)) + expect(mocks.messageListRenders - rendersBefore).toBe(0) + expect(storePublications).toBe(0) + } + ) +}) diff --git a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx index 26cee219bc9..3d014c8deaa 100644 --- a/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx +++ b/src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test-harness.tsx @@ -93,6 +93,7 @@ export function createStructuredSessionMocks() { readRefusal: absent(), messages: null as null | unknown[], messageListProps: initialMessageListProps, + messageListRenders: 0, composerProps: nullable<{ launchSeed?: NativeChatLaunchSeed structuredTransport?: Record & { @@ -308,6 +309,7 @@ export function createStructuredSessionMocks() { nativeChatMessageList: () => ({ NativeChatMessageList: (props: typeof mocks.messageListProps) => { mocks.messageListProps = props + mocks.messageListRenders += 1 useImperativeHandle(props?.ref, () => ({ revealLatest: mocks.revealLatest, readerAtEnd: () => true, @@ -352,6 +354,7 @@ export function createStructuredSessionMocks() { mocks.readRefusal = undefined mocks.messages = null mocks.messageListProps = null + mocks.messageListRenders = 0 mocks.composerProps = null mocks.approvalCardProps = null mocks.questionCardProps = null diff --git a/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx new file mode 100644 index 00000000000..be16ba53a87 --- /dev/null +++ b/src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.performance.test.tsx @@ -0,0 +1,50 @@ +// @vitest-environment happy-dom + +import { cleanup } from '@testing-library/react' +import { render } from '../../messages/actions/native-chat-tooltip-test-harness' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { list, marker, stubLayout, windowState } from './native-chat-windowing-test-harness' + +let restoreLayout = (): void => {} +beforeEach(() => { + restoreLayout = stubLayout() +}) +afterEach(() => { + cleanup() + restoreLayout() +}) + +function mountedRows(container: HTMLElement): Map { + return new Map( + Array.from(container.querySelectorAll('[data-index]'), (row) => [ + Number(row.dataset.index), + row + ]) + ) +} + +// ceil(600px viewport / 44px row pitch) = 14 visible, 2 x 6 overscan, and the pinned latest row. +const MOUNTED_ROW_BOUND = 27 + +describe('windowed transcript row budget', () => { + it.each([200, 2_000])('mounts a bounded row set from a %i-message transcript', (count) => { + const transcript = Array.from({ length: count }, (_, index) => marker(index)) + const { container, rerender } = render(list(transcript)) + const opened = windowState(container) + expect(opened.indexes.length).toBeLessThanOrEqual(MOUNTED_ROW_BOUND) + expect(opened.indexes).toContain(count - 1) + const before = mountedRows(container) + + rerender(list([...transcript, marker(count)])) + const appended = windowState(container) + expect(appended.indexes.length).toBeLessThanOrEqual(MOUNTED_ROW_BOUND) + expect(appended.indexes).toContain(count) + expect(container.textContent).toContain(`marker-${count}`) + const after = mountedRows(container) + const kept = [...before].filter(([index]) => after.has(index)) + expect(kept.length).toBeGreaterThan(0) + for (const [index, row] of kept) { + expect(after.get(index)).toBe(row) + } + }) +}) diff --git a/src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts b/src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts deleted file mode 100644 index 8c4d72be00e..00000000000 --- a/src/renderer/src/components/sidebar/markdown-parse-meter.test-fixture.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { Nodes, Root } from 'mdast' - -type ParseWork = { - discovery: string[] - render: string[] - shifts: number - cloneNodes: number - cloneBytes: number - scans: { source: string; marker: string }[] - blocks: number -} - -export function createParseWork(): ParseWork { - return { - discovery: [], - render: [], - shifts: 0, - cloneNodes: 0, - cloneBytes: 0, - scans: [], - blocks: 0 - } -} - -export function nodeCount(node: Nodes): number { - return 1 + ('children' in node ? node.children.reduce((n, child) => n + nodeCount(child), 0) : 0) -} - -// Meter actual coordinate writes, leaving the parser's values and clone semantics unchanged. -export function meterPositions(tree: Root, onWrite: () => void): void { - function visit(node: Nodes): void { - if (node.position) { - for (const point of [node.position.start, node.position.end]) { - let offset = point.offset - Object.defineProperty(point, 'offset', { - enumerable: true, - configurable: true, - get: () => offset, - set: (value: number) => { - onWrite() - offset = value - } - }) - } - } - if ('children' in node) { - node.children.forEach(visit) - } - } - visit(tree) -} diff --git a/src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts b/src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts deleted file mode 100644 index fb50574b17a..00000000000 --- a/src/renderer/src/components/sidebar/markdown-top-level-blocks-legacy.test-fixture.ts +++ /dev/null @@ -1,103 +0,0 @@ -// Frozen splitter: differential tests compare every streaming prefix with the previous renderer. -// Reparse the last two blocks on append; cross-block definitions or HTML fall back to the whole document. - -import type { Nodes } from 'mdast' -import remarkGfm from 'remark-gfm' -import remarkParse from 'remark-parse' -import { remarkChatMath } from './chat-markdown-math' -import { chatMathCodeFences } from './chat-markdown-math-nodes' -import { unified } from 'unified' - -export type MarkdownBlock = { - /** Source offset, retained for settled blocks on append. */ - start: number - /** One-based source line. */ - line: number - text: string - literalMath?: boolean - /** Parser-owned end, excluding separators held for the next block. */ - end?: number -} - -export type MarkdownBlockSplit = { - source: string - blocks: readonly MarkdownBlock[] - /** Cross-block content requires whole-document rendering. */ - whole: boolean -} - -/** The last block, which is still growing, and the one it may yet join. */ -const UNSETTLED_BLOCKS = 2 - -const blockParser = unified().use(remarkParse).use(remarkGfm) -const mathBlockParser = blockParser().use(remarkChatMath) - -/** Tags that cannot hold anything, so cannot hold a later block. */ -const VOID_TAG_PATTERN = /^<(?:br|hr|wbr|img)\b[^>]*>$/i - -/** References and non-void HTML can affect other blocks and require whole-document parsing. */ -function reachesAcrossBlocks(node: Nodes): boolean { - if (node.type === 'definition' || node.type === 'footnoteDefinition') { - return true - } - if (node.type === 'html') { - return !VOID_TAG_PATTERN.test(node.value.trim()) - } - return 'children' in node && node.children.some(reachesAcrossBlocks) -} - -function hasLiteralMath(node: Nodes | undefined): boolean { - if (!node) { - return false - } - return ( - node.data?.mathComplete === false || - node.data?.mathLiteral === true || - ('children' in node && node.children.some(hasLiteralMath)) - ) -} - -function wholeDocument(source: string, literalMath = false): MarkdownBlockSplit { - return { source, blocks: [{ start: 0, line: 1, text: source, literalMath }], whole: true } -} - -export function splitMarkdownTopLevelBlocks( - source: string, - previous: MarkdownBlockSplit | null, - math = false -): MarkdownBlockSplit { - const grewFromPrevious = previous !== null && source.startsWith(previous.source) - if (grewFromPrevious && previous.whole && !math) { - return wholeDocument(source) - } - const settled = grewFromPrevious ? previous.blocks.slice(0, -UNSETTLED_BLOCKS) : [] - const reparsed = grewFromPrevious ? previous.blocks.at(-UNSETTLED_BLOCKS) : undefined - const base = reparsed?.start ?? 0 - const baseLine = reparsed?.line ?? 1 - const tail = source.slice(base) - const tree = (math ? mathBlockParser : blockParser).parse(tail) - if (math) { - chatMathCodeFences(tree, tail) - } - if (reachesAcrossBlocks(tree)) { - return wholeDocument(source, math && hasLiteralMath(tree)) - } - // Each block runs to the next one's start, so the blank lines between stay in the source. - const points = tree.children.map((child) => - 'position' in child ? child.position?.start : undefined - ) - const starts = points.map((point) => point?.offset ?? 0) - starts[0] = 0 - const blocks = starts.map((start, index) => ({ - start: base + start, - line: baseLine + (index === 0 ? 0 : (points[index]?.line ?? 1) - 1), - text: tail.slice(start, starts[index + 1]), - ...(math - ? { - literalMath: hasLiteralMath(tree.children[index]), - end: base + (tree.children[index]?.position?.end.offset ?? tail.length) - } - : {}) - })) - return { source, blocks: [...settled, ...blocks], whole: false } -} diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx new file mode 100644 index 00000000000..d7ecad94d71 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-activity-status.performance.test.tsx @@ -0,0 +1,76 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' +import { useWorktreeActivityStatus } from './use-worktree-activity-status' +import { useWorktreeActivityStatuses } from './use-worktree-activity-statuses' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// One permission transition changes one card; sidebar sizing changes no status output. +describe('sidebar activity status subscription contract', () => { + it.each([40, 400])('isolates a status transition among %i cards', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const fixture = buildAgentStatusScaleFixture(undefined, count) + useAppStore.setState(initialState, true) + useAppStore.setState({ + ...fixture.state, + agentStatusByPaneKey: fixture.agentStatusByPaneKey, + refreshGitHubForWorktreeIfStale: vi.fn().mockResolvedValue(undefined) + }) + const ids = Object.keys(fixture.state.tabsByWorktree) + let commits = 0 + let picker: ReturnType | undefined + const statuses = new Map() + function Probe({ worktreeId }: { worktreeId: string }) { + const status = useWorktreeActivityStatus(worktreeId) + useEffect(() => { + commits += 1 + statuses.set(worktreeId, status) + }) + return null + } + function Picker() { + picker = useWorktreeActivityStatuses(ids) + return null + } + render( + <> + + {ids.map((id) => ( + + ))} + + ) + commits = 0 + const index = fixture.owners.findIndex((owner) => owner.worktreeId === 'wt-17') + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'blocked', agentType: 'claude', prompt: 'permission requested' }, + undefined, + { updatedAt: 2_000_000_001 }, + fixture.owners[index] + ) + ) + expect(commits).toBe(1) + expect(statuses.get('wt-17')).toBe('permission') + expect(picker?.get('wt-17')).toBe('permission') + const previousPicker = picker + commits = 0 + act(() => useAppStore.setState({ sidebarWidth: 333 })) + expect(commits).toBe(0) + expect(picker).toBe(previousPicker) + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx new file mode 100644 index 00000000000..ef457c4dcf9 --- /dev/null +++ b/src/renderer/src/components/sidebar/workspace-card/activity/use-worktree-agent-rows.performance.test.tsx @@ -0,0 +1,63 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' +import { useWorktreeAgentRows } from './useWorktreeAgentRows' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// Only the card owning the changed prompt has new rows; a same-freshness epoch changes none. +describe('worktree agent row subscription contract', () => { + it.each([40, 400])('isolates a status ping among %i cards', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const fixture = buildAgentStatusScaleFixture(undefined, count) + useAppStore.setState(initialState, true) + useAppStore.setState({ ...fixture.state, agentStatusByPaneKey: fixture.agentStatusByPaneKey }) + let commits = 0 + const prompts = new Map() + function Probe({ worktreeId }: { worktreeId: string }) { + const rows = useWorktreeAgentRows(worktreeId, true) + useEffect(() => { + commits += 1 + prompts.set(worktreeId, rows[0]?.entry.prompt ?? '') + }) + return null + } + render( + <> + {Object.keys(fixture.state.tabsByWorktree).map((id) => ( + + ))} + + ) + commits = 0 + const index = fixture.owners.findIndex((owner) => owner.worktreeId === 'wt-17') + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'working', agentType: 'claude', prompt: 'changed prompt' }, + undefined, + { updatedAt: 2_000_000_001 }, + fixture.owners[index] + ) + ) + expect(commits).toBe(1) + expect(prompts.get('wt-17')).toBe('changed prompt') + commits = 0 + act(() => + useAppStore.setState({ agentStatusEpoch: useAppStore.getState().agentStatusEpoch + 1 }) + ) + expect(commits).toBe(0) + }) +}) diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts index ca86090a00a..fbcac1c47c0 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-live-index-patch.ts @@ -14,15 +14,6 @@ export type LiveEntriesByWorktreeCache = { entriesByWorktree: Map } -// Count full rebuilds to verify same-key status pings take the incremental path. -let liveEntriesFullRebuildCount = 0 -export function getLiveEntriesFullRebuildCountForTests(): number { - return liveEntriesFullRebuildCount -} -export function recordLiveEntriesFullRebuild(): void { - liveEntriesFullRebuildCount += 1 -} - // Local completed orphans stay hidden; remote rows await host retraction, not tab hydration. export function liveEntryWorktreeId( paneKey: string, diff --git a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts index ea6312970a3..12b6f915d6c 100644 --- a/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts +++ b/src/renderer/src/components/sidebar/workspace-card/activity/worktree-agent-row-selectors.ts @@ -7,8 +7,7 @@ import { parsePaneKey } from '../../../../../../shared/workspace-layout/stable-p import { type LiveEntriesByWorktreeCache, liveEntryWorktreeId, - patchLiveEntriesByWorktree, - recordLiveEntriesFullRebuild + patchLiveEntriesByWorktree } from './worktree-agent-live-index-patch' import './worktree-agent-orchestration-index' import { createWorktreeRecordSelector } from '@/store/terminals/worktree-terminal-record-selector' @@ -150,7 +149,6 @@ function getLiveEntriesByWorktree(state: WorktreeAgentRowsState): Map() for (const [paneKey, entry] of Object.entries(agentStatusByPaneKey)) { diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx new file mode 100644 index 00000000000..30c2a8cf139 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/listing/use-visible-worktrees.performance.test.tsx @@ -0,0 +1,97 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { buildAgentStatusScaleFixture } from '@/store/slices/agent-status/agent-status-scale.test-fixture' +import { forgetWorktreeSleepIntent, markWorktreeSleepIntent } from '@/lib/worktree-sleep-intent' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host' +import { useVisibleSidebarWorktrees } from './use-visible-worktrees' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + forgetWorktreeSleepIntent('wt-18') + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// Heartbeats change no visible membership; ending the deliberately slept row's last agent removes one row. +describe('visible sidebar worktree subscription contract', () => { + it.each([40, 400])('retains the visible list through heartbeats at %i worktrees', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const fixture = buildAgentStatusScaleFixture(undefined, count) + useAppStore.setState(initialState, true) + useAppStore.setState({ + ...fixture.state, + agentStatusByPaneKey: fixture.agentStatusByPaneKey, + refreshGitHubForWorktreeIfStale: vi.fn().mockResolvedValue(undefined) + }) + const args: Parameters[0] = { + filterState: { + showSleepingWorkspaces: false, + filterRepoIds: [], + hideDefaultBranchWorkspace: false, + hideAutomationGeneratedWorkspaces: false, + hideCliCreatedWorkspaces: false, + hideDetachedHeadWorkspaces: false, + hideWorkspacesFromOtherDevices: false, + alwaysShowDefaultBranchWorkspace: false, + visibleWorkspaceHostIds: null, + workspaceHostScope: 'all' + }, + sortBy: 'recent', + sortedIds: Object.keys(fixture.state.tabsByWorktree), + repoMap: new Map(fixture.state.repos.map((repo) => [repo.id, repo])), + worktreeLineageById: {}, + defaultHostId: LOCAL_EXECUTION_HOST_ID, + agentSendTargetWorktreeId: null + } + let commits = 0 + let visible: ReturnType['visibleWorktrees'] = [] + function Probe() { + const result = useVisibleSidebarWorktrees(args) + useEffect(() => { + commits += 1 + visible = result.visibleWorktrees + }) + return null + } + render() + expect(visible).toHaveLength(count) + const baseline = visible + commits = 0 + const index = fixture.owners.findIndex((owner) => owner.worktreeId === 'wt-18') + for (let tick = 1; tick <= 20; tick += 1) { + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'working', agentType: 'claude', prompt: 'initial prompt' }, + undefined, + { updatedAt: 2_000_000_000 + tick }, + fixture.owners[index] + ) + ) + expect(commits).toBe(0) + expect(visible).toBe(baseline) + } + markWorktreeSleepIntent('wt-18') + act(() => + useAppStore + .getState() + .setAgentStatus( + fixture.paneKeys[index], + { state: 'done', agentType: 'claude', prompt: 'initial prompt' }, + undefined, + { updatedAt: 2_000_000_021 }, + fixture.owners[index] + ) + ) + expect(commits).toBe(1) + expect(visible.some((worktree) => worktree.id === 'wt-18')).toBe(false) + }) +}) diff --git a/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts new file mode 100644 index 00000000000..66aca792cf7 --- /dev/null +++ b/src/renderer/src/components/tab-bar/tab-agent-types-by-tab-id.performance.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types' +import type { TerminalLayoutSnapshot } from '../../../../shared/workspace-layout/terminal-tab-types' +import { + makeAgentEntry, + makeManyTabState, + LEAF_ID +} from '../worktree-jump/worktree-jump-palette-test-fixtures' +import { createTabBarAgentProjectionSelector } from './tab-agent-types-by-tab-id' + +// Same-agent pings change neither strip projection; a different agent must update the owning tab. +describe('tab bar agent projection identity contract', () => { + it.each([20, 200])('retains projection identities through pings at %i tabs', (count) => { + const tabs = makeManyTabState(count).tabsByWorktree!['wt-many'] + let statuses: Record = Object.fromEntries( + tabs.map((tab) => { + const entry = makeAgentEntry(tab.id, 'working', 2_000_000_000, { agentType: 'claude' }) + return [entry.paneKey, entry] + }) + ) + const layouts: Record = Object.fromEntries( + tabs.map((tab) => [ + tab.id, + { + root: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: LEAF_ID }, + second: { type: 'leaf', leafId: '22222222-2222-4222-8222-222222222222' } + }, + activeLeafId: LEAF_ID, + expandedLeafId: null + } satisfies TerminalLayoutSnapshot + ]) + ) + const select = createTabBarAgentProjectionSelector() + const baseline = select({ agentStatusByPaneKey: statuses, terminalLayoutsByTabId: layouts }) + for (let ping = 1; ping <= 50; ping += 1) { + statuses = Object.fromEntries( + Object.entries(statuses).map(([key, entry]) => [ + key, + { ...entry, updatedAt: 2_000_000_000 + ping } + ]) + ) + const next = select({ agentStatusByPaneKey: statuses, terminalLayoutsByTabId: layouts }) + expect(next.tabAgentTypesByTabId).toBe(baseline.tabAgentTypesByTabId) + expect(next.nativeChatTabWideFallbackUnsafeTabsById).toBe( + baseline.nativeChatTabWideFallbackUnsafeTabsById + ) + } + const changedKey = `term-5:${LEAF_ID}` + statuses = { ...statuses, [changedKey]: { ...statuses[changedKey], agentType: 'codex' } } + const changed = select({ agentStatusByPaneKey: statuses, terminalLayoutsByTabId: layouts }) + expect(changed.tabAgentTypesByTabId).not.toBe(baseline.tabAgentTypesByTabId) + expect(changed.tabAgentTypesByTabId).toEqual({ + ...baseline.tabAgentTypesByTabId, + 'term-5': 'codex' + }) + expect(changed.nativeChatTabWideFallbackUnsafeTabsById).toBe( + baseline.nativeChatTabWideFallbackUnsafeTabsById + ) + }) +}) diff --git a/src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx b/src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx new file mode 100644 index 00000000000..3f4e5ed56f5 --- /dev/null +++ b/src/renderer/src/components/tab-bar/use-terminal-tab-activity.performance.test.tsx @@ -0,0 +1,77 @@ +// @vitest-environment happy-dom +import { useEffect } from 'react' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@/store' +import { + makeAgentEntry, + makeManyTabState +} from '../worktree-jump/worktree-jump-palette-test-fixtures' +import { useTerminalTabActivity } from './use-terminal-tab-activity' + +const initialState = useAppStore.getInitialState() + +afterEach(() => { + cleanup() + useAppStore.setState(initialState, true) + vi.useRealTimers() +}) + +// Only the completed tab's glyph changes; other workspaces' titles and sidebar sizing change none. +describe('terminal tab activity subscription contract', () => { + it.each([20, 200])('isolates one completion among %i tabs', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + useAppStore.setState(initialState, true) + useAppStore.setState(makeManyTabState(count)) + const tabs = useAppStore.getState().tabsByWorktree['wt-many'] + const entries = tabs.map((tab) => + makeAgentEntry(tab.id, 'working', 2_000_000_000, { agentType: 'claude' }) + ) + useAppStore.setState({ + refreshGitHubForWorktreeIfStale: vi.fn().mockResolvedValue(undefined), + agentStatusByPaneKey: Object.fromEntries(entries.map((entry) => [entry.paneKey, entry])) + }) + let commits = 0 + const statuses = new Map() + function Probe({ tab }: { tab: (typeof tabs)[number] }) { + const activity = useTerminalTabActivity(tab) + useEffect(() => { + commits += 1 + statuses.set(tab.id, activity.activityStatus) + }) + return null + } + render( + <> + {tabs.map((tab) => ( + + ))} + + ) + commits = 0 + act(() => + useAppStore + .getState() + .setAgentStatus( + entries[5].paneKey, + { state: 'done', agentType: 'claude', prompt: '' }, + undefined, + { updatedAt: 2_000_000_001 }, + { tabId: tabs[5].id, worktreeId: 'wt-many' } + ) + ) + expect(commits).toBe(1) + expect(statuses.get('term-5')).toBe('done') + commits = 0 + for (let tick = 0; tick < 20; tick += 1) { + act(() => + useAppStore.setState({ + runtimePaneTitlesByTabId: { 'other-worktree-tab': { 0: `title ${tick}` } }, + sidebarWidth: 300 + tick + }) + ) + expect(commits).toBe(0) + } + }) +}) diff --git a/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts b/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts index 727ccf8df3e..c2b40336453 100644 --- a/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts +++ b/src/renderer/src/runtime/sync-runtime-graph/agent-status-projection.ts @@ -103,16 +103,3 @@ export function buildRuntimeMobileAgentStatusProjection( } return projection } - -export function buildRuntimeMobileAgentStatusProjectionForTests( - agentStatusByPaneKey: AppState['agentStatusByPaneKey'] -): string { - return buildRuntimeMobileAgentStatusProjection(agentStatusByPaneKey) -} - -export const AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS_FOR_TESTS = - AGENT_STATUS_SYNC_UPDATED_AT_BUCKET_MS - -export function resetRuntimeMobileAgentStatusProjectionCacheForTests(): void { - cachedAgentStatusProjection = null -} diff --git a/src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts b/src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts new file mode 100644 index 00000000000..64f0e56110f --- /dev/null +++ b/src/renderer/src/store/slices/agent-status/agent-status-batch.performance.test.ts @@ -0,0 +1,34 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { AgentStatusBatchUpdate } from './agent-status-contract' +import { buildAgentStatusScaleFixture } from './agent-status-scale.test-fixture' + +// One burst has one externally visible snapshot, irrespective of how many panes it changes. +describe('agent status burst publication contract', () => { + afterEach(() => vi.useRealTimers()) + + it.each([8, 80])('publishes %i updates once and retains untouched entries', (count) => { + vi.useFakeTimers() + vi.setSystemTime(2_000_000_000) + const { store, paneKeys, owners, agentStatusByPaneKey } = buildAgentStatusScaleFixture() + store.setState({ agentStatusByPaneKey }) + const before = store.getState().agentStatusByPaneKey + const published = vi.fn() + const stop = store.subscribe(published) + const updates: AgentStatusBatchUpdate[] = paneKeys.slice(0, count).map((paneKey, index) => ({ + paneKey, + payload: { state: 'working', agentType: 'claude', prompt: 'new prompt' }, + timing: { updatedAt: 2_000_000_001 }, + routing: owners[index] + })) + store.getState().setAgentStatuses(updates) + stop() + expect(published).toHaveBeenCalledTimes(1) + const after = store.getState().agentStatusByPaneKey + for (const paneKey of paneKeys.slice(0, count)) { + expect(after[paneKey].prompt).toBe('new prompt') + } + for (const paneKey of paneKeys.slice(count)) { + expect(after[paneKey]).toBe(before[paneKey]) + } + }) +}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts b/src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts new file mode 100644 index 00000000000..76cd7f36a36 --- /dev/null +++ b/src/renderer/src/store/slices/agent-status/agent-status-scale.test-fixture.ts @@ -0,0 +1,91 @@ +import { tmpdir } from 'node:os' +import type { AppState } from '@/store/types' +import type { AgentStatusEntry } from '../../../../../shared/agent-status/contracts/agent-status-types' +import { createTestStore } from '@/store/testing/app-store-test-fixture' +import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' +import { makeUnifiedTab } from '@/store/slices/tabs/tab-group.test-fixture' +import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' +import { TEST_REPO } from '@/store/repos/repo.test-fixture' +import { makePaneKey } from '../../../../../shared/workspace-layout/stable-pane-id' +import { getDefaultSettings } from '../../../../../shared/constants' + +const LEAF_ID = '11111111-1111-4111-8111-111111111111' + +export function buildAgentStatusScaleFixture( + onTabVisit: (() => void) | undefined = undefined, + worktreeCount = 423 +) { + /** Tab list whose iteration is observable, so the nested-loop resolver's comparisons are countable. */ + class CountingTabList extends Array { + [Symbol.iterator](): ArrayIterator { + const iterator = super[Symbol.iterator]() + const next = iterator.next.bind(iterator) + iterator.next = (...args) => { + const result = next(...args) + if (!result.done) { + onTabVisit?.() + } + return result + } + return iterator + } + } + + const store = createTestStore() + const settings = store.getState().settings ?? getDefaultSettings(tmpdir()) + const tabsByWorktree: AppState['tabsByWorktree'] = {} + const unifiedTabsByWorktree: AppState['unifiedTabsByWorktree'] = {} + const worktrees: ReturnType[] = [] + const paneKeys: string[] = [] + const owners: { tabId: string; worktreeId: string }[] = [] + for (let index = 0; index < worktreeCount; index += 1) { + const worktreeId = `wt-${index}` + worktrees.push(makeWorktree({ id: worktreeId, repoId: TEST_REPO.id })) + const tabs: ReturnType[] = [] + const unified: ReturnType[] = [] + for (let tab = 0; tab < (index % 2 === 0 ? 1 : 2); tab += 1) { + const tabId = `tab-${index}-${tab}` + tabs.push(makeTab({ id: tabId, worktreeId, title: `Terminal ${index}-${tab}` })) + unified.push( + makeUnifiedTab({ + id: tabId, + worktreeId, + groupId: `group-${index}`, + label: `Label ${index}` + }) + ) + paneKeys.push(makePaneKey(tabId, LEAF_ID)) + owners.push({ tabId, worktreeId }) + } + tabsByWorktree[worktreeId] = onTabVisit ? CountingTabList.from(tabs) : tabs + unifiedTabsByWorktree[worktreeId] = unified + } + const state = { + repos: [TEST_REPO], + worktreesByRepo: { [TEST_REPO.id]: worktrees }, + tabsByWorktree, + unifiedTabsByWorktree, + terminalLayoutsByTabId: {}, + settings: { ...settings, tabAutoGenerateTitle: false } + } satisfies Partial + store.setState(state) + const agentStatusByPaneKey = Object.fromEntries( + paneKeys + .map((paneKey, index): [string, AgentStatusEntry] => [ + paneKey, + { + paneKey, + ...owners[index], + state: 'working', + agentType: 'claude', + prompt: 'initial prompt', + updatedAt: 2_000_000_000, + stateStartedAt: 2_000_000_000, + firstStateStartedAt: 2_000_000_000, + stateHistory: [] + } satisfies AgentStatusEntry + ]) + .filter((_, index) => owners[index].tabId.endsWith('-0')) + ) + return { store, state, paneKeys, owners, agentStatusByPaneKey } +} From 65412f3f6db6240689fcffe9bcaa65e628267702 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 8 Nov 2026 13:54:02 -0800 Subject: [PATCH 9/9] refactor: organize browser extension requests and rule owners (#39975) * refactor: organize browser extension request and rule owners * refactor: retain browser extension type-reference directives * chore: follow concrete owners in sync filesystem baseline --- config/main-sync-fs-baseline.txt | 17 +- .../scripts/ci/sharding/ci-shard-timings.json | 6 +- .../actions/browser-extension-toolbar.ts | 2 +- .../browser-extension-api-namespaces.test.ts | 2 +- src/main/browser/extensions/api/commands.ts | 2 +- src/main/browser/extensions/api/cookies.ts | 2 +- .../api/declarative-net-request-test-match.ts | 12 +- .../extensions/api/declarative-net-request.ts | 2 +- .../browser/extensions/api/management.test.ts | 4 +- src/main/browser/extensions/api/management.ts | 2 +- .../extensions/api/notifications.test.ts | 7 +- .../browser/extensions/api/notifications.ts | 2 +- .../browser/extensions/api/permissions.ts | 64 +--- src/main/browser/extensions/api/runtime.ts | 24 +- .../browser/extensions/api/storage-sync.ts | 23 +- .../extensions/api/tabs-capture.test.ts | 2 +- .../browser/extensions/api/tabs-capture.ts | 2 +- src/main/browser/extensions/api/tabs.ts | 19 +- .../browser/extensions/api/web-navigation.ts | 31 +- src/main/browser/extensions/api/windows.ts | 2 +- .../browser-extension-management.test.ts | 4 +- .../browser-extension-management.ts | 4 +- .../extensions/browser-extension-startup.ts | 2 +- .../browser-extension-web-request.ts | 305 ------------------ ...rowser-extension-context-menu-host.test.ts | 9 +- .../browser-extension-context-menu-host.ts | 4 +- .../engine-stages.test.ts | 6 +- .../declarative-net-request/engine.test.ts | 4 +- .../declarative-net-request/engine.ts | 12 +- .../header-modification.ts | 2 +- .../{ => header-actions}/header-rules.ts | 10 +- .../{ => indexing}/candidate-postings.ts | 2 +- .../{ => indexing}/ngram-dictionary.ts | 0 .../{ => indexing}/ruleset-index.ts | 8 +- .../{ => matching}/domain-matching.ts | 0 .../{ => matching}/extension-matcher.ts | 2 +- .../{ => matching}/rule-matching.ts | 6 +- .../{ => matching}/ruleset-matcher.ts | 22 +- .../{ => matching}/url-pattern.test.ts | 0 .../{ => matching}/url-pattern.ts | 0 .../{ => matching}/url-text.ts | 0 .../redirect-url.test.ts | 6 +- .../{ => redirect-actions}/redirect-url.ts | 4 +- .../{ => regex}/regex-char-set.ts | 0 .../{ => regex}/regex-filter.test.ts | 0 .../{ => regex}/regex-filter.ts | 0 .../{ => regex}/regex-piece.ts | 0 .../{ => regex}/regex-repetition.ts | 0 .../{ => regex}/regex-translation.ts | 0 .../request-context.ts | 12 +- .../declarative-net-request/request-state.ts | 2 +- .../{ => rule-compilation}/indexed-rule.ts | 10 +- .../{ => rule-compilation}/parse-errors.ts | 0 .../{ => rule-compilation}/rule-conditions.ts | 4 +- .../{ => rule-compilation}/rule-flags.ts | 0 .../{ => rule-compilation}/rule-schema.ts | 0 .../{ => rule-compilation}/rule-types.ts | 0 .../{ => rule-compilation}/ruleset-builder.ts | 2 +- .../browser-extension-dnr-extension-rules.ts | 4 +- .../browser-extension-dnr-frames.test.ts | 2 +- .../session/browser-extension-dnr-frames.ts | 2 +- .../session/browser-extension-dnr-limits.ts | 2 +- ...rowser-extension-dnr-matched-rules.test.ts | 2 +- .../browser-extension-dnr-matched-rules.ts | 2 +- .../browser-extension-dnr-requests.test.ts | 2 +- .../session/browser-extension-dnr-requests.ts | 9 +- .../browser-extension-dnr-static-rulesets.ts | 9 +- .../session/browser-extension-dnr-store.ts | 8 +- .../browser-extension-mutation-lock.ts | 27 ++ ...browser-extension-webstore-install.test.ts | 9 +- .../browser-extension-webstore-install.ts | 27 -- .../browser-extension-request-host-access.ts | 2 +- .../browser-extension-session-permissions.ts | 19 ++ ...extension-settings-prompt-lifetime.test.ts | 14 +- .../browser-extension-user-gesture.ts | 36 +++ ...browser-extension-session-services.test.ts | 2 +- .../browser-extension-session-services.ts | 2 +- .../browser-extension-data-removal.test.ts | 6 +- ...rowser-extension-profile-document-store.ts | 158 +++++++++ ...owser-extension-sync-storage-store.test.ts | 17 +- .../browser-extension-sync-storage-store.ts | 166 +--------- ...rowser-extension-request-classification.ts | 57 ++++ .../browser-extension-web-request-details.ts | 101 ++++++ .../browser-extension-web-request-filter.ts | 32 ++ .../browser-extension-web-request-observer.ts | 127 ++++++++ .../browser-extension-discarded-tabs.test.ts | 4 +- .../browser-extension-frame-projection.ts | 27 ++ .../browser-extension-options-page.ts | 23 ++ .../browser-extension-requested-navigation.ts | 21 ++ .../browser-extension-tab-lifecycle.ts} | 4 +- .../browser-extension-tab-model.ts | 2 +- .../browser-extension-tab-resolution.test.ts | 2 +- .../browser-extension-webstore-service.ts | 8 +- ...browser-extension-webstore-updater.test.ts | 2 +- .../browser-extension-webstore-updater.ts | 6 +- src/main/ipc/browser/browser.ts | 2 +- 96 files changed, 849 insertions(+), 765 deletions(-) delete mode 100644 src/main/browser/extensions/browser-extension-web-request.ts rename src/main/browser/extensions/declarative-net-request/{ => header-actions}/header-modification.ts (98%) rename src/main/browser/extensions/declarative-net-request/{ => header-actions}/header-rules.ts (94%) rename src/main/browser/extensions/declarative-net-request/{ => indexing}/candidate-postings.ts (98%) rename src/main/browser/extensions/declarative-net-request/{ => indexing}/ngram-dictionary.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => indexing}/ruleset-index.ts (96%) rename src/main/browser/extensions/declarative-net-request/{ => matching}/domain-matching.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => matching}/extension-matcher.ts (98%) rename src/main/browser/extensions/declarative-net-request/{ => matching}/rule-matching.ts (95%) rename src/main/browser/extensions/declarative-net-request/{ => matching}/ruleset-matcher.ts (92%) rename src/main/browser/extensions/declarative-net-request/{ => matching}/url-pattern.test.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => matching}/url-pattern.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => matching}/url-text.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => redirect-actions}/redirect-url.test.ts (94%) rename src/main/browser/extensions/declarative-net-request/{ => redirect-actions}/redirect-url.ts (98%) rename src/main/browser/extensions/declarative-net-request/{ => regex}/regex-char-set.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => regex}/regex-filter.test.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => regex}/regex-filter.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => regex}/regex-piece.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => regex}/regex-repetition.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => regex}/regex-translation.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => rule-compilation}/indexed-rule.ts (96%) rename src/main/browser/extensions/declarative-net-request/{ => rule-compilation}/parse-errors.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => rule-compilation}/rule-conditions.ts (97%) rename src/main/browser/extensions/declarative-net-request/{ => rule-compilation}/rule-flags.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => rule-compilation}/rule-schema.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => rule-compilation}/rule-types.ts (100%) rename src/main/browser/extensions/declarative-net-request/{ => rule-compilation}/ruleset-builder.ts (98%) create mode 100644 src/main/browser/extensions/installation/browser-extension-mutation-lock.ts create mode 100644 src/main/browser/extensions/permissions/browser-extension-session-permissions.ts create mode 100644 src/main/browser/extensions/permissions/browser-extension-user-gesture.ts create mode 100644 src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts create mode 100644 src/main/browser/extensions/requests/browser-extension-request-classification.ts create mode 100644 src/main/browser/extensions/requests/browser-extension-web-request-details.ts create mode 100644 src/main/browser/extensions/requests/browser-extension-web-request-filter.ts create mode 100644 src/main/browser/extensions/requests/browser-extension-web-request-observer.ts create mode 100644 src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts create mode 100644 src/main/browser/extensions/tabs-and-windows/browser-extension-options-page.ts create mode 100644 src/main/browser/extensions/tabs-and-windows/browser-extension-requested-navigation.ts rename src/main/browser/extensions/{api/tabs-lifecycle.ts => tabs-and-windows/browser-extension-tab-lifecycle.ts} (98%) diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index eb8a6f17c23..f64f48d6883 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -2,14 +2,15 @@ # Startup-only or one-shot uses are fine to keep; per-RPC, per-spawn, per-focus or per-poll uses are the target. # This is a RATCHET: counts may only go DOWN. # Prune after removing calls: pnpm check:main-sync-fs-ratchet --prune -1 src/main/agent-hooks/first-work-rename-runtime.ts -2 src/main/agent-hooks/hook-config-write-path.ts -1 src/main/agent-hooks/hooks-json-read.ts -20 src/main/agent-hooks/installer-utils.ts -6 src/main/agent-hooks/locked-executable-rename.ts +1 src/main/agent-hooks/first-work/first-work-rename-runtime.ts +2 src/main/agent-hooks/installation/configuration/hook-config-write-path.ts +1 src/main/agent-hooks/installation/configuration/hooks-json-read.ts +11 src/main/agent-hooks/installation/configuration/hooks-json-write.ts +6 src/main/agent-hooks/installation/scripts/locked-executable-rename.ts +9 src/main/agent-hooks/installation/scripts/managed-hook-script-write.ts 1 src/main/agent-hooks/server/server-hydration.ts -1 src/main/agent-hooks/wsl-hook-relay-deps.ts -3 src/main/agent-hooks/wsl-hook-relay-launch.ts +1 src/main/agent-hooks/wsl-relay/wsl-hook-relay-deps.ts +3 src/main/agent-hooks/wsl-relay/wsl-hook-relay-launch.ts 1 src/main/agent-launch/trust/agent-trust-ownership-ledger.ts 14 src/main/agent-launch/trust/agent-trust-presets.ts 2 src/main/agent-launch/trust/antigravity-workspace-trust-ownership.ts @@ -57,9 +58,9 @@ 1 src/main/browser/extensions/installation/browser-extension-load-directory.ts 1 src/main/browser/extensions/profile-sessions/browser-extension-session-loader.ts 2 src/main/browser/extensions/profile-storage/browser-extension-data-removal.ts +8 src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts 4 src/main/browser/extensions/profile-storage/browser-extension-profile-state-store.ts 3 src/main/browser/extensions/profile-storage/browser-extension-retired-profile-storage.ts -8 src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts 1 src/main/browser/guest-lifecycle/popups/browser-popup-background-cdp-probe.ts 2 src/main/browser/guest-lifecycle/popups/popup-identity-electron-probe.ts 1 src/main/browser/identity/browser-identity-mode-record.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 9c25664e63d..45c1aa25247 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -1115,9 +1115,9 @@ "src/main/browser/extensions/api-runtime/browser-extension-worker-api-host.test.ts": 237, "src/main/browser/extensions/declarative-net-request/engine-stages.test.ts": 112, "src/main/browser/extensions/declarative-net-request/engine.test.ts": 145, - "src/main/browser/extensions/declarative-net-request/redirect-url.test.ts": 66, - "src/main/browser/extensions/declarative-net-request/regex-filter.test.ts": 116, - "src/main/browser/extensions/declarative-net-request/url-pattern.test.ts": 84, + "src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts": 66, + "src/main/browser/extensions/declarative-net-request/regex/regex-filter.test.ts": 116, + "src/main/browser/extensions/declarative-net-request/matching/url-pattern.test.ts": 84, "src/main/browser/element-grab/grab-guest-overlay-follow.test.ts": 332, "src/main/browser/element-grab/grab-guest-script.test.ts": 107, "src/main/browser/cdp/debugger/guest-cdp-command.test.ts": 105, diff --git a/src/main/browser/extensions/actions/browser-extension-toolbar.ts b/src/main/browser/extensions/actions/browser-extension-toolbar.ts index c7546303b53..ea8108e6c7e 100644 --- a/src/main/browser/extensions/actions/browser-extension-toolbar.ts +++ b/src/main/browser/extensions/actions/browser-extension-toolbar.ts @@ -1,5 +1,5 @@ import { webContents } from 'electron' -import { noteBrowserExtensionUserGesture } from '../api/permissions' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' import type { BrowserExtensionActionResult } from '../../../../shared/browser/extensions/browser-extension-types' import { BROWSER_EXTENSION_POPUP_REQUEST_CHANNEL, diff --git a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts index 9c6d2083c11..f603dd5cd73 100644 --- a/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts +++ b/src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts @@ -70,7 +70,7 @@ await import('./permissions') const { getBrowserExtensionProfileStateStore } = await import('../profile-storage/browser-extension-profile-state-store') const menuHost = await import('../context-menus/browser-extension-context-menu-host') -const webRequest = await import('../browser-extension-web-request') +const webRequest = await import('../requests/browser-extension-web-request-observer') const { setBrowserExtensionSupportEnabled } = await import('../browser-extension-support') const contexts = await import('../api-runtime/browser-extension-contexts') const eventDispatch = await import('../api-runtime/browser-extension-event-dispatch') diff --git a/src/main/browser/extensions/api/commands.ts b/src/main/browser/extensions/api/commands.ts index 2d360905381..8e21f2f3f33 100644 --- a/src/main/browser/extensions/api/commands.ts +++ b/src/main/browser/extensions/api/commands.ts @@ -22,7 +22,7 @@ import { resolveBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' import { runBrowserExtensionToolbarAction } from '../actions/browser-extension-toolbar' -import { noteBrowserExtensionUserGesture } from './permissions' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' function isOrcaShortcut(input: Electron.Input): boolean { const overrides = browserManager.getKeybindingOverrides() diff --git a/src/main/browser/extensions/api/cookies.ts b/src/main/browser/extensions/api/cookies.ts index 92e5d49c716..d28b9ca95f3 100644 --- a/src/main/browser/extensions/api/cookies.ts +++ b/src/main/browser/extensions/api/cookies.ts @@ -9,7 +9,7 @@ import { } from '../api-runtime/browser-extension-namespace-registry' import { hasBrowserExtensionHostPermission } from '../permissions/browser-extension-permission-grants' import { listBrowserExtensionTabs } from '../tabs-and-windows/browser-extension-tab-model' -import { browserExtensionHostPatternsInSession } from './permissions' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' /** Each extension session has one cookie store; Chrome names the regular store "0". */ const STORE_ID = '0' diff --git a/src/main/browser/extensions/api/declarative-net-request-test-match.ts b/src/main/browser/extensions/api/declarative-net-request-test-match.ts index 4b8dd84c158..564602f9bd9 100644 --- a/src/main/browser/extensions/api/declarative-net-request-test-match.ts +++ b/src/main/browser/extensions/api/declarative-net-request-test-match.ts @@ -1,9 +1,15 @@ import { z } from 'zod' import { createDnrRequestState } from '../declarative-net-request/request-state' import { DnrEngine } from '../declarative-net-request/engine' -import type { DnrHostAccess } from '../declarative-net-request/extension-matcher' -import { compareActions, type DnrRequestAction } from '../declarative-net-request/ruleset-matcher' -import { DNR_REQUEST_METHODS, DNR_RESOURCE_TYPES } from '../declarative-net-request/rule-types' +import type { DnrHostAccess } from '../declarative-net-request/matching/extension-matcher' +import { + compareActions, + type DnrRequestAction +} from '../declarative-net-request/matching/ruleset-matcher' +import { + DNR_REQUEST_METHODS, + DNR_RESOURCE_TYPES +} from '../declarative-net-request/rule-compilation/rule-types' import { BrowserExtensionApiError } from '../api-runtime/browser-extension-namespace-registry' import type { DnrExtensionRules } from '../declarative-net-request/session/browser-extension-dnr-extension-rules' import { DNR_ERRORS } from '../declarative-net-request/session/browser-extension-dnr-limits' diff --git a/src/main/browser/extensions/api/declarative-net-request.ts b/src/main/browser/extensions/api/declarative-net-request.ts index 010fef4770f..beaeba5e2a6 100644 --- a/src/main/browser/extensions/api/declarative-net-request.ts +++ b/src/main/browser/extensions/api/declarative-net-request.ts @@ -1,5 +1,5 @@ import { z } from 'zod' -import { isDnrRegexSupported } from '../declarative-net-request/regex-filter' +import { isDnrRegexSupported } from '../declarative-net-request/regex/regex-filter' import { hasBrowserExtensionActiveTab } from '../permissions/browser-extension-active-tab' import { DnrApiError, diff --git a/src/main/browser/extensions/api/management.test.ts b/src/main/browser/extensions/api/management.test.ts index e16e2e09e3d..96ff8bd8026 100644 --- a/src/main/browser/extensions/api/management.test.ts +++ b/src/main/browser/extensions/api/management.test.ts @@ -25,7 +25,9 @@ vi.mock('../browser-extension-management', () => ({ vi.mock('../installation/browser-extension-list-changes', () => ({ notifyBrowserExtensionListChanged: mocks.notify })) -vi.mock('./permissions', () => ({ hasBrowserExtensionUserGesture: () => mocks.gesture })) +vi.mock('../permissions/browser-extension-user-gesture', () => ({ + hasBrowserExtensionUserGesture: () => mocks.gesture +})) const registry = await import('../api-runtime/browser-extension-namespace-registry') const { registerManagementNamespace } = await import('./management') diff --git a/src/main/browser/extensions/api/management.ts b/src/main/browser/extensions/api/management.ts index 22dbc257e1d..be6cf127186 100644 --- a/src/main/browser/extensions/api/management.ts +++ b/src/main/browser/extensions/api/management.ts @@ -12,7 +12,7 @@ import { registerBrowserExtensionNamespace, type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' -import { hasBrowserExtensionUserGesture } from './permissions' +import { hasBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' /** * chrome.management for extensions that declare "management": Orca's installed list as the diff --git a/src/main/browser/extensions/api/notifications.test.ts b/src/main/browser/extensions/api/notifications.test.ts index 1f305468c42..4443dcd4b8b 100644 --- a/src/main/browser/extensions/api/notifications.test.ts +++ b/src/main/browser/extensions/api/notifications.test.ts @@ -31,13 +31,16 @@ vi.mock('../../../window/foreground-activation-policy', () => ({ isBackgroundLaunch: () => mocks.background })) vi.mock('../api-runtime/browser-extension-api-host', () => ({ emitBrowserExtensionEvent: vi.fn() })) -vi.mock('./permissions', () => ({ noteBrowserExtensionUserGesture: vi.fn() })) +vi.mock('../permissions/browser-extension-user-gesture', () => ({ + noteBrowserExtensionUserGesture: vi.fn() +})) const { registerNotificationsNamespace } = await import('./notifications') const { getBrowserExtensionNamespace } = await import('../api-runtime/browser-extension-namespace-registry') const { emitBrowserExtensionEvent } = await import('../api-runtime/browser-extension-api-host') -const { noteBrowserExtensionUserGesture } = await import('./permissions') +const { noteBrowserExtensionUserGesture } = + await import('../permissions/browser-extension-user-gesture') registerNotificationsNamespace() const extension = { id: 'a'.repeat(32), path: join('/ext', 'root') } diff --git a/src/main/browser/extensions/api/notifications.ts b/src/main/browser/extensions/api/notifications.ts index 067c8546ed3..e397022f9a5 100644 --- a/src/main/browser/extensions/api/notifications.ts +++ b/src/main/browser/extensions/api/notifications.ts @@ -14,7 +14,7 @@ import { registerBrowserExtensionNamespace, type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' -import { noteBrowserExtensionUserGesture } from './permissions' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' const optionsSchema = z .object({ diff --git a/src/main/browser/extensions/api/permissions.ts b/src/main/browser/extensions/api/permissions.ts index 79154866d1f..d575757ce9e 100644 --- a/src/main/browser/extensions/api/permissions.ts +++ b/src/main/browser/extensions/api/permissions.ts @@ -1,3 +1,5 @@ +import { readBrowserExtensionProfileGrants } from '../permissions/browser-extension-session-permissions' +import { hasBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' import { z } from 'zod' import { emitBrowserExtensionEvent, @@ -11,7 +13,6 @@ import { type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' import { - browserExtensionHostPatterns, containsBrowserExtensionPermissions, effectiveBrowserExtensionPermissions, planBrowserExtensionPermissionRemoval, @@ -25,10 +26,8 @@ import { getBrowserExtensionProfileStateStore } from '../profile-storage/browser import { getHostSessionState } from '../api-runtime/browser-extension-contexts' import { getBrowserExtensionContextSignal } from '../api-runtime/browser-extension-context-lifetime' import { getDnrSessionRuntime } from '../declarative-net-request/session/browser-extension-dnr-session' -import { observeBrowserExtensionWebRequests } from '../browser-extension-web-request' +import { observeBrowserExtensionWebRequests } from '../requests/browser-extension-web-request-observer' -const USER_GESTURE_WINDOW_MS = 5_000 -const recentGestures = new WeakMap() const pendingRequests = new Set() const permissionsSchema = z @@ -40,51 +39,6 @@ function gestureKey(profileId: string, extensionId: string): string { return `${profileId}\n${extensionId}` } -/** - * Chrome lets permissions.request run only inside a user gesture. Orca records the gestures it - * delivers to an extension (menu click, command, notification click, toolbar click). - */ -export function noteBrowserExtensionUserGesture( - session: Electron.Session, - extensionId: string -): void { - const state = getHostSessionState(session) - if (!state) { - return - } - const signal = getBrowserExtensionContextSignal(state, extensionId) - recentGestures.set(signal, Date.now()) -} - -export function hasBrowserExtensionUserGesture(caller: BrowserExtensionCaller): boolean { - if (caller.userGesture === true) { - return true - } - const state = getHostSessionState(caller.session) - if (!state) { - return false - } - const signal = getBrowserExtensionContextSignal(state, caller.extension.id) - const at = recentGestures.get(signal) - return at !== undefined && !signal.aborted && Date.now() - at <= USER_GESTURE_WINDOW_MS -} - -function readGrants(profileId: string, extensionId: string) { - return getBrowserExtensionProfileStateStore().read(profileId, extensionId) -} - -/** Manifest host patterns plus origins the user granted in this session's profile. */ -export function browserExtensionHostPatternsInSession( - extension: Electron.Extension, - session: Electron.Session -): string[] { - const profileId = getBrowserExtensionProfileIdForSession(session) - const grants = profileId - ? readGrants(profileId, extension.id) - : { grantedPermissions: [], grantedOrigins: [] } - return browserExtensionHostPatterns(extension.manifest, grants) -} - function emitChange( caller: BrowserExtensionCaller, event: 'onAdded' | 'onRemoved', @@ -108,7 +62,7 @@ async function request( const { extension, browserProfileId } = caller const plan = planBrowserExtensionPermissionRequest( extension.manifest, - readGrants(browserProfileId, extension.id), + readBrowserExtensionProfileGrants(browserProfileId, extension.id), wanted ) if (plan.kind === 'invalid') { @@ -161,7 +115,7 @@ async function remove( const { extension, browserProfileId } = caller const plan = planBrowserExtensionPermissionRemoval( extension.manifest, - readGrants(browserProfileId, extension.id), + readBrowserExtensionProfileGrants(browserProfileId, extension.id), wanted ) if (plan.kind === 'invalid') { @@ -178,21 +132,23 @@ async function remove( export function registerPermissionsNamespace(): void { setBrowserExtensionGrantedPermissionsLookup((extension, session) => { const profileId = getBrowserExtensionProfileIdForSession(session) - return profileId ? readGrants(profileId, extension.id).grantedPermissions : [] + return profileId + ? readBrowserExtensionProfileGrants(profileId, extension.id).grantedPermissions + : [] }) registerBrowserExtensionNamespace('permissions', { methods: { contains: defineBrowserExtensionMethod(z.tuple([permissionsSchema]), (caller, wanted) => containsBrowserExtensionPermissions( caller.extension.manifest, - readGrants(caller.browserProfileId, caller.extension.id), + readBrowserExtensionProfileGrants(caller.browserProfileId, caller.extension.id), wanted ) ), getAll: defineBrowserExtensionMethod(z.tuple([]), (caller) => effectiveBrowserExtensionPermissions( caller.extension.manifest, - readGrants(caller.browserProfileId, caller.extension.id) + readBrowserExtensionProfileGrants(caller.browserProfileId, caller.extension.id) ) ), request: defineBrowserExtensionMethod(z.tuple([permissionsSchema]), request), diff --git a/src/main/browser/extensions/api/runtime.ts b/src/main/browser/extensions/api/runtime.ts index 0c7d9c29919..4b0f8d16974 100644 --- a/src/main/browser/extensions/api/runtime.ts +++ b/src/main/browser/extensions/api/runtime.ts @@ -1,31 +1,9 @@ +import { openBrowserExtensionOptionsPage } from '../tabs-and-windows/browser-extension-options-page' import { z } from 'zod' -import { getChromeExtensionOrigin } from '../../../../shared/browser/extensions/browser-extension-url' import { - BrowserExtensionApiError, defineBrowserExtensionMethod, registerBrowserExtensionNamespace } from '../api-runtime/browser-extension-namespace-registry' -import { openBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' - -function optionsPagePath(extension: Electron.Extension): string | null { - const manifest: { options_ui?: { page?: unknown }; options_page?: unknown } = - extension.manifest ?? {} - const page = manifest.options_ui?.page ?? manifest.options_page - return typeof page === 'string' && page.length > 0 ? page : null -} - -/** Opens the extension's options page as an Orca tab in the given browser profile. */ -export async function openBrowserExtensionOptionsPage( - browserProfileId: string, - extension: Electron.Extension -): Promise { - const page = optionsPagePath(extension) - if (!page) { - throw new BrowserExtensionApiError('This extension has no options page') - } - const url = new URL(page.replace(/^\/+/, ''), `${getChromeExtensionOrigin(extension.id)}/`) - await openBrowserExtensionTab(browserProfileId, url.toString(), true) -} /** Only what Electron leaves unimplemented (lifecycle events: runtime-lifecycle); the rest is native. */ export function registerRuntimeNamespace(): void { diff --git a/src/main/browser/extensions/api/storage-sync.ts b/src/main/browser/extensions/api/storage-sync.ts index 16fc39273c2..17862c39604 100644 --- a/src/main/browser/extensions/api/storage-sync.ts +++ b/src/main/browser/extensions/api/storage-sync.ts @@ -6,10 +6,8 @@ import { registerBrowserExtensionNamespace, type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' -import { - getBrowserExtensionSyncStorageStore, - type BrowserExtensionSyncItems -} from '../profile-storage/browser-extension-sync-storage-store' +import { getBrowserExtensionSyncStorageStore } from '../profile-storage/browser-extension-sync-storage-store' +import type { BrowserExtensionProfileDocumentItems } from '../profile-storage/browser-extension-profile-document-store' /** * Electron disables chrome.storage.sync ("not available in this instance of Chrome"), so Orca @@ -50,7 +48,7 @@ function itemBytes(key: string, value: unknown): number { return Buffer.byteLength(key) + Buffer.byteLength(JSON.stringify(value)) } -function bytesInUse(items: BrowserExtensionSyncItems, keys: string[]): number { +function bytesInUse(items: BrowserExtensionProfileDocumentItems, keys: string[]): number { return keys.reduce( (total, key) => (Object.hasOwn(items, key) ? total + itemBytes(key, items[key]) : total), 0 @@ -65,15 +63,15 @@ function sameValue(left: unknown, right: unknown): boolean { return JSON.stringify(left) === JSON.stringify(right) } -function readItems(caller: BrowserExtensionCaller): BrowserExtensionSyncItems { +function readItems(caller: BrowserExtensionCaller): BrowserExtensionProfileDocumentItems { return getBrowserExtensionSyncStorageStore().read(caller.browserProfileId, caller.extension.id) } /** Saves `next`; returns and announces the changes for every key whose value differs. */ function commit( caller: BrowserExtensionCaller, - current: BrowserExtensionSyncItems, - next: BrowserExtensionSyncItems, + current: BrowserExtensionProfileDocumentItems, + next: BrowserExtensionProfileDocumentItems, keys: Iterable ): StorageChanges { const changes: StorageChanges = {} @@ -103,7 +101,7 @@ function commit( function get( caller: BrowserExtensionCaller, keys: z.infer -): BrowserExtensionSyncItems { +): BrowserExtensionProfileDocumentItems { const items = readItems(caller) if (keys == null) { return { ...items } @@ -113,7 +111,7 @@ function get( [keys].flat().flatMap((key) => (Object.hasOwn(items, key) ? [[key, items[key]]] : [])) ) } - const result: BrowserExtensionSyncItems = {} + const result: BrowserExtensionProfileDocumentItems = {} for (const [key, fallback] of Object.entries(keys)) { const value = Object.hasOwn(items, key) ? items[key] : toStoredValue(fallback) if (value !== undefined) { @@ -123,7 +121,10 @@ function get( return result } -function set(caller: BrowserExtensionCaller, input: BrowserExtensionSyncItems): StorageChanges { +function set( + caller: BrowserExtensionCaller, + input: BrowserExtensionProfileDocumentItems +): StorageChanges { const current = readItems(caller) const next = { ...current } let total = bytesInUse(current, Object.keys(current)) diff --git a/src/main/browser/extensions/api/tabs-capture.test.ts b/src/main/browser/extensions/api/tabs-capture.test.ts index df386f80fd7..407758f63b6 100644 --- a/src/main/browser/extensions/api/tabs-capture.test.ts +++ b/src/main/browser/extensions/api/tabs-capture.test.ts @@ -28,7 +28,7 @@ vi.mock('../tabs-and-windows/browser-extension-window-model', () => ({ WINDOW_ID_CURRENT: -2, getBrowserExtensionWindow: (id: number) => (mocks.windows.has(id) ? {} : null) })) -vi.mock('./permissions', () => ({ +vi.mock('../permissions/browser-extension-session-permissions', () => ({ browserExtensionHostPatternsInSession: () => mocks.hostPatterns })) vi.mock('../permissions/browser-extension-active-tab', () => ({ diff --git a/src/main/browser/extensions/api/tabs-capture.ts b/src/main/browser/extensions/api/tabs-capture.ts index 0b5386de259..976eeaa7b07 100644 --- a/src/main/browser/extensions/api/tabs-capture.ts +++ b/src/main/browser/extensions/api/tabs-capture.ts @@ -17,7 +17,7 @@ import { WINDOW_ID_CURRENT, getBrowserExtensionWindow } from '../tabs-and-windows/browser-extension-window-model' -import { browserExtensionHostPatternsInSession } from './permissions' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' // Chrome's default JPEG quality for tabs.captureVisibleTab. const DEFAULT_JPEG_QUALITY = 90 diff --git a/src/main/browser/extensions/api/tabs.ts b/src/main/browser/extensions/api/tabs.ts index 04d1e8f34f9..b69233ca4d3 100644 --- a/src/main/browser/extensions/api/tabs.ts +++ b/src/main/browser/extensions/api/tabs.ts @@ -1,6 +1,7 @@ /// +import { requireOpenableUrl } from '../tabs-and-windows/browser-extension-requested-navigation' + import { z } from 'zod' -import { resolveBrowserExtensionRequestedUrl } from '../../../../shared/browser/extensions/browser-extension-url' import { BrowserExtensionApiError, defineBrowserExtensionMethod, @@ -76,22 +77,6 @@ const updatePropertiesSchema = z .partial() .loose() -/** Resolves an extension-requested URL through Orca's rules; extension pages must be loaded in `sess`. */ -export function requireOpenableUrl( - caller: BrowserExtensionCaller, - rawUrl: string | undefined, - sess: Electron.Session -): string { - const resolved = resolveBrowserExtensionRequestedUrl(rawUrl, caller.extension.id) - if ( - !resolved || - (resolved.kind === 'extension' && !sess.extensions.getExtension(resolved.extensionId)) - ) { - throw new BrowserExtensionApiError(`Cannot open URL: ${rawUrl ?? ''}`) - } - return resolved.url -} - async function createTab( caller: BrowserExtensionCaller, url: string, diff --git a/src/main/browser/extensions/api/web-navigation.ts b/src/main/browser/extensions/api/web-navigation.ts index 50959520698..d9b28b16b79 100644 --- a/src/main/browser/extensions/api/web-navigation.ts +++ b/src/main/browser/extensions/api/web-navigation.ts @@ -1,4 +1,9 @@ /// +import { + chromeFrameId, + chromeFrameDocument +} from '../tabs-and-windows/browser-extension-frame-projection' + import { webFrameMain } from 'electron' import { z } from 'zod' import { emitBrowserExtensionEvent } from '../api-runtime/browser-extension-api-host' @@ -19,32 +24,6 @@ import { resolveBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' -/** - * Chrome frame ids: 0 for a tab's main frame, the frame-tree-node id otherwise. Electron's own - * content-script `sender.frameId` uses the same numbering, so tabs.sendMessage targets line up. - */ -export function chromeFrameId(frame: Electron.WebFrameMain): number { - return frame.parent ? frame.frameTreeNodeId : 0 -} - -function chromeParentFrameId(frame: Electron.WebFrameMain): number { - return frame.parent ? chromeFrameId(frame.parent) : -1 -} - -/** Chrome's frame fields; `documentId` is left out where the document does not exist yet. */ -export function chromeFrameDocument(frame: Electron.WebFrameMain, withDocument: boolean) { - return { - frameId: chromeFrameId(frame), - parentFrameId: chromeParentFrameId(frame), - ...(withDocument ? { documentId: getBrowserExtensionDocumentId(frame.frameTreeNodeId) } : {}), - ...(frame.parent - ? { parentDocumentId: getBrowserExtensionDocumentId(frame.parent.frameTreeNodeId) } - : {}), - frameType: frame.parent ? ('sub_frame' as const) : ('outermost_frame' as const), - documentLifecycle: 'active' as const - } -} - function frameDetails( tabId: number, frame: Electron.WebFrameMain, diff --git a/src/main/browser/extensions/api/windows.ts b/src/main/browser/extensions/api/windows.ts index dec336d5512..dcf3834777f 100644 --- a/src/main/browser/extensions/api/windows.ts +++ b/src/main/browser/extensions/api/windows.ts @@ -21,7 +21,7 @@ import { presentBrowserExtensionWindow, type BrowserExtensionWindowEntry } from '../tabs-and-windows/browser-extension-window-model' -import { requireOpenableUrl } from './tabs' +import { requireOpenableUrl } from '../tabs-and-windows/browser-extension-requested-navigation' const windowIdSchema = z.number().int() const queryOptionsSchema = z diff --git a/src/main/browser/extensions/browser-extension-management.test.ts b/src/main/browser/extensions/browser-extension-management.test.ts index 356326785cd..f93accf963a 100644 --- a/src/main/browser/extensions/browser-extension-management.test.ts +++ b/src/main/browser/extensions/browser-extension-management.test.ts @@ -23,7 +23,9 @@ vi.mock('../sessions/browser-session-registry', () => ({ getProfile: () => ({ id: 'default' }) } })) -vi.mock('./api/runtime', () => ({ openBrowserExtensionOptionsPage: vi.fn() })) +vi.mock('./tabs-and-windows/browser-extension-options-page', () => ({ + openBrowserExtensionOptionsPage: vi.fn() +})) vi.mock('./installation/browser-extension-install-store', () => ({ getBrowserExtensionInstallStore: () => mocks.store })) diff --git a/src/main/browser/extensions/browser-extension-management.ts b/src/main/browser/extensions/browser-extension-management.ts index c6ef6cfdec6..31267be9a85 100644 --- a/src/main/browser/extensions/browser-extension-management.ts +++ b/src/main/browser/extensions/browser-extension-management.ts @@ -5,7 +5,7 @@ import type { InstalledBrowserExtension } from '../../../shared/browser/extensions/browser-extension-types' import { browserSessionRegistry } from '../sessions/browser-session-registry' -import { openBrowserExtensionOptionsPage } from './api/runtime' +import { openBrowserExtensionOptionsPage } from './tabs-and-windows/browser-extension-options-page' import { getBrowserExtensionInstallStore } from './installation/browser-extension-install-store' import { reloadBrowserExtensionWhereEnabled } from './profile-sessions/browser-extension-profile-reload' import { @@ -32,7 +32,7 @@ import { } from './profile-sessions/browser-extension-load-errors' import { notifyBrowserExtensionListChanged } from './installation/browser-extension-list-changes' import { reviewHeldBrowserExtensionUpdate } from './web-store/browser-extension-webstore-updater' -import { withBrowserExtensionLock } from './installation/browser-extension-webstore-install' +import { withBrowserExtensionLock } from './installation/browser-extension-mutation-lock' import { isBrowserExtensionSupportEnabled } from './browser-extension-support' import { withExtensionEnabled, diff --git a/src/main/browser/extensions/browser-extension-startup.ts b/src/main/browser/extensions/browser-extension-startup.ts index 340d29d7245..6a740be8901 100644 --- a/src/main/browser/extensions/browser-extension-startup.ts +++ b/src/main/browser/extensions/browser-extension-startup.ts @@ -17,7 +17,7 @@ import { } from './profile-sessions/browser-extension-session-loader' import { notifyBrowserExtensionActionsChanged } from './actions/browser-extension-action-registry' import { registerBrowserExtensionNamespaces } from './register-browser-extension-namespaces' -import { observeBrowserExtensionTabLifecycle } from './api/tabs-lifecycle' +import { observeBrowserExtensionTabLifecycle } from './tabs-and-windows/browser-extension-tab-lifecycle' import { observeBrowserExtensionWebNavigation } from './api/web-navigation' import { observeBrowserExtensionCommands } from './api/commands' import { observeBrowserExtensionDnrContents } from './declarative-net-request/session/browser-extension-dnr-contents' diff --git a/src/main/browser/extensions/browser-extension-web-request.ts b/src/main/browser/extensions/browser-extension-web-request.ts deleted file mode 100644 index 43df3da9131..00000000000 --- a/src/main/browser/extensions/browser-extension-web-request.ts +++ /dev/null @@ -1,305 +0,0 @@ -import { CHROME_WEB_STORE_ORIGIN } from '../../../shared/browser/extensions/browser-extension-webstore' -import { - installBrowserSessionHeadersReceived, - installBrowserSessionRequestLifecycle, - removeBrowserSessionHeadersReceived, - removeBrowserSessionRequestLifecycle -} from '../sessions/requests/browser-session-request-decisions' -import { - setBrowserSessionWebRequestObserver, - type ObservedWebRequestDetails, - type ObservedWebRequestEvent -} from '../sessions/requests/browser-session-web-request-observer' -import { chromeFrameDocument } from './api/web-navigation' -import { browserExtensionHostPatternsInSession } from './api/permissions' -import { - emitBrowserExtensionEvent, - getBrowserExtensionProfileIdForSession -} from './api-runtime/browser-extension-api-host' -import { browserExtensionEventHasListener } from './api-runtime/browser-extension-contexts' -import { matchesExtensionMatchPattern } from './permissions/browser-extension-match-pattern' -import { extensionHasPermission } from './api-runtime/browser-extension-namespace-registry' -import { hasBrowserExtensionHostPermission } from './permissions/browser-extension-permission-grants' -import { canExtensionAccessRequest } from './permissions/browser-extension-request-host-access' -import { resolveBrowserExtensionTab } from './tabs-and-windows/browser-extension-tab-model' - -/** - * chrome.webRequest, observed rather than blocking. Electron 43 delivers no webRequest events to - * MV3 workers, and Orca's own session handlers switch Electron's extension webRequest off anyway, - * so Orca forwards what its handlers see. MV3 store extensions cannot block requests in Chrome - * either (webRequestBlocking is policy-only), so nothing they could do is lost. - */ - -type ChromeResourceType = - | 'main_frame' - | 'sub_frame' - | 'stylesheet' - | 'script' - | 'image' - | 'font' - | 'object' - | 'xmlhttprequest' - | 'ping' - | 'csp_report' - | 'media' - | 'websocket' - | 'other' - -const CHROME_RESOURCE_TYPES = new Map([ - ['mainFrame', 'main_frame'], - ['subFrame', 'sub_frame'], - ['stylesheet', 'stylesheet'], - ['script', 'script'], - ['image', 'image'], - ['font', 'font'], - ['object', 'object'], - ['xhr', 'xmlhttprequest'], - ['ping', 'ping'], - ['cspReport', 'csp_report'], - ['media', 'media'], - ['webSocket', 'websocket'] -]) - -/** Electron's resourceType → Chrome's, shared by webRequest and declarativeNetRequest. */ -export function chromeResourceType(resourceType: string): ChromeResourceType { - return CHROME_RESOURCE_TYPES.get(resourceType) ?? 'other' -} - -// Chrome hides these unless a listener asks for 'extraHeaders'. -const HIDDEN_REQUEST_HEADERS = new Set(['accept-language', 'accept-encoding', 'referer', 'cookie']) -const HIDDEN_RESPONSE_HEADERS = new Set(['set-cookie']) - -export type ChromeWebRequestDetails = { - requestId: string - url: string - method: string - frameId: number - parentFrameId: number - tabId: number - windowId: number - type: string - timeStamp: number - frameType?: 'outermost_frame' | 'sub_frame' - documentId?: string - parentDocumentId?: string - documentLifecycle?: 'active' - requestHeaders?: { name: string; value: string }[] - responseHeaders?: { name: string; value: string }[] - statusCode?: number - statusLine?: string - fromCache?: boolean - ip?: string - redirectUrl?: string - error?: string -} - -function requestHeaderList(headers: Record): { name: string; value: string }[] { - return Object.entries(headers) - .filter(([name]) => !HIDDEN_REQUEST_HEADERS.has(name.toLowerCase())) - .map(([name, value]) => ({ name, value })) -} - -function responseHeaderList(headers: Record): { name: string; value: string }[] { - return Object.entries(headers) - .filter(([name]) => !HIDDEN_RESPONSE_HEADERS.has(name.toLowerCase())) - .flatMap(([name, values]) => values.map((value) => ({ name, value }))) -} - -type WebRequestFrameFields = Pick< - ChromeWebRequestDetails, - | 'frameId' - | 'parentFrameId' - | 'frameType' - | 'documentId' - | 'parentDocumentId' - | 'documentLifecycle' -> - -/** A navigation request has no document yet; any other request belongs to its frame's current one. */ -function frameFields(details: ObservedWebRequestDetails): WebRequestFrameFields { - if (details.resourceType === 'mainFrame') { - return { - frameId: 0, - parentFrameId: -1, - frameType: 'outermost_frame', - documentLifecycle: 'active' - } - } - const frame = details.frame && !details.frame.isDestroyed() ? details.frame : null - return frame - ? chromeFrameDocument(frame, details.resourceType !== 'subFrame') - : { frameId: 0, parentFrameId: -1 } -} - -export function toChromeWebRequestDetails( - details: ObservedWebRequestDetails, - tab: { tabId: number; windowId: number }, - frame: WebRequestFrameFields -): ChromeWebRequestDetails { - const type = chromeResourceType(details.resourceType) - return { - requestId: String(details.id), - url: details.url, - method: details.method, - ...frame, - ...tab, - type, - timeStamp: details.timestamp, - ...(details.requestHeaders - ? { requestHeaders: requestHeaderList(details.requestHeaders) } - : {}), - ...(details.responseHeaders - ? { responseHeaders: responseHeaderList(details.responseHeaders) } - : {}), - ...(details.statusCode !== undefined ? { statusCode: details.statusCode } : {}), - ...(details.statusLine !== undefined ? { statusLine: details.statusLine } : {}), - ...(details.fromCache !== undefined ? { fromCache: details.fromCache } : {}), - ...(details.ip ? { ip: details.ip } : {}), - ...(details.redirectURL ? { redirectUrl: details.redirectURL } : {}), - ...(details.error ? { error: details.error } : {}) - } -} - -/** Main-side pre-filter against one listener's chrome.webRequest.RequestFilter. */ -export function webRequestFilterMatches( - filter: unknown, - details: ChromeWebRequestDetails -): boolean { - if (filter === null || typeof filter !== 'object') { - return true - } - const fields = new Map(Object.entries(filter)) - const urls = fields.get('urls') - if ( - Array.isArray(urls) && - !urls.some( - (pattern) => typeof pattern === 'string' && matchesExtensionMatchPattern(pattern, details.url) - ) - ) { - return false - } - const types = fields.get('types') - if (Array.isArray(types) && !types.includes(details.type)) { - return false - } - const tabId = fields.get('tabId') - const windowId = fields.get('windowId') - return ( - (typeof tabId !== 'number' || tabId === details.tabId) && - (typeof windowId !== 'number' || windowId === details.windowId) - ) -} - -const WEB_URL = /^(?:https?|wss?):/i - -/** WebRequestPermissions::HideRequest: requests extensions never see or act on. */ -export function isRequestHiddenFromExtensions(details: { - url: string - webContentsId?: number - initiatorOrigin?: string -}): boolean { - if (!WEB_URL.test(details.url)) { - return true - } - // Orca's own main-process requests carry neither a webContents nor an initiator. - if (details.webContentsId === undefined && details.initiatorOrigin === undefined) { - return true - } - return ( - details.url.startsWith(`${CHROME_WEB_STORE_ORIGIN}/`) || - details.url.startsWith('https://chrome.google.com/webstore') - ) -} - -function forward( - session: Electron.Session, - event: ObservedWebRequestEvent, - details: ObservedWebRequestDetails -): void { - if ( - isRequestHiddenFromExtensions(details) || - !getBrowserExtensionProfileIdForSession(session) || - !browserExtensionEventHasListener(session, 'webRequest', event) - ) { - return - } - const entry = - details.webContentsId === undefined ? null : resolveBrowserExtensionTab(details.webContentsId) - const chromeDetails = toChromeWebRequestDetails( - details, - entry ? { tabId: entry.contents.id, windowId: entry.windowId } : { tabId: -1, windowId: -1 }, - frameFields(details) - ) - const request = { - url: details.url, - initiator: details.initiatorOrigin ?? null, - tabId: chromeDetails.tabId, - type: chromeDetails.type - } - emitBrowserExtensionEvent( - { session }, - 'webRequest', - event, - (extension) => { - const patterns = browserExtensionHostPatternsInSession(extension, session) - return canExtensionAccessRequest(extension.id, request, (url) => - hasBrowserExtensionHostPermission(patterns, url) - ) - ? [chromeDetails] - : null - }, - (filter) => webRequestFilterMatches(filter, chromeDetails) - ) -} - -const observedSessions = new WeakSet() -const watchedSessions = new WeakSet() -const OBSERVE_ALL = { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] } - -/** The events Orca does not otherwise handle, installed once a webRequest extension loads. */ -function observeRemainingEvents(session: Electron.Session): void { - if (observedSessions.has(session)) { - return - } - observedSessions.add(session) - const { webRequest } = session - webRequest.onSendHeaders(OBSERVE_ALL, (details) => forward(session, 'onSendHeaders', details)) - installBrowserSessionHeadersReceived(session) - webRequest.onResponseStarted(OBSERVE_ALL, (details) => - forward(session, 'onResponseStarted', details) - ) - webRequest.onBeforeRedirect(OBSERVE_ALL, (details) => - forward(session, 'onBeforeRedirect', details) - ) - installBrowserSessionRequestLifecycle(session) -} - -export function observeBrowserExtensionWebRequests(session: Electron.Session): void { - const maybeObserve = (extension: Electron.Extension): void => { - if (extensionHasPermission(extension, 'webRequest', session)) { - observeRemainingEvents(session) - } - } - if (!watchedSessions.has(session)) { - watchedSessions.add(session) - session.extensions.on('extension-ready', (_event, extension) => maybeObserve(extension)) - } - session.extensions.getAllExtensions().forEach(maybeObserve) -} - -/** Extensions turned off: hand the session's request path back to Orca's own handlers alone. */ -export function stopObservingBrowserExtensionWebRequests(session: Electron.Session): void { - removeBrowserSessionHeadersReceived(session) - removeBrowserSessionRequestLifecycle(session) - if (!observedSessions.delete(session)) { - return - } - const { webRequest } = session - webRequest.onSendHeaders(null) - webRequest.onResponseStarted(null) - webRequest.onBeforeRedirect(null) -} - -export function installBrowserExtensionWebRequestForwarding(): void { - setBrowserSessionWebRequestObserver(forward) -} diff --git a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts index ee17628fa2e..47ef817d418 100644 --- a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts +++ b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts @@ -7,8 +7,12 @@ const mocks = vi.hoisted(() => ({ })) const VAULT = 'a'.repeat(32) -vi.mock('../api/web-navigation', () => ({ chromeFrameId: () => 0 })) -vi.mock('../api/permissions', () => ({ noteBrowserExtensionUserGesture: vi.fn() })) +vi.mock('../tabs-and-windows/browser-extension-frame-projection', () => ({ + chromeFrameId: () => 0 +})) +vi.mock('../permissions/browser-extension-user-gesture', () => ({ + noteBrowserExtensionUserGesture: vi.fn() +})) vi.mock('../api-runtime/browser-extension-api-host', () => ({ emitBrowserExtensionEvent: mocks.emit, getBrowserExtensionProfileIdForSession: () => 'default' @@ -37,7 +41,6 @@ vi.mock('../tabs-and-windows/browser-extension-tab-model', () => ({ resolveBrowserExtensionTab: () => null, describeBrowserExtensionTab: vi.fn() })) - import { createContextMenuItem } from './browser-extension-context-menu-model' import * as menuHost from './browser-extension-context-menu-host' diff --git a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts index 4e748f9d52c..892d6d346a7 100644 --- a/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts +++ b/src/main/browser/extensions/context-menus/browser-extension-context-menu-host.ts @@ -4,8 +4,8 @@ import type { BrowserExtensionContextMenuGroup, BrowserExtensionContextMenuPayload } from '../../../../shared/browser/extensions/browser-extension-context-menu-types' -import { chromeFrameId } from '../api/web-navigation' -import { noteBrowserExtensionUserGesture } from '../api/permissions' +import { chromeFrameId } from '../tabs-and-windows/browser-extension-frame-projection' +import { noteBrowserExtensionUserGesture } from '../permissions/browser-extension-user-gesture' import { emitBrowserExtensionEvent, getBrowserExtensionProfileIdForSession diff --git a/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts b/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts index 7d1b9380cba..11daab5e627 100644 --- a/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts +++ b/src/main/browser/extensions/declarative-net-request/engine-stages.test.ts @@ -1,10 +1,10 @@ import { describe, expect, it } from 'vitest' import { createDnrRequestState } from './request-state' import { DnrEngine } from './engine' -import { applyDnrRequestHeaderActions } from './header-modification' +import { applyDnrRequestHeaderActions } from './header-actions/header-modification' import type { DnrRequestInfo } from './request-context' -import type { DnrRule } from './rule-types' -import { buildDnrRuleset } from './ruleset-builder' +import type { DnrRule } from './rule-compilation/rule-types' +import { buildDnrRuleset } from './rule-compilation/ruleset-builder' const OLD = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' const NEW = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' diff --git a/src/main/browser/extensions/declarative-net-request/engine.test.ts b/src/main/browser/extensions/declarative-net-request/engine.test.ts index 7caf03bf64a..cea3c2e0cc5 100644 --- a/src/main/browser/extensions/declarative-net-request/engine.test.ts +++ b/src/main/browser/extensions/declarative-net-request/engine.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it } from 'vitest' import { createDnrRequestState } from './request-state' import { DnrEngine, type DnrEvaluateOptions } from './engine' import type { DnrRequestInfo } from './request-context' -import type { DnrRule, DnrRulesetSource } from './rule-types' -import { buildDnrRuleset } from './ruleset-builder' +import type { DnrRule, DnrRulesetSource } from './rule-compilation/rule-types' +import { buildDnrRuleset } from './rule-compilation/ruleset-builder' const OLD = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' diff --git a/src/main/browser/extensions/declarative-net-request/engine.ts b/src/main/browser/extensions/declarative-net-request/engine.ts index 4e7bb97ac82..66431fb0d7e 100644 --- a/src/main/browser/extensions/declarative-net-request/engine.ts +++ b/src/main/browser/extensions/declarative-net-request/engine.ts @@ -2,8 +2,8 @@ import { DnrExtensionMatcher, type DnrFrameAllowState, type DnrHostAccess -} from './extension-matcher' -import { sameDomainOrHost } from './domain-matching' +} from './matching/extension-matcher' +import { sameDomainOrHost } from './matching/domain-matching' import { createDnrRequestContext, dnrOriginHost, @@ -11,8 +11,8 @@ import { type DnrRequestInfo, type DnrResponseHeaders } from './request-context' -import { DnrCandidatePostings } from './candidate-postings' -import type { DnrRulesetIndex } from './ruleset-index' +import { DnrCandidatePostings } from './indexing/candidate-postings' +import type { DnrRulesetIndex } from './indexing/ruleset-index' import { crossExtensionRank, emptyDnrEvaluation, @@ -25,8 +25,8 @@ import { DnrRulesetMatcher, type DnrRequestAction, type DnrStage -} from './ruleset-matcher' -import type { DnrRulesetSource } from './rule-types' +} from './matching/ruleset-matcher' +import type { DnrRulesetSource } from './rule-compilation/rule-types' // RulesetManager (ruleset_manager.cc) plus the per-request bookkeeping WebRequestInfo keeps // between stages (see request-state.ts). diff --git a/src/main/browser/extensions/declarative-net-request/header-modification.ts b/src/main/browser/extensions/declarative-net-request/header-actions/header-modification.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/header-modification.ts rename to src/main/browser/extensions/declarative-net-request/header-actions/header-modification.ts index a6591cb454f..e9f11134eab 100644 --- a/src/main/browser/extensions/declarative-net-request/header-modification.ts +++ b/src/main/browser/extensions/declarative-net-request/header-actions/header-modification.ts @@ -1,5 +1,5 @@ import { REQUEST_HEADER_APPEND_DELIMITERS, type DnrHeaderModification } from './header-rules' -import type { DnrRequestAction } from './ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' // Applies modifyHeaders actions the way web_request_api_helpers.cc does // (ModifyRequestHeadersForAction, ModifyResponseHeadersForAction, DNRHeaderAction). diff --git a/src/main/browser/extensions/declarative-net-request/header-rules.ts b/src/main/browser/extensions/declarative-net-request/header-actions/header-rules.ts similarity index 94% rename from src/main/browser/extensions/declarative-net-request/header-rules.ts rename to src/main/browser/extensions/declarative-net-request/header-actions/header-rules.ts index c3c9ec95050..090f01a21f3 100644 --- a/src/main/browser/extensions/declarative-net-request/header-rules.ts +++ b/src/main/browser/extensions/declarative-net-request/header-actions/header-rules.ts @@ -1,6 +1,10 @@ -import { dnrRuleProblem, type DnrRuleProblem } from './parse-errors' -import type { DnrHeaderInfo, DnrHeaderOperation, DnrModifyHeaderInfo } from './rule-types' -import { toLowerAscii } from './url-text' +import { dnrRuleProblem, type DnrRuleProblem } from '../rule-compilation/parse-errors' +import type { + DnrHeaderInfo, + DnrHeaderOperation, + DnrModifyHeaderInfo +} from '../rule-compilation/rule-types' +import { toLowerAscii } from '../matching/url-text' // Header validation from indexed_rule.cc (ValidateHeadersForModification, // ValidateResponseHeadersForMatching) and the request-header append allowlist with each diff --git a/src/main/browser/extensions/declarative-net-request/candidate-postings.ts b/src/main/browser/extensions/declarative-net-request/indexing/candidate-postings.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/candidate-postings.ts rename to src/main/browser/extensions/declarative-net-request/indexing/candidate-postings.ts index 56a141cf882..040249be382 100644 --- a/src/main/browser/extensions/declarative-net-request/candidate-postings.ts +++ b/src/main/browser/extensions/declarative-net-request/indexing/candidate-postings.ts @@ -1,4 +1,4 @@ -import type { DnrRequestContext } from './request-context' +import type { DnrRequestContext } from '../request-context' import type { DnrRulePartition, DnrRulesetIndex } from './ruleset-index' // Engine-wide inverted index over every attached ruleset: n-gram id or domain -> the partitions diff --git a/src/main/browser/extensions/declarative-net-request/ngram-dictionary.ts b/src/main/browser/extensions/declarative-net-request/indexing/ngram-dictionary.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/ngram-dictionary.ts rename to src/main/browser/extensions/declarative-net-request/indexing/ngram-dictionary.ts diff --git a/src/main/browser/extensions/declarative-net-request/ruleset-index.ts b/src/main/browser/extensions/declarative-net-request/indexing/ruleset-index.ts similarity index 96% rename from src/main/browser/extensions/declarative-net-request/ruleset-index.ts rename to src/main/browser/extensions/declarative-net-request/indexing/ruleset-index.ts index 93200a76ef4..d022f52d441 100644 --- a/src/main/browser/extensions/declarative-net-request/ruleset-index.ts +++ b/src/main/browser/extensions/declarative-net-request/indexing/ruleset-index.ts @@ -1,8 +1,8 @@ -import { hostLabelSuffixes, type DnrDomainList } from './domain-matching' -import type { DnrIndexedRule } from './indexed-rule' +import { hostLabelSuffixes, type DnrDomainList } from '../matching/domain-matching' +import type { DnrIndexedRule } from '../rule-compilation/indexed-rule' import { dnrNgramDictionary, patternNgrams } from './ngram-dictionary' -import type { DnrRequestContext } from './request-context' -import { toLowerAscii } from './url-text' +import type { DnrRequestContext } from '../request-context' +import { toLowerAscii } from '../matching/url-text' // One url_pattern_index (url_pattern_index.cc UrlPatternIndexBuilder): rules keyed by a 5-gram // of their filter. Rules without one are keyed by an included request or initiator domain, diff --git a/src/main/browser/extensions/declarative-net-request/domain-matching.ts b/src/main/browser/extensions/declarative-net-request/matching/domain-matching.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/domain-matching.ts rename to src/main/browser/extensions/declarative-net-request/matching/domain-matching.ts diff --git a/src/main/browser/extensions/declarative-net-request/extension-matcher.ts b/src/main/browser/extensions/declarative-net-request/matching/extension-matcher.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/extension-matcher.ts rename to src/main/browser/extensions/declarative-net-request/matching/extension-matcher.ts index da2b2371b35..8e38a49a07c 100644 --- a/src/main/browser/extensions/declarative-net-request/extension-matcher.ts +++ b/src/main/browser/extensions/declarative-net-request/matching/extension-matcher.ts @@ -1,4 +1,4 @@ -import type { DnrRequestContext } from './request-context' +import type { DnrRequestContext } from '../request-context' import { compareActions, isAllowAction, diff --git a/src/main/browser/extensions/declarative-net-request/rule-matching.ts b/src/main/browser/extensions/declarative-net-request/matching/rule-matching.ts similarity index 95% rename from src/main/browser/extensions/declarative-net-request/rule-matching.ts rename to src/main/browser/extensions/declarative-net-request/matching/rule-matching.ts index 5ec676d9cfa..fea70d5dd5e 100644 --- a/src/main/browser/extensions/declarative-net-request/rule-matching.ts +++ b/src/main/browser/extensions/declarative-net-request/matching/rule-matching.ts @@ -1,7 +1,7 @@ import { hostMatchesDomainLists } from './domain-matching' -import type { DnrHeaderCondition } from './header-rules' -import type { DnrIndexedRule } from './indexed-rule' -import type { DnrRequestContext } from './request-context' +import type { DnrHeaderCondition } from '../header-actions/header-rules' +import type { DnrIndexedRule } from '../rule-compilation/indexed-rule' +import type { DnrRequestContext } from '../request-context' // Per-rule checks from url_pattern_index.cc (DoesRuleFlagsMatch, DoesOriginMatchInitiatorDomainList, // DoesURLMatchRequestDomainList) and request_params.cc DoEmbedderConditionsMatch. diff --git a/src/main/browser/extensions/declarative-net-request/ruleset-matcher.ts b/src/main/browser/extensions/declarative-net-request/matching/ruleset-matcher.ts similarity index 92% rename from src/main/browser/extensions/declarative-net-request/ruleset-matcher.ts rename to src/main/browser/extensions/declarative-net-request/matching/ruleset-matcher.ts index 8cf3f82bf9e..3d49c2f2c51 100644 --- a/src/main/browser/extensions/declarative-net-request/ruleset-matcher.ts +++ b/src/main/browser/extensions/declarative-net-request/matching/ruleset-matcher.ts @@ -1,13 +1,17 @@ -import type { DnrHeaderModification } from './header-rules' -import type { DnrIndexedRule } from './indexed-rule' -import { transformDnrUrl, upgradeDnrUrl } from './redirect-url' -import { applyRegexSubstitution } from './regex-filter' -import { isCollapsibleType, type DnrRequestContext } from './request-context' -import { ELEMENT_TYPE } from './rule-flags' +import type { DnrHeaderModification } from '../header-actions/header-rules' +import type { DnrIndexedRule } from '../rule-compilation/indexed-rule' +import { transformDnrUrl, upgradeDnrUrl } from '../redirect-actions/redirect-url' +import { applyRegexSubstitution } from '../regex/regex-filter' +import { isCollapsibleType, type DnrRequestContext } from '../request-context' +import { ELEMENT_TYPE } from '../rule-compilation/rule-flags' import { regexRuleMetadataMatches, urlRuleMatches } from './rule-matching' -import { compareRulePriority, type DnrRulePartition, type DnrRulesetIndex } from './ruleset-index' -import type { DnrRulesetSource } from './rule-types' -import { dnrPublicRulesetId, dnrRulesetOrdinal } from './rule-types' +import { + compareRulePriority, + type DnrRulePartition, + type DnrRulesetIndex +} from '../indexing/ruleset-index' +import type { DnrRulesetSource } from '../rule-compilation/rule-types' +import { dnrPublicRulesetId, dnrRulesetOrdinal } from '../rule-compilation/rule-types' // One ruleset's matcher: ruleset_matcher.cc, extension_url_pattern_index_matcher.cc, // regex_rules_matcher.cc and ruleset_matcher_base.cc. diff --git a/src/main/browser/extensions/declarative-net-request/url-pattern.test.ts b/src/main/browser/extensions/declarative-net-request/matching/url-pattern.test.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/url-pattern.test.ts rename to src/main/browser/extensions/declarative-net-request/matching/url-pattern.test.ts diff --git a/src/main/browser/extensions/declarative-net-request/url-pattern.ts b/src/main/browser/extensions/declarative-net-request/matching/url-pattern.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/url-pattern.ts rename to src/main/browser/extensions/declarative-net-request/matching/url-pattern.ts diff --git a/src/main/browser/extensions/declarative-net-request/url-text.ts b/src/main/browser/extensions/declarative-net-request/matching/url-text.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/url-text.ts rename to src/main/browser/extensions/declarative-net-request/matching/url-text.ts diff --git a/src/main/browser/extensions/declarative-net-request/redirect-url.test.ts b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts similarity index 94% rename from src/main/browser/extensions/declarative-net-request/redirect-url.test.ts rename to src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts index cdadd533660..bb32dd224b4 100644 --- a/src/main/browser/extensions/declarative-net-request/redirect-url.test.ts +++ b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest' -import { sameDomainOrHost } from './domain-matching' +import { sameDomainOrHost } from '../matching/domain-matching' import { parseDnrRedirect, transformDnrUrl } from './redirect-url' -import { isDnrRuleProblem } from './parse-errors' -import type { DnrUrlTransform } from './rule-types' +import { isDnrRuleProblem } from '../rule-compilation/parse-errors' +import type { DnrUrlTransform } from '../rule-compilation/rule-types' function transform(url: string, spec: DnrUrlTransform): string | null { const parsed = parseDnrRedirect({ transform: spec }, 1, 'ext') diff --git a/src/main/browser/extensions/declarative-net-request/redirect-url.ts b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/redirect-url.ts rename to src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.ts index be584833a37..e3087ffdd7f 100644 --- a/src/main/browser/extensions/declarative-net-request/redirect-url.ts +++ b/src/main/browser/extensions/declarative-net-request/redirect-actions/redirect-url.ts @@ -1,5 +1,5 @@ -import { dnrRuleProblem, type DnrRuleProblem } from './parse-errors' -import type { DnrRedirect, DnrUrlTransform } from './rule-types' +import { dnrRuleProblem, type DnrRuleProblem } from '../rule-compilation/parse-errors' +import type { DnrRedirect, DnrUrlTransform } from '../rule-compilation/rule-types' // Redirect parsing (indexed_rule.cc ParseRedirect/ValidateTransform, flat_ruleset_indexer.cc // BuildTransformOffset) and application (ruleset_matcher_base.cc GetTransformedURL, diff --git a/src/main/browser/extensions/declarative-net-request/regex-char-set.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-char-set.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-char-set.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-char-set.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-filter.test.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-filter.test.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-filter.test.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-filter.test.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-filter.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-filter.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-filter.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-filter.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-piece.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-piece.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-piece.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-piece.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-repetition.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-repetition.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-repetition.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-repetition.ts diff --git a/src/main/browser/extensions/declarative-net-request/regex-translation.ts b/src/main/browser/extensions/declarative-net-request/regex/regex-translation.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/regex-translation.ts rename to src/main/browser/extensions/declarative-net-request/regex/regex-translation.ts diff --git a/src/main/browser/extensions/declarative-net-request/request-context.ts b/src/main/browser/extensions/declarative-net-request/request-context.ts index 9e878bfe10e..5a01843437f 100644 --- a/src/main/browser/extensions/declarative-net-request/request-context.ts +++ b/src/main/browser/extensions/declarative-net-request/request-context.ts @@ -1,9 +1,9 @@ -import { hostLabelSuffixes, sameDomainOrHost } from './domain-matching' -import { dnrNgramDictionary } from './ngram-dictionary' -import { ELEMENT_TYPE, requestMethodBit, resourceTypeBit } from './rule-flags' -import type { DnrResourceType } from './rule-types' -import type { DnrUrlText } from './url-pattern' -import { dnrUrlHost, dnrUrlText, toLowerAscii } from './url-text' +import { hostLabelSuffixes, sameDomainOrHost } from './matching/domain-matching' +import { dnrNgramDictionary } from './indexing/ngram-dictionary' +import { ELEMENT_TYPE, requestMethodBit, resourceTypeBit } from './rule-compilation/rule-flags' +import type { DnrResourceType } from './rule-compilation/rule-types' +import type { DnrUrlText } from './matching/url-pattern' +import { dnrUrlHost, dnrUrlText, toLowerAscii } from './matching/url-text' // Everything a rule looks at for one request, computed once and shared by every ruleset // (request_params.cc RequestParams). diff --git a/src/main/browser/extensions/declarative-net-request/request-state.ts b/src/main/browser/extensions/declarative-net-request/request-state.ts index 2b17dc9e628..f29eb39df77 100644 --- a/src/main/browser/extensions/declarative-net-request/request-state.ts +++ b/src/main/browser/extensions/declarative-net-request/request-state.ts @@ -1,4 +1,4 @@ -import { compareActions, isAllowAction, type DnrRequestAction } from './ruleset-matcher' +import { compareActions, isAllowAction, type DnrRequestAction } from './matching/ruleset-matcher' // What WebRequestInfo carries for one request between onBeforeRequest and onHeadersReceived // (dnr_actions, max_priority_allow_action), and the event router's merge between the stages diff --git a/src/main/browser/extensions/declarative-net-request/indexed-rule.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/indexed-rule.ts similarity index 96% rename from src/main/browser/extensions/declarative-net-request/indexed-rule.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/indexed-rule.ts index 0e8898e6599..b935d4f1872 100644 --- a/src/main/browser/extensions/declarative-net-request/indexed-rule.ts +++ b/src/main/browser/extensions/declarative-net-request/rule-compilation/indexed-rule.ts @@ -3,10 +3,10 @@ import { parseResponseHeaderConditions, type DnrHeaderCondition, type DnrHeaderModification -} from './header-rules' +} from '../header-actions/header-rules' import { dnrRuleProblem, isDnrRuleProblem, type DnrRuleProblem } from './parse-errors' -import { parseDnrRedirect, type DnrRedirectSpec } from './redirect-url' -import { isValidRegexSubstitution, translateDnrRegex } from './regex-filter' +import { parseDnrRedirect, type DnrRedirectSpec } from '../redirect-actions/redirect-url' +import { isValidRegexSubstitution, translateDnrRegex } from '../regex/regex-filter' import { emptyConditionListProblem, parseRuleConditionFields, @@ -14,8 +14,8 @@ import { } from './rule-conditions' import { indexedRulePriority } from './rule-flags' import type { DnrActionType, DnrRule } from './rule-types' -import { DnrUrlPatternMatcher, parseUrlFilter } from './url-pattern' -import { isAsciiText, toLowerAscii } from './url-text' +import { DnrUrlPatternMatcher, parseUrlFilter } from '../matching/url-pattern' +import { isAsciiText, toLowerAscii } from '../matching/url-text' // IndexedRule::CreateIndexedRule (indexed_rule.cc). Checks run in Chromium's order so the // first problem reported is the one Chrome would report. diff --git a/src/main/browser/extensions/declarative-net-request/parse-errors.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/parse-errors.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/parse-errors.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/parse-errors.ts diff --git a/src/main/browser/extensions/declarative-net-request/rule-conditions.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-conditions.ts similarity index 97% rename from src/main/browser/extensions/declarative-net-request/rule-conditions.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-conditions.ts index df1506dc306..fc44fcc1e8e 100644 --- a/src/main/browser/extensions/declarative-net-request/rule-conditions.ts +++ b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-conditions.ts @@ -1,4 +1,4 @@ -import { DnrDomainList } from './domain-matching' +import { DnrDomainList } from '../matching/domain-matching' import { dnrRuleProblem, isDnrRuleProblem, type DnrRuleProblem } from './parse-errors' import { ELEMENT_TYPE, @@ -9,7 +9,7 @@ import { ruleMethodBit } from './rule-flags' import type { DnrRule } from './rule-types' -import { isAsciiText, toLowerAscii } from './url-text' +import { isAsciiText, toLowerAscii } from '../matching/url-text' // Condition parsing steps of IndexedRule::CreateIndexedRule (indexed_rule.cc): // ComputeRequestMethods, ComputeElementTypes, CanonicalizeDomains and tab ids. diff --git a/src/main/browser/extensions/declarative-net-request/rule-flags.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-flags.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/rule-flags.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-flags.ts diff --git a/src/main/browser/extensions/declarative-net-request/rule-schema.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-schema.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/rule-schema.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-schema.ts diff --git a/src/main/browser/extensions/declarative-net-request/rule-types.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/rule-types.ts similarity index 100% rename from src/main/browser/extensions/declarative-net-request/rule-types.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/rule-types.ts diff --git a/src/main/browser/extensions/declarative-net-request/ruleset-builder.ts b/src/main/browser/extensions/declarative-net-request/rule-compilation/ruleset-builder.ts similarity index 98% rename from src/main/browser/extensions/declarative-net-request/ruleset-builder.ts rename to src/main/browser/extensions/declarative-net-request/rule-compilation/ruleset-builder.ts index 33fd81070ea..4705a27f540 100644 --- a/src/main/browser/extensions/declarative-net-request/ruleset-builder.ts +++ b/src/main/browser/extensions/declarative-net-request/rule-compilation/ruleset-builder.ts @@ -2,7 +2,7 @@ import { createIndexedRule } from './indexed-rule' import { dnrRuleProblem, type DnrRuleProblem } from './parse-errors' import { readDnrRuleJson } from './rule-schema' import type { DnrRulesetSource } from './rule-types' -import { DnrRulesetIndex } from './ruleset-index' +import { DnrRulesetIndex } from '../indexing/ruleset-index' // RulesetSource::IndexRules (ruleset_source.cc). Static rulesets skip bad rules with warnings; // updateDynamicRules / updateSessionRules reject the whole update on the first bad rule. diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts index 9581670859c..e4edf987e07 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-extension-rules.ts @@ -1,6 +1,6 @@ import type { DnrEngine } from '../engine' -import { readDnrRuleJson } from '../rule-schema' -import type { DnrRule, DnrRulesetSource } from '../rule-types' +import { readDnrRuleJson } from '../rule-compilation/rule-schema' +import type { DnrRule, DnrRulesetSource } from '../rule-compilation/rule-types' import { DNR_API_CONSTANTS, DNR_ERRORS, diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts index f132f16584b..4a04c618c1a 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from 'vitest' import { DnrEngine } from '../engine' import { createDnrRequestState } from '../request-state' -import { buildDnrRuleset } from '../ruleset-builder' +import { buildDnrRuleset } from '../rule-compilation/ruleset-builder' import { DnrFrameTracker } from './browser-extension-dnr-frames' const EXT = 'f'.repeat(32) diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts index e607c45d0a4..8e203a098e3 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-frames.ts @@ -1,5 +1,5 @@ import type { DnrEngine, DnrFrameCommit } from '../engine' -import type { DnrFrameAllowState } from '../extension-matcher' +import type { DnrFrameAllowState } from '../matching/extension-matcher' import type { DnrResponseHeaders } from '../request-context' /** What a frame's navigation request carried, which its committed document is matched with. */ diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts index f2dce544d0d..f0c34c3e39c 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-limits.ts @@ -1,4 +1,4 @@ -import type { DnrRule } from '../rule-types' +import type { DnrRule } from '../rule-compilation/rule-types' /** chrome.declarativeNetRequest constants (declarative_net_request.webidl, Chromium 150). */ export const DNR_API_CONSTANTS = { diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts index 2df5534cedd..3c6f6baeb01 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -import type { DnrRequestAction } from '../ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' import { DnrMatchedRules } from './browser-extension-dnr-matched-rules' const EXT = 'e'.repeat(32) diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts index 7d1245cf3a0..1a1d93ba192 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-matched-rules.ts @@ -1,4 +1,4 @@ -import type { DnrRequestAction } from '../ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' /** getMatchedRules' MatchedRuleInfo. */ export type DnrMatchedRuleInfo = { diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts index 0fec7e7570e..61945867460 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.test.ts @@ -37,7 +37,7 @@ const { attachBrowserExtensionDnr, getDnrSessionRuntime } = await import('./browser-extension-dnr-session') const { observeBrowserExtensionDnrContents } = await import('./browser-extension-dnr-contents') await import('../../actions/browser-extension-action-registry') -await import('../../browser-extension-web-request') +await import('../../requests/browser-extension-web-request-observer') const BLOCKER = 'c'.repeat(32) const PAGE = 'https://site.example' diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts index 76fd9ef456b..77c4ec418db 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-requests.ts @@ -1,15 +1,18 @@ import type { BrowserSessionRequestDecider } from '../../../sessions/requests/browser-session-request-decisions' import { createDnrRequestState, type DnrRequestState } from '../request-state' import type { DnrEvaluateOptions } from '../engine' -import { applyDnrRequestHeaderActions, applyDnrResponseHeaderActions } from '../header-modification' +import { + applyDnrRequestHeaderActions, + applyDnrResponseHeaderActions +} from '../header-actions/header-modification' import type { DnrRequestInfo, DnrResponseHeaders } from '../request-context' -import type { DnrRequestAction } from '../ruleset-matcher' +import type { DnrRequestAction } from '../matching/ruleset-matcher' import { getDnrSessionRuntime, type DnrSessionRuntime } from './browser-extension-dnr-session' import { extensionHasPermission } from '../../api-runtime/browser-extension-namespace-registry' import { chromeResourceType, isRequestHiddenFromExtensions -} from '../../browser-extension-web-request' +} from '../../requests/browser-extension-request-classification' type RequestDetails = { id: number diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts index 294812e4037..2eb66ca91ec 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-static-rulesets.ts @@ -1,8 +1,11 @@ import { readFile } from 'node:fs/promises' import { isAbsolute, relative, resolve } from 'node:path' -import { buildDnrRulesetInSlices, type DnrInvalidRulePolicy } from '../ruleset-builder' -import type { DnrRulesetIndex } from '../ruleset-index' -import type { DnrRulesetSource } from '../rule-types' +import { + buildDnrRulesetInSlices, + type DnrInvalidRulePolicy +} from '../rule-compilation/ruleset-builder' +import type { DnrRulesetIndex } from '../indexing/ruleset-index' +import type { DnrRulesetSource } from '../rule-compilation/rule-types' /** One manifest declarative_net_request.rule_resources entry. */ export type DnrManifestRuleset = { diff --git a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts index df9c0fea925..a3560b0bf83 100644 --- a/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts +++ b/src/main/browser/extensions/declarative-net-request/session/browser-extension-dnr-store.ts @@ -1,6 +1,6 @@ import { app } from 'electron' import { z } from 'zod' -import { BrowserExtensionSyncStorageStore } from '../../profile-storage/browser-extension-sync-storage-store' +import { BrowserExtensionProfileDocumentStore } from '../../profile-storage/browser-extension-profile-document-store' import { getBrowserExtensionProfileDataDirectory } from '../../profile-storage/browser-extension-profile-data-directory' /** @@ -19,11 +19,11 @@ const dnrStateSchema = z.object({ export type BrowserExtensionDnrState = z.infer -let store: BrowserExtensionSyncStorageStore | null = null +let store: BrowserExtensionProfileDocumentStore | null = null -export function getBrowserExtensionDnrStore(): BrowserExtensionSyncStorageStore { +export function getBrowserExtensionDnrStore(): BrowserExtensionProfileDocumentStore { if (!store) { - const created = new BrowserExtensionSyncStorageStore( + const created = new BrowserExtensionProfileDocumentStore( getBrowserExtensionProfileDataDirectory(), 'declarative-net-request' ) diff --git a/src/main/browser/extensions/installation/browser-extension-mutation-lock.ts b/src/main/browser/extensions/installation/browser-extension-mutation-lock.ts new file mode 100644 index 00000000000..41d9d6215a9 --- /dev/null +++ b/src/main/browser/extensions/installation/browser-extension-mutation-lock.ts @@ -0,0 +1,27 @@ +const busyExtensionIds = new Set() + +export class BrowserExtensionBusyError extends Error { + constructor() { + super('This extension is already being installed or removed') + } +} + +/** Serializes install, update and uninstall of one extension id. */ +export async function withBrowserExtensionLock( + extensionId: string, + action: () => Promise +): Promise { + if (busyExtensionIds.has(extensionId)) { + throw new BrowserExtensionBusyError() + } + busyExtensionIds.add(extensionId) + try { + return await action() + } finally { + busyExtensionIds.delete(extensionId) + } +} + +export function isBrowserExtensionBusy(extensionId: string): boolean { + return busyExtensionIds.has(extensionId) +} diff --git a/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts b/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts index 72a6e9aa4fa..138304fa1c3 100644 --- a/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts +++ b/src/main/browser/extensions/installation/browser-extension-webstore-install.test.ts @@ -8,6 +8,7 @@ import { extensionIdFromPublicKey, type VerifiedCrx } from './browser-extension- import { generateCrxTestKey, type CrxTestKey } from './browser-extension-crx-fixture' import type * as InstallStoreModule from './browser-extension-install-store' import type * as InstallModule from './browser-extension-webstore-install' +import type * as MutationLockModule from './browser-extension-mutation-lock' const state = vi.hoisted(() => { const enabled: Record = {} @@ -21,7 +22,9 @@ const state = vi.hoisted(() => { }) vi.mock('electron', () => ({ app: { getPath: () => state.userData, on: vi.fn() } })) -vi.mock('../api/runtime', () => ({ openBrowserExtensionOptionsPage: vi.fn() })) +vi.mock('../tabs-and-windows/browser-extension-options-page', () => ({ + openBrowserExtensionOptionsPage: vi.fn() +})) vi.mock('../web-store/browser-extension-webstore-updater', () => ({ reviewHeldBrowserExtensionUpdate: vi.fn() })) @@ -50,6 +53,7 @@ vi.mock('../profile-sessions/browser-extension-session-loader', () => ({ let key: CrxTestKey let extensionId: string let install: typeof InstallModule +let mutationLock: typeof MutationLockModule let installStore: typeof InstallStoreModule beforeAll(() => { @@ -64,6 +68,7 @@ beforeEach(async () => { state.load.mockImplementation(async () => ({})) vi.resetModules() install = await import('./browser-extension-webstore-install') + mutationLock = await import('./browser-extension-mutation-lock') installStore = await import('./browser-extension-install-store') }) afterEach(() => { @@ -111,7 +116,7 @@ describe('store installs', () => { await vi.waitFor(() => expect(state.load).toHaveBeenCalledWith('work', first)) try { await expect( - install.withBrowserExtensionLock(extensionId, () => + mutationLock.withBrowserExtensionLock(extensionId, () => install.commitStagedWebStoreExtension(staged, null) ) ).rejects.toThrow('already being installed') diff --git a/src/main/browser/extensions/installation/browser-extension-webstore-install.ts b/src/main/browser/extensions/installation/browser-extension-webstore-install.ts index 2ed352f13db..095890c8e28 100644 --- a/src/main/browser/extensions/installation/browser-extension-webstore-install.ts +++ b/src/main/browser/extensions/installation/browser-extension-webstore-install.ts @@ -36,33 +36,6 @@ import { const VERSION_PATTERN = /^\d+(\.\d+){0,3}$/ const STAGING_PREFIX = '.staging-' -const busyExtensionIds = new Set() - -export class BrowserExtensionBusyError extends Error { - constructor() { - super('This extension is already being installed or removed') - } -} - -/** Serializes install, update and uninstall of one extension id. */ -export async function withBrowserExtensionLock( - extensionId: string, - action: () => Promise -): Promise { - if (busyExtensionIds.has(extensionId)) { - throw new BrowserExtensionBusyError() - } - busyExtensionIds.add(extensionId) - try { - return await action() - } finally { - busyExtensionIds.delete(extensionId) - } -} - -export function isBrowserExtensionBusy(extensionId: string): boolean { - return busyExtensionIds.has(extensionId) -} export type StagedWebStoreExtension = { extensionId: string diff --git a/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts b/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts index be7c935dcad..ab5cf2b08c4 100644 --- a/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts +++ b/src/main/browser/extensions/permissions/browser-extension-request-host-access.ts @@ -1,4 +1,4 @@ -import type { DnrHostAccess } from '../declarative-net-request/extension-matcher' +import type { DnrHostAccess } from '../declarative-net-request/matching/extension-matcher' import { browserExtensionActiveTabCovers } from './browser-extension-active-tab' import { matchesExtensionMatchPattern } from './browser-extension-match-pattern' import { manifestPermissionSets } from './browser-extension-permission-grants' diff --git a/src/main/browser/extensions/permissions/browser-extension-session-permissions.ts b/src/main/browser/extensions/permissions/browser-extension-session-permissions.ts new file mode 100644 index 00000000000..750309bcd88 --- /dev/null +++ b/src/main/browser/extensions/permissions/browser-extension-session-permissions.ts @@ -0,0 +1,19 @@ +import { getBrowserExtensionProfileIdForSession } from '../api-runtime/browser-extension-api-host' +import { browserExtensionHostPatterns } from './browser-extension-permission-grants' +import { getBrowserExtensionProfileStateStore } from '../profile-storage/browser-extension-profile-state-store' + +export function readBrowserExtensionProfileGrants(profileId: string, extensionId: string) { + return getBrowserExtensionProfileStateStore().read(profileId, extensionId) +} + +/** Manifest host patterns plus origins the user granted in this session's profile. */ +export function browserExtensionHostPatternsInSession( + extension: Electron.Extension, + session: Electron.Session +): string[] { + const profileId = getBrowserExtensionProfileIdForSession(session) + const grants = profileId + ? readBrowserExtensionProfileGrants(profileId, extension.id) + : { grantedPermissions: [], grantedOrigins: [] } + return browserExtensionHostPatterns(extension.manifest, grants) +} diff --git a/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts b/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts index f074bd911d4..4ac6e47d000 100644 --- a/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts +++ b/src/main/browser/extensions/permissions/browser-extension-settings-prompt-lifetime.test.ts @@ -10,7 +10,7 @@ import { } from '../../../../shared/browser/extensions/browser-extension-webstore' import type * as PromptModule from './browser-extension-install-prompt' import type * as ServiceModule from '../web-store/browser-extension-webstore-service' -import type * as InstallModule from '../installation/browser-extension-webstore-install' +import type * as MutationLockModule from '../installation/browser-extension-mutation-lock' const state = vi.hoisted(() => ({ userData: '', @@ -65,7 +65,7 @@ const renderers: EventEmitter[] = [] const installs: Promise[] = [] let service: typeof ServiceModule let prompt: typeof PromptModule -let install: typeof InstallModule +let mutationLock: typeof MutationLockModule function renderer() { const contents = Object.assign(new EventEmitter(), { @@ -138,7 +138,7 @@ beforeEach(async () => { vi.resetModules() service = await import('../web-store/browser-extension-webstore-service') prompt = await import('./browser-extension-install-prompt') - install = await import('../installation/browser-extension-webstore-install') + mutationLock = await import('../installation/browser-extension-mutation-lock') }) afterEach(async () => { @@ -155,14 +155,14 @@ describe('Settings extension install prompt lifetime', () => { const pending = start(contents) const request = await requested(contents) expect(stagedFolders()).toHaveLength(1) - expect(install.isBrowserExtensionBusy(extensionId)).toBe(true) + expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(true) contents.emit('did-navigate', {}, 'file:///orca/index.html', 200, 'OK') - await vi.waitFor(() => expect(install.isBrowserExtensionBusy(extensionId)).toBe(false)) + await vi.waitFor(() => expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(false)) await expect(pending).resolves.toEqual({ status: 'cancelled' }) expect(stagedFolders()).toEqual([]) - expect(install.isBrowserExtensionBusy(extensionId)).toBe(false) + expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(false) expect( prompt.respondToBrowserExtensionInstallPrompt(asContents(contents), { requestId: request.requestId, @@ -181,6 +181,6 @@ describe('Settings extension install prompt lifetime', () => { accepted: true }) await expect(retry).resolves.toEqual({ status: 'installed', name: 'Vault' }) - expect(install.isBrowserExtensionBusy(extensionId)).toBe(false) + expect(mutationLock.isBrowserExtensionBusy(extensionId)).toBe(false) }) }) diff --git a/src/main/browser/extensions/permissions/browser-extension-user-gesture.ts b/src/main/browser/extensions/permissions/browser-extension-user-gesture.ts new file mode 100644 index 00000000000..e0abfe450e3 --- /dev/null +++ b/src/main/browser/extensions/permissions/browser-extension-user-gesture.ts @@ -0,0 +1,36 @@ +import type { BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' +import { getHostSessionState } from '../api-runtime/browser-extension-contexts' +import { getBrowserExtensionContextSignal } from '../api-runtime/browser-extension-context-lifetime' + +const USER_GESTURE_WINDOW_MS = 5_000 + +const recentGestures = new WeakMap() + +/** + * Chrome lets permissions.request run only inside a user gesture. Orca records the gestures it + * delivers to an extension (menu click, command, notification click, toolbar click). + */ +export function noteBrowserExtensionUserGesture( + session: Electron.Session, + extensionId: string +): void { + const state = getHostSessionState(session) + if (!state) { + return + } + const signal = getBrowserExtensionContextSignal(state, extensionId) + recentGestures.set(signal, Date.now()) +} + +export function hasBrowserExtensionUserGesture(caller: BrowserExtensionCaller): boolean { + if (caller.userGesture === true) { + return true + } + const state = getHostSessionState(caller.session) + if (!state) { + return false + } + const signal = getBrowserExtensionContextSignal(state, caller.extension.id) + const at = recentGestures.get(signal) + return at !== undefined && !signal.aborted && Date.now() - at <= USER_GESTURE_WINDOW_MS +} diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts index 62e6027932e..542207de588 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.test.ts @@ -59,7 +59,7 @@ vi.mock('./browser-extension-session-loader', () => ({ attachHook = hooks } })) -vi.mock('../browser-extension-web-request', () => ({ +vi.mock('../requests/browser-extension-web-request-observer', () => ({ installBrowserExtensionWebRequestForwarding: vi.fn(), observeBrowserExtensionWebRequests: vi.fn(), stopObservingBrowserExtensionWebRequests: vi.fn() diff --git a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts index 6addfc642d1..c7ecd3215b2 100644 --- a/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts +++ b/src/main/browser/extensions/profile-sessions/browser-extension-session-services.ts @@ -22,7 +22,7 @@ import { installBrowserExtensionWebRequestForwarding, observeBrowserExtensionWebRequests, stopObservingBrowserExtensionWebRequests -} from '../browser-extension-web-request' +} from '../requests/browser-extension-web-request-observer' // Why once: a session outlives the experimental setting being switched off and on again. const servedSessions = new WeakSet() diff --git a/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts b/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts index 235dbeef7b7..c88feafc4f5 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-data-removal.test.ts @@ -51,7 +51,9 @@ const { } = await import('./browser-extension-data-removal') const { getBrowserExtensionProfileStateStore } = await import('./browser-extension-profile-state-store') -const { BrowserExtensionSyncStorageStore, getBrowserExtensionSyncStorageStore } = +const { BrowserExtensionProfileDocumentStore } = + await import('./browser-extension-profile-document-store') +const { getBrowserExtensionSyncStorageStore } = await import('./browser-extension-sync-storage-store') const { getBrowserExtensionInstallStore } = await import('../installation/browser-extension-install-store') @@ -112,7 +114,7 @@ describe('removeUninstalledBrowserExtensionData', () => { expect(Object.keys(states.readProfile('work'))).toEqual([OTHER]) expect(states.read('home', ID).grantedPermissions).toEqual(['tabs']) expect( - new BrowserExtensionSyncStorageStore(getBrowserExtensionProfileDataDirectory()).read( + new BrowserExtensionProfileDocumentStore(getBrowserExtensionProfileDataDirectory()).read( 'work', ID ) diff --git a/src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts b/src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts new file mode 100644 index 00000000000..9a1f6a8b0bb --- /dev/null +++ b/src/main/browser/extensions/profile-storage/browser-extension-profile-document-store.ts @@ -0,0 +1,158 @@ +import { mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { join } from 'node:path' +import { isChromeExtensionId } from '../../../../shared/browser/extensions/browser-extension-url' +import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' + +const SYNC_STORAGE_DIRECTORY = 'sync-storage' + +const PERSIST_DELAY_MS = 250 + +export type BrowserExtensionProfileDocumentItems = Record + +function isItems(value: unknown): value is BrowserExtensionProfileDocumentItems { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +export class BrowserExtensionProfileDocumentStore { + /** Profile → extension → items. */ + private readonly cache = new Map>() + /** Profile → extensions whose items are not on disk yet. */ + private readonly dirty = new Map>() + private timer: NodeJS.Timeout | null = null + + constructor( + private readonly rootDirectory: string, + /** declarativeNetRequest state reuses this store under its own directory. */ + private readonly directoryName = SYNC_STORAGE_DIRECTORY + ) {} + + read(profileId: string, extensionId: string): BrowserExtensionProfileDocumentItems { + let byExtension = this.cache.get(profileId) + if (!byExtension) { + byExtension = new Map() + this.cache.set(profileId, byExtension) + } + let items = byExtension.get(extensionId) + if (!items) { + items = this.load(profileId, extensionId) + byExtension.set(extensionId, items) + } + return items + } + + write(profileId: string, extensionId: string, items: BrowserExtensionProfileDocumentItems): void { + this.read(profileId, extensionId) + this.cache.get(profileId)?.set(extensionId, items) + const dirty = this.dirty.get(profileId) ?? new Set() + dirty.add(extensionId) + this.dirty.set(profileId, dirty) + this.schedulePersist() + } + + forgetExtension(extensionId: string): void { + for (const byExtension of this.cache.values()) { + byExtension.delete(extensionId) + } + for (const dirty of this.dirty.values()) { + dirty.delete(extensionId) + } + let profileDirectories: string[] + try { + profileDirectories = readdirSync(join(this.rootDirectory, this.directoryName)) + } catch { + return + } + for (const directory of profileDirectories) { + rmSync(join(this.rootDirectory, this.directoryName, directory, this.fileName(extensionId)), { + force: true + }) + } + } + + forgetProfileExtension(profileId: string, extensionId: string): void { + this.cache.get(profileId)?.delete(extensionId) + this.dirty.get(profileId)?.delete(extensionId) + rmSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), { force: true }) + } + + /** Drops one profile's items of every extension not in `extensionIds`. */ + forgetExtensionsExcept(profileId: string, extensionIds: ReadonlySet): void { + const cached = this.cache.get(profileId) + for (const extensionId of cached?.keys() ?? []) { + if (!extensionIds.has(extensionId)) { + cached?.delete(extensionId) + this.dirty.get(profileId)?.delete(extensionId) + } + } + let files: string[] + try { + files = readdirSync(this.profileDirectory(profileId)) + } catch { + return + } + for (const file of files) { + const extensionId = file.replace(/\.json$/, '') + if (isChromeExtensionId(extensionId) && !extensionIds.has(extensionId)) { + rmSync(join(this.profileDirectory(profileId), file), { force: true }) + } + } + } + + forgetProfile(profileId: string): void { + this.cache.delete(profileId) + this.dirty.delete(profileId) + rmSync(this.profileDirectory(profileId), { recursive: true, force: true }) + } + + flush(): void { + if (this.timer) { + clearTimeout(this.timer) + this.timer = null + } + for (const [profileId, extensionIds] of this.dirty) { + const directory = this.profileDirectory(profileId) + mkdirSync(directory, { recursive: true }) + for (const extensionId of extensionIds) { + const target = join(directory, this.fileName(extensionId)) + const items = this.cache.get(profileId)?.get(extensionId) ?? {} + writeFileDurableSync(durableWriteTempPath(target), target, JSON.stringify(items)) + extensionIds.delete(extensionId) + } + this.dirty.delete(profileId) + } + } + + // Why debounce: extensions often write settings key by key in a burst. + private schedulePersist(): void { + if (this.timer) { + return + } + this.timer = setTimeout(() => { + this.timer = null + try { + this.flush() + } catch (error) { + console.warn('[browser-extensions] Could not save extension sync storage:', error) + } + }, PERSIST_DELAY_MS) + } + + private load(profileId: string, extensionId: string): BrowserExtensionProfileDocumentItems { + try { + const raw: unknown = JSON.parse( + readFileSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), 'utf8') + ) + return isItems(raw) ? raw : {} + } catch { + return {} + } + } + + private profileDirectory(profileId: string): string { + return join(this.rootDirectory, this.directoryName, encodeURIComponent(profileId)) + } + + private fileName(extensionId: string): string { + return `${encodeURIComponent(extensionId)}.json` + } +} diff --git a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts index 4b87e80c204..fd00df7b1f4 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.test.ts @@ -5,7 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { getPath: () => tmpdir(), on: vi.fn() } })) -const { BrowserExtensionSyncStorageStore } = await import('./browser-extension-sync-storage-store') +const { BrowserExtensionProfileDocumentStore } = + await import('./browser-extension-profile-document-store') const EXTENSION = 'a'.repeat(32) const OTHER = 'b'.repeat(32) @@ -18,34 +19,34 @@ afterEach(() => { rmSync(root, { recursive: true, force: true }) }) -describe('BrowserExtensionSyncStorageStore', () => { +describe('BrowserExtensionProfileDocumentStore', () => { it('keeps each profile and extension apart and survives a restart', () => { - const store = new BrowserExtensionSyncStorageStore(root) + const store = new BrowserExtensionProfileDocumentStore(root) store.write('default', EXTENSION, { theme: { dark: true }, list: [1, 'two'] }) store.write('work', EXTENSION, { theme: 'light' }) store.flush() - const reopened = new BrowserExtensionSyncStorageStore(root) + const reopened = new BrowserExtensionProfileDocumentStore(root) expect(reopened.read('default', EXTENSION)).toEqual({ theme: { dark: true }, list: [1, 'two'] }) expect(reopened.read('work', EXTENSION)).toEqual({ theme: 'light' }) expect(reopened.read('default', OTHER)).toEqual({}) }) it('retries acknowledged writes after a failed flush', () => { - const store = new BrowserExtensionSyncStorageStore(root) + const store = new BrowserExtensionProfileDocumentStore(root) store.write('default', EXTENSION, { token: 'saved after recovery' }) writeFileSync(join(root, 'sync-storage'), 'blocks the storage directory') expect(() => store.flush()).toThrow() rmSync(join(root, 'sync-storage')) store.flush() - expect(new BrowserExtensionSyncStorageStore(root).read('default', EXTENSION)).toEqual({ + expect(new BrowserExtensionProfileDocumentStore(root).read('default', EXTENSION)).toEqual({ token: 'saved after recovery' }) }) it('forgets a removed extension in every profile and a deleted profile entirely', () => { - const store = new BrowserExtensionSyncStorageStore(root) + const store = new BrowserExtensionProfileDocumentStore(root) for (const profile of ['default', 'work']) { store.write(profile, EXTENSION, { kept: profile }) store.write(profile, OTHER, { kept: profile }) @@ -58,7 +59,7 @@ describe('BrowserExtensionSyncStorageStore', () => { store.flush() expect(store.read('default', EXTENSION)).toEqual({}) - const reopened = new BrowserExtensionSyncStorageStore(root) + const reopened = new BrowserExtensionProfileDocumentStore(root) expect(reopened.read('default', EXTENSION)).toEqual({}) expect(reopened.read('default', OTHER)).toEqual({ kept: 'default' }) expect(reopened.read('work', OTHER)).toEqual({}) diff --git a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts index 441a023ffd1..569bdd6b60c 100644 --- a/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts +++ b/src/main/browser/extensions/profile-storage/browser-extension-sync-storage-store.ts @@ -1,173 +1,19 @@ +import { BrowserExtensionProfileDocumentStore } from './browser-extension-profile-document-store' import { app } from 'electron' -import { mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs' -import { join } from 'node:path' -import { isChromeExtensionId } from '../../../../shared/browser/extensions/browser-extension-url' -import { durableWriteTempPath, writeFileDurableSync } from '../../../filesystem/durable-file-write' import { getBrowserExtensionProfileDataDirectory } from './browser-extension-profile-data-directory' -const SYNC_STORAGE_DIRECTORY = 'sync-storage' -const PERSIST_DELAY_MS = 250 - -export type BrowserExtensionSyncItems = Record - -function isItems(value: unknown): value is BrowserExtensionSyncItems { - return value !== null && typeof value === 'object' && !Array.isArray(value) -} +let syncStorageStore: BrowserExtensionProfileDocumentStore | null = null /** * chrome.storage.sync items per browser profile and extension, kept on this machine the way * Chrome keeps them for a user who is not signed in. One file per extension, so a write rewrites * only that extension's items (up to 100 KB). */ -export class BrowserExtensionSyncStorageStore { - /** Profile → extension → items. */ - private readonly cache = new Map>() - /** Profile → extensions whose items are not on disk yet. */ - private readonly dirty = new Map>() - private timer: NodeJS.Timeout | null = null - - constructor( - private readonly rootDirectory: string, - /** declarativeNetRequest state reuses this store under its own directory. */ - private readonly directoryName = SYNC_STORAGE_DIRECTORY - ) {} - - read(profileId: string, extensionId: string): BrowserExtensionSyncItems { - let byExtension = this.cache.get(profileId) - if (!byExtension) { - byExtension = new Map() - this.cache.set(profileId, byExtension) - } - let items = byExtension.get(extensionId) - if (!items) { - items = this.load(profileId, extensionId) - byExtension.set(extensionId, items) - } - return items - } - - write(profileId: string, extensionId: string, items: BrowserExtensionSyncItems): void { - this.read(profileId, extensionId) - this.cache.get(profileId)?.set(extensionId, items) - const dirty = this.dirty.get(profileId) ?? new Set() - dirty.add(extensionId) - this.dirty.set(profileId, dirty) - this.schedulePersist() - } - - forgetExtension(extensionId: string): void { - for (const byExtension of this.cache.values()) { - byExtension.delete(extensionId) - } - for (const dirty of this.dirty.values()) { - dirty.delete(extensionId) - } - let profileDirectories: string[] - try { - profileDirectories = readdirSync(join(this.rootDirectory, this.directoryName)) - } catch { - return - } - for (const directory of profileDirectories) { - rmSync(join(this.rootDirectory, this.directoryName, directory, this.fileName(extensionId)), { - force: true - }) - } - } - - forgetProfileExtension(profileId: string, extensionId: string): void { - this.cache.get(profileId)?.delete(extensionId) - this.dirty.get(profileId)?.delete(extensionId) - rmSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), { force: true }) - } - - /** Drops one profile's items of every extension not in `extensionIds`. */ - forgetExtensionsExcept(profileId: string, extensionIds: ReadonlySet): void { - const cached = this.cache.get(profileId) - for (const extensionId of cached?.keys() ?? []) { - if (!extensionIds.has(extensionId)) { - cached?.delete(extensionId) - this.dirty.get(profileId)?.delete(extensionId) - } - } - let files: string[] - try { - files = readdirSync(this.profileDirectory(profileId)) - } catch { - return - } - for (const file of files) { - const extensionId = file.replace(/\.json$/, '') - if (isChromeExtensionId(extensionId) && !extensionIds.has(extensionId)) { - rmSync(join(this.profileDirectory(profileId), file), { force: true }) - } - } - } - - forgetProfile(profileId: string): void { - this.cache.delete(profileId) - this.dirty.delete(profileId) - rmSync(this.profileDirectory(profileId), { recursive: true, force: true }) - } - - flush(): void { - if (this.timer) { - clearTimeout(this.timer) - this.timer = null - } - for (const [profileId, extensionIds] of this.dirty) { - const directory = this.profileDirectory(profileId) - mkdirSync(directory, { recursive: true }) - for (const extensionId of extensionIds) { - const target = join(directory, this.fileName(extensionId)) - const items = this.cache.get(profileId)?.get(extensionId) ?? {} - writeFileDurableSync(durableWriteTempPath(target), target, JSON.stringify(items)) - extensionIds.delete(extensionId) - } - this.dirty.delete(profileId) - } - } - - // Why debounce: extensions often write settings key by key in a burst. - private schedulePersist(): void { - if (this.timer) { - return - } - this.timer = setTimeout(() => { - this.timer = null - try { - this.flush() - } catch (error) { - console.warn('[browser-extensions] Could not save extension sync storage:', error) - } - }, PERSIST_DELAY_MS) - } - - private load(profileId: string, extensionId: string): BrowserExtensionSyncItems { - try { - const raw: unknown = JSON.parse( - readFileSync(join(this.profileDirectory(profileId), this.fileName(extensionId)), 'utf8') - ) - return isItems(raw) ? raw : {} - } catch { - return {} - } - } - - private profileDirectory(profileId: string): string { - return join(this.rootDirectory, this.directoryName, encodeURIComponent(profileId)) - } - - private fileName(extensionId: string): string { - return `${encodeURIComponent(extensionId)}.json` - } -} - -let syncStorageStore: BrowserExtensionSyncStorageStore | null = null - -export function getBrowserExtensionSyncStorageStore(): BrowserExtensionSyncStorageStore { +export function getBrowserExtensionSyncStorageStore(): BrowserExtensionProfileDocumentStore { if (!syncStorageStore) { - const store = new BrowserExtensionSyncStorageStore(getBrowserExtensionProfileDataDirectory()) + const store = new BrowserExtensionProfileDocumentStore( + getBrowserExtensionProfileDataDirectory() + ) app.on('will-quit', () => store.flush()) syncStorageStore = store } diff --git a/src/main/browser/extensions/requests/browser-extension-request-classification.ts b/src/main/browser/extensions/requests/browser-extension-request-classification.ts new file mode 100644 index 00000000000..1d974b43e40 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-request-classification.ts @@ -0,0 +1,57 @@ +import { CHROME_WEB_STORE_ORIGIN } from '../../../../shared/browser/extensions/browser-extension-webstore' + +type ChromeResourceType = + | 'main_frame' + | 'sub_frame' + | 'stylesheet' + | 'script' + | 'image' + | 'font' + | 'object' + | 'xmlhttprequest' + | 'ping' + | 'csp_report' + | 'media' + | 'websocket' + | 'other' + +const CHROME_RESOURCE_TYPES = new Map([ + ['mainFrame', 'main_frame'], + ['subFrame', 'sub_frame'], + ['stylesheet', 'stylesheet'], + ['script', 'script'], + ['image', 'image'], + ['font', 'font'], + ['object', 'object'], + ['xhr', 'xmlhttprequest'], + ['ping', 'ping'], + ['cspReport', 'csp_report'], + ['media', 'media'], + ['webSocket', 'websocket'] +]) + +/** Electron's resourceType → Chrome's, shared by webRequest and declarativeNetRequest. */ +export function chromeResourceType(resourceType: string): ChromeResourceType { + return CHROME_RESOURCE_TYPES.get(resourceType) ?? 'other' +} + +const WEB_URL = /^(?:https?|wss?):/i + +/** WebRequestPermissions::HideRequest: requests extensions never see or act on. */ +export function isRequestHiddenFromExtensions(details: { + url: string + webContentsId?: number + initiatorOrigin?: string +}): boolean { + if (!WEB_URL.test(details.url)) { + return true + } + // Orca's own main-process requests carry neither a webContents nor an initiator. + if (details.webContentsId === undefined && details.initiatorOrigin === undefined) { + return true + } + return ( + details.url.startsWith(`${CHROME_WEB_STORE_ORIGIN}/`) || + details.url.startsWith('https://chrome.google.com/webstore') + ) +} diff --git a/src/main/browser/extensions/requests/browser-extension-web-request-details.ts b/src/main/browser/extensions/requests/browser-extension-web-request-details.ts new file mode 100644 index 00000000000..90964d4ab29 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-web-request-details.ts @@ -0,0 +1,101 @@ +import { chromeResourceType } from './browser-extension-request-classification' +import type { ObservedWebRequestDetails } from '../../sessions/requests/browser-session-web-request-observer' +import { chromeFrameDocument } from '../tabs-and-windows/browser-extension-frame-projection' + +// Chrome hides these unless a listener asks for 'extraHeaders'. +const HIDDEN_REQUEST_HEADERS = new Set(['accept-language', 'accept-encoding', 'referer', 'cookie']) + +const HIDDEN_RESPONSE_HEADERS = new Set(['set-cookie']) + +export type ChromeWebRequestDetails = { + requestId: string + url: string + method: string + frameId: number + parentFrameId: number + tabId: number + windowId: number + type: string + timeStamp: number + frameType?: 'outermost_frame' | 'sub_frame' + documentId?: string + parentDocumentId?: string + documentLifecycle?: 'active' + requestHeaders?: { name: string; value: string }[] + responseHeaders?: { name: string; value: string }[] + statusCode?: number + statusLine?: string + fromCache?: boolean + ip?: string + redirectUrl?: string + error?: string +} + +function requestHeaderList(headers: Record): { name: string; value: string }[] { + return Object.entries(headers) + .filter(([name]) => !HIDDEN_REQUEST_HEADERS.has(name.toLowerCase())) + .map(([name, value]) => ({ name, value })) +} + +function responseHeaderList(headers: Record): { name: string; value: string }[] { + return Object.entries(headers) + .filter(([name]) => !HIDDEN_RESPONSE_HEADERS.has(name.toLowerCase())) + .flatMap(([name, values]) => values.map((value) => ({ name, value }))) +} + +type WebRequestFrameFields = Pick< + ChromeWebRequestDetails, + | 'frameId' + | 'parentFrameId' + | 'frameType' + | 'documentId' + | 'parentDocumentId' + | 'documentLifecycle' +> + +/** A navigation request has no document yet; any other request belongs to its frame's current one. */ +export function browserExtensionRequestFrameFields( + details: ObservedWebRequestDetails +): WebRequestFrameFields { + if (details.resourceType === 'mainFrame') { + return { + frameId: 0, + parentFrameId: -1, + frameType: 'outermost_frame', + documentLifecycle: 'active' + } + } + const frame = details.frame && !details.frame.isDestroyed() ? details.frame : null + return frame + ? chromeFrameDocument(frame, details.resourceType !== 'subFrame') + : { frameId: 0, parentFrameId: -1 } +} + +export function toChromeWebRequestDetails( + details: ObservedWebRequestDetails, + tab: { tabId: number; windowId: number }, + frame: WebRequestFrameFields +): ChromeWebRequestDetails { + const type = chromeResourceType(details.resourceType) + return { + requestId: String(details.id), + url: details.url, + method: details.method, + ...frame, + ...tab, + type, + timeStamp: details.timestamp, + ...(details.requestHeaders + ? { requestHeaders: requestHeaderList(details.requestHeaders) } + : {}), + ...(details.responseHeaders + ? { responseHeaders: responseHeaderList(details.responseHeaders) } + : {}), + ...(details.statusCode !== undefined ? { statusCode: details.statusCode } : {}), + ...(details.statusLine !== undefined ? { statusLine: details.statusLine } : {}), + ...(details.fromCache !== undefined ? { fromCache: details.fromCache } : {}), + ...(details.ip ? { ip: details.ip } : {}), + ...(details.redirectURL ? { redirectUrl: details.redirectURL } : {}), + ...(details.error ? { error: details.error } : {}) + } +} diff --git a/src/main/browser/extensions/requests/browser-extension-web-request-filter.ts b/src/main/browser/extensions/requests/browser-extension-web-request-filter.ts new file mode 100644 index 00000000000..fdce0232e65 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-web-request-filter.ts @@ -0,0 +1,32 @@ +import type { ChromeWebRequestDetails } from './browser-extension-web-request-details' +import { matchesExtensionMatchPattern } from '../permissions/browser-extension-match-pattern' + +/** Main-side pre-filter against one listener's chrome.webRequest.RequestFilter. */ +export function webRequestFilterMatches( + filter: unknown, + details: ChromeWebRequestDetails +): boolean { + if (filter === null || typeof filter !== 'object') { + return true + } + const fields = new Map(Object.entries(filter)) + const urls = fields.get('urls') + if ( + Array.isArray(urls) && + !urls.some( + (pattern) => typeof pattern === 'string' && matchesExtensionMatchPattern(pattern, details.url) + ) + ) { + return false + } + const types = fields.get('types') + if (Array.isArray(types) && !types.includes(details.type)) { + return false + } + const tabId = fields.get('tabId') + const windowId = fields.get('windowId') + return ( + (typeof tabId !== 'number' || tabId === details.tabId) && + (typeof windowId !== 'number' || windowId === details.windowId) + ) +} diff --git a/src/main/browser/extensions/requests/browser-extension-web-request-observer.ts b/src/main/browser/extensions/requests/browser-extension-web-request-observer.ts new file mode 100644 index 00000000000..bd47fdd2ae8 --- /dev/null +++ b/src/main/browser/extensions/requests/browser-extension-web-request-observer.ts @@ -0,0 +1,127 @@ +import { webRequestFilterMatches } from './browser-extension-web-request-filter' +import { + browserExtensionRequestFrameFields, + toChromeWebRequestDetails +} from './browser-extension-web-request-details' +import { isRequestHiddenFromExtensions } from './browser-extension-request-classification' +import { + installBrowserSessionHeadersReceived, + installBrowserSessionRequestLifecycle, + removeBrowserSessionHeadersReceived, + removeBrowserSessionRequestLifecycle +} from '../../sessions/requests/browser-session-request-decisions' +import { + setBrowserSessionWebRequestObserver, + type ObservedWebRequestDetails, + type ObservedWebRequestEvent +} from '../../sessions/requests/browser-session-web-request-observer' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' +import { + emitBrowserExtensionEvent, + getBrowserExtensionProfileIdForSession +} from '../api-runtime/browser-extension-api-host' +import { browserExtensionEventHasListener } from '../api-runtime/browser-extension-contexts' +import { extensionHasPermission } from '../api-runtime/browser-extension-namespace-registry' +import { hasBrowserExtensionHostPermission } from '../permissions/browser-extension-permission-grants' +import { canExtensionAccessRequest } from '../permissions/browser-extension-request-host-access' +import { resolveBrowserExtensionTab } from '../tabs-and-windows/browser-extension-tab-model' + +/** + * chrome.webRequest, observed rather than blocking. Electron 43 delivers no webRequest events to + * MV3 workers, and Orca's own session handlers switch Electron's extension webRequest off anyway, + * so Orca forwards what its handlers see. MV3 store extensions cannot block requests in Chrome + * either (webRequestBlocking is policy-only), so nothing they could do is lost. + */ + +function forward( + session: Electron.Session, + event: ObservedWebRequestEvent, + details: ObservedWebRequestDetails +): void { + if ( + isRequestHiddenFromExtensions(details) || + !getBrowserExtensionProfileIdForSession(session) || + !browserExtensionEventHasListener(session, 'webRequest', event) + ) { + return + } + const entry = + details.webContentsId === undefined ? null : resolveBrowserExtensionTab(details.webContentsId) + const chromeDetails = toChromeWebRequestDetails( + details, + entry ? { tabId: entry.contents.id, windowId: entry.windowId } : { tabId: -1, windowId: -1 }, + browserExtensionRequestFrameFields(details) + ) + const request = { + url: details.url, + initiator: details.initiatorOrigin ?? null, + tabId: chromeDetails.tabId, + type: chromeDetails.type + } + emitBrowserExtensionEvent( + { session }, + 'webRequest', + event, + (extension) => { + const patterns = browserExtensionHostPatternsInSession(extension, session) + return canExtensionAccessRequest(extension.id, request, (url) => + hasBrowserExtensionHostPermission(patterns, url) + ) + ? [chromeDetails] + : null + }, + (filter) => webRequestFilterMatches(filter, chromeDetails) + ) +} + +const observedSessions = new WeakSet() +const watchedSessions = new WeakSet() +const OBSERVE_ALL = { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*'] } + +/** The events Orca does not otherwise handle, installed once a webRequest extension loads. */ +function observeRemainingEvents(session: Electron.Session): void { + if (observedSessions.has(session)) { + return + } + observedSessions.add(session) + const { webRequest } = session + webRequest.onSendHeaders(OBSERVE_ALL, (details) => forward(session, 'onSendHeaders', details)) + installBrowserSessionHeadersReceived(session) + webRequest.onResponseStarted(OBSERVE_ALL, (details) => + forward(session, 'onResponseStarted', details) + ) + webRequest.onBeforeRedirect(OBSERVE_ALL, (details) => + forward(session, 'onBeforeRedirect', details) + ) + installBrowserSessionRequestLifecycle(session) +} + +export function observeBrowserExtensionWebRequests(session: Electron.Session): void { + const maybeObserve = (extension: Electron.Extension): void => { + if (extensionHasPermission(extension, 'webRequest', session)) { + observeRemainingEvents(session) + } + } + if (!watchedSessions.has(session)) { + watchedSessions.add(session) + session.extensions.on('extension-ready', (_event, extension) => maybeObserve(extension)) + } + session.extensions.getAllExtensions().forEach(maybeObserve) +} + +/** Extensions turned off: hand the session's request path back to Orca's own handlers alone. */ +export function stopObservingBrowserExtensionWebRequests(session: Electron.Session): void { + removeBrowserSessionHeadersReceived(session) + removeBrowserSessionRequestLifecycle(session) + if (!observedSessions.delete(session)) { + return + } + const { webRequest } = session + webRequest.onSendHeaders(null) + webRequest.onResponseStarted(null) + webRequest.onBeforeRedirect(null) +} + +export function installBrowserExtensionWebRequestForwarding(): void { + setBrowserSessionWebRequestObserver(forward) +} diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts index 318f8fbe940..d24ec8647ce 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-discarded-tabs.test.ts @@ -99,7 +99,7 @@ vi.mock('./browser-extension-window-model', () => ({ presentBrowserExtensionWindow: vi.fn() })) vi.mock('../api/tabs-capture', () => ({ captureVisibleTabMethod: {} })) -vi.mock('../api/permissions', () => ({ +vi.mock('../permissions/browser-extension-session-permissions', () => ({ browserExtensionHostPatternsInSession: (_extension: unknown, sess: unknown) => sess === mocks.sessions.default ? mocks.grantedOrigins : [] })) @@ -109,7 +109,7 @@ const discardedTabs = await import('./browser-extension-discarded-tabs') const { recordActiveBrowserPage } = await import('./browser-extension-tab-model') const { registerTabsNamespace } = await import('../api/tabs') const { announceRegisteredBrowserExtensionTab, observeBrowserExtensionTabLifecycle } = - await import('../api/tabs-lifecycle') + await import('./browser-extension-tab-lifecycle') await import('../../../../preload/browser-extension-document-targets') function page(id: string, workspaceId: string, overrides: Partial = {}): BrowserPage { diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts new file mode 100644 index 00000000000..58732fa864f --- /dev/null +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-frame-projection.ts @@ -0,0 +1,27 @@ +import { getBrowserExtensionDocumentId } from './browser-extension-document-ids' + +/** + * Chrome frame ids: 0 for a tab's main frame, the frame-tree-node id otherwise. Electron's own + * content-script `sender.frameId` uses the same numbering, so tabs.sendMessage targets line up. + */ +export function chromeFrameId(frame: Electron.WebFrameMain): number { + return frame.parent ? frame.frameTreeNodeId : 0 +} + +function chromeParentFrameId(frame: Electron.WebFrameMain): number { + return frame.parent ? chromeFrameId(frame.parent) : -1 +} + +/** Chrome's frame fields; `documentId` is left out where the document does not exist yet. */ +export function chromeFrameDocument(frame: Electron.WebFrameMain, withDocument: boolean) { + return { + frameId: chromeFrameId(frame), + parentFrameId: chromeParentFrameId(frame), + ...(withDocument ? { documentId: getBrowserExtensionDocumentId(frame.frameTreeNodeId) } : {}), + ...(frame.parent + ? { parentDocumentId: getBrowserExtensionDocumentId(frame.parent.frameTreeNodeId) } + : {}), + frameType: frame.parent ? ('sub_frame' as const) : ('outermost_frame' as const), + documentLifecycle: 'active' as const + } +} diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-options-page.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-options-page.ts new file mode 100644 index 00000000000..541ab745a2f --- /dev/null +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-options-page.ts @@ -0,0 +1,23 @@ +import { getChromeExtensionOrigin } from '../../../../shared/browser/extensions/browser-extension-url' +import { BrowserExtensionApiError } from '../api-runtime/browser-extension-namespace-registry' +import { openBrowserExtensionTab } from './browser-extension-tab-model' + +function optionsPagePath(extension: Electron.Extension): string | null { + const manifest: { options_ui?: { page?: unknown }; options_page?: unknown } = + extension.manifest ?? {} + const page = manifest.options_ui?.page ?? manifest.options_page + return typeof page === 'string' && page.length > 0 ? page : null +} + +/** Opens the extension's options page as an Orca tab in the given browser profile. */ +export async function openBrowserExtensionOptionsPage( + browserProfileId: string, + extension: Electron.Extension +): Promise { + const page = optionsPagePath(extension) + if (!page) { + throw new BrowserExtensionApiError('This extension has no options page') + } + const url = new URL(page.replace(/^\/+/, ''), `${getChromeExtensionOrigin(extension.id)}/`) + await openBrowserExtensionTab(browserProfileId, url.toString(), true) +} diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-requested-navigation.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-requested-navigation.ts new file mode 100644 index 00000000000..912591a34be --- /dev/null +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-requested-navigation.ts @@ -0,0 +1,21 @@ +import { resolveBrowserExtensionRequestedUrl } from '../../../../shared/browser/extensions/browser-extension-url' +import { + BrowserExtensionApiError, + type BrowserExtensionCaller +} from '../api-runtime/browser-extension-namespace-registry' + +/** Resolves an extension-requested URL through Orca's rules; extension pages must be loaded in `sess`. */ +export function requireOpenableUrl( + caller: BrowserExtensionCaller, + rawUrl: string | undefined, + sess: Electron.Session +): string { + const resolved = resolveBrowserExtensionRequestedUrl(rawUrl, caller.extension.id) + if ( + !resolved || + (resolved.kind === 'extension' && !sess.extensions.getExtension(resolved.extensionId)) + ) { + throw new BrowserExtensionApiError(`Cannot open URL: ${rawUrl ?? ''}`) + } + return resolved.url +} diff --git a/src/main/browser/extensions/api/tabs-lifecycle.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle.ts similarity index 98% rename from src/main/browser/extensions/api/tabs-lifecycle.ts rename to src/main/browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle.ts index afbeb6c8ff4..743584daf4b 100644 --- a/src/main/browser/extensions/api/tabs-lifecycle.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle.ts @@ -11,14 +11,14 @@ import { emitDiscardedBrowserTabRemoved, noteBrowserPageGuestGone, takeDiscardedBrowserTabId -} from '../tabs-and-windows/browser-extension-discarded-tabs' +} from './browser-extension-discarded-tabs' import { isBrowserExtensionSupportEnabled } from '../browser-extension-support' import { canExtensionSeeTabUrl, describeBrowserExtensionTab, replaceActivatedBrowserTabId, resolveBrowserExtensionTab -} from '../tabs-and-windows/browser-extension-tab-model' +} from './browser-extension-tab-model' /** Tabs announced through onCreated or onReplaced, with their window, so onRemoved matches them. */ const announcedTabWindowIds = new Map() diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts index 9cdc971f5e2..9db54215557 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-model.ts @@ -13,7 +13,7 @@ import { type BrowserExtensionCaller } from '../api-runtime/browser-extension-namespace-registry' import { hasBrowserExtensionHostPermission } from '../permissions/browser-extension-permission-grants' -import { browserExtensionHostPatternsInSession } from '../api/permissions' +import { browserExtensionHostPatternsInSession } from '../permissions/browser-extension-session-permissions' import { closeBrowserExtensionPopup } from '../actions/browser-extension-popup-host' import { hasBrowserExtensionActiveTab } from '../permissions/browser-extension-active-tab' import { diff --git a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts index 7c82b7a10a8..36408158c1a 100644 --- a/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts +++ b/src/main/browser/extensions/tabs-and-windows/browser-extension-tab-resolution.test.ts @@ -90,7 +90,7 @@ vi.mock('../permissions/browser-extension-active-tab', () => ({ hasBrowserExtensionActiveTab: (_extensionId: string, tabId: number) => mocks.activeGrants.has(tabId) })) -vi.mock('../api/permissions', () => ({ +vi.mock('../permissions/browser-extension-session-permissions', () => ({ browserExtensionHostPatternsInSession: () => mocks.hostPatterns })) vi.mock('../api/tabs-capture', () => ({ captureVisibleTabMethod: {} })) diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts index 2e209ad717f..454fe682ab4 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-service.ts @@ -26,10 +26,12 @@ import { import { commitStagedWebStoreExtension, discardStagedWebStoreExtension, - isBrowserExtensionBusy, - stageWebStoreExtension, - withBrowserExtensionLock + stageWebStoreExtension } from '../installation/browser-extension-webstore-install' +import { + isBrowserExtensionBusy, + withBrowserExtensionLock +} from '../installation/browser-extension-mutation-lock' import { ChromeWebStoreInstallFlow, InvalidIconUrlError, diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts index d2d55516bd5..dc36c26bdff 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.test.ts @@ -22,7 +22,7 @@ vi.mock('./browser-extension-webstore-download', async (importOriginal) => ({ ...(await importOriginal()), downloadWebStoreCrx: mocks.download })) -vi.mock('../installation/browser-extension-webstore-install', () => ({ +vi.mock('../installation/browser-extension-mutation-lock', () => ({ withBrowserExtensionLock: (_id: string, action: () => Promise) => action(), isBrowserExtensionBusy: () => false })) diff --git a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts index 5ffee7341c2..127282b88f6 100644 --- a/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts +++ b/src/main/browser/extensions/web-store/browser-extension-webstore-updater.ts @@ -24,11 +24,13 @@ import { downloadWebStoreCrx, isAllowedCrxDownloadUrl } from './browser-extensio import { commitStagedWebStoreExtension, discardStagedWebStoreExtension, - isBrowserExtensionBusy, stageWebStoreExtension, - withBrowserExtensionLock, type StagedWebStoreExtension } from '../installation/browser-extension-webstore-install' +import { + isBrowserExtensionBusy, + withBrowserExtensionLock +} from '../installation/browser-extension-mutation-lock' /** * Background updates for store installs. Request shape follows electron-chrome-web-store's diff --git a/src/main/ipc/browser/browser.ts b/src/main/ipc/browser/browser.ts index de5ad39ab89..55f722092e5 100644 --- a/src/main/ipc/browser/browser.ts +++ b/src/main/ipc/browser/browser.ts @@ -26,7 +26,7 @@ import type { } from '../../../shared/browser-page-prompt' import { respondToBrowserPagePrompt } from '../../browser/guest-lifecycle/prompts/browser-page-prompts' import { recordActiveBrowserPage } from '../../browser/extensions/tabs-and-windows/browser-extension-tab-model' -import { announceRegisteredBrowserExtensionTab } from '../../browser/extensions/api/tabs-lifecycle' +import { announceRegisteredBrowserExtensionTab } from '../../browser/extensions/tabs-and-windows/browser-extension-tab-lifecycle' import { registerBrowserExtensionHandlers } from './browser-extensions' import { registerBrowserExtensionContextMenuHandlers } from './browser-extension-context-menu' import {