diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 8e3ca0e7d0d..e6f0b1eeb50 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -3,7 +3,6 @@ # Prune after a fix: pnpm check:flaky-test-pattern-ratchet --prune 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 -3 test-no-in-test-import-actual:src/main/claude-usage/scanner-scan.test.ts 5 test-no-in-test-import-actual:src/main/daemon/endpoint/publication/testing/daemon-endpoint-publish.test.ts 1 test-no-in-test-import-actual:src/main/daemon/history/storage/testing/terminal-history-permissions.test.ts 1 test-no-in-test-import-actual:src/main/git/command-runner/process-capture/spawned-command-tree-kill.test.ts diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index d4fd4620d7d..b01e0b309a5 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -779,9 +779,6 @@ "src/main/claude-accounts/sign-in/claude-sign-in-browser.test.ts": 314, "src/main/claude-accounts/runtime-auth/keychain-config-directory-aliases.test.ts": 51, "src/main/claude-usage/persisted-source-authority.test.ts": 491, - "src/main/claude-usage/scanner-long-context.test.ts": 186, - "src/main/claude-usage/scanner-scan.test.ts": 295, - "src/main/claude-usage/scanner.test.ts": 80, "src/main/claude-usage/source-cache-compression.test.ts": 74, "src/main/claude-usage/transcript-file-discovery-errors.test.ts": 62, "src/main/claude-usage/transcript-reader-lifetime.test.ts": 100, @@ -903,13 +900,11 @@ "src/main/codex-accounts/account-management/sta-4734-login-rollback-deletes-authenticated-home.test.ts": 713, "src/main/codex-cli/codex-home-process-lock.test.ts": 52, "src/main/codex-usage/codex-rollout-file-lifetime.test.ts": 173, - "src/main/codex-usage/codex-usage-long-context-billing.test.ts": 615, "src/main/codex-usage/scanner-checkpoint-races.test.ts": 523, "src/main/codex-usage/scanner-file-identity.test.ts": 389, "src/main/codex-usage/scanner-incremental-append.test.ts": 690, "src/main/codex-usage/scanner-large-directory.test.ts": 503, "src/main/codex-usage/scanner-paths.test.ts": 493, - "src/main/codex-usage/scanner.test.ts": 247, "src/main/codex-usage/session-file-discovery-errors.test.ts": 70, "src/main/codex/app-server/codex-app-server-client.test.ts": 13839, "src/main/codex/app-server/codex-app-server-connection-exit-order.test.ts": 264, @@ -1707,7 +1702,6 @@ "src/main/memory/hydrate-local-pty-registry.test.ts": 1970, "src/main/memory/verified-local-folder-workspaces.test.ts": 74, "src/main/mimo/hook-service.test.ts": 115, - "src/main/muse-usage/scanner.test.ts": 363, "src/main/native-chat/agent-model-catalog/agent-model-catalog-discovery-freshness.test.ts": 390, "src/main/native-chat/agent-model-catalog/agent-model-catalog-probe-runner.test.ts": 4786, "src/main/native-chat/agent-model-catalog/agent-model-catalog-store.test.ts": 611, @@ -1830,7 +1824,6 @@ "src/main/observability/redactor.test.ts": 80, "src/main/omp/omp-session-cwd-lookup.test.ts": 232, "src/main/opencode-usage/scanner-windows-data-directory.test.ts": 464, - "src/main/opencode-usage/scanner.test.ts": 554, "src/main/opencode/status-hooks/hook-service-startup-refresh.test.ts": 111, "src/main/opencode/status-hooks/hook-service.test.ts": 262, "src/main/opencode/model-launch/opencode-launch-model-context-supervision.test.ts": 2290, @@ -1999,7 +1992,6 @@ "src/main/pi/rpc/rpc-session-startup.test.ts": 4955, "src/main/pi/rpc/rpc-turn-races.test.ts": 2191, "src/main/pi/managed-extensions/titlebar-extension-service.test.ts": 263, - "src/main/plugins/catalog/plugin-install-stats-service.test.ts": 196, "src/main/plugins/catalog/plugin-kill-list-content-revocation.test.ts": 3680, "src/main/plugins/catalog/plugin-marketplace-installer.test.ts": 859, "src/main/plugins/catalog/plugin-marketplace-store.test.ts": 250, @@ -2008,7 +2000,6 @@ "src/main/plugins/contributions/plugin-content-pack-registry.test.ts": 589, "src/main/plugins/contributions/plugin-icon-theme-registry.test.ts": 268, "src/main/plugins/contributions/plugin-syntax-registry.test.ts": 221, - "src/main/plugins/contributions/plugin-theme-registries.test.ts": 250, "src/main/plugins/installation/plugin-catalog-install-guard.test.ts": 475, "src/main/plugins/installation/plugin-derived-publisher.test.ts": 620, "src/main/plugins/installation/plugin-git-ref-resolution.integration.test.ts": 608, @@ -3221,7 +3212,6 @@ "src/renderer/src/components/activity/activity-thread-list-pane.multi-select.test.tsx": 4699, "src/renderer/src/components/activity/useActivityUnreadCount.freshness.test.tsx": 1990, "src/renderer/src/components/agent-tab-shortcut-launch.test.ts": 369, - "src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx": 2090, "src/renderer/src/components/artifacts/ArtifactPublishButton.test.tsx": 706, "src/renderer/src/components/artifacts/ArtifactsPage.test.tsx": 2052, "src/renderer/src/components/artifacts/artifact-publish-flow.test.ts": 114, @@ -3536,7 +3526,6 @@ "src/renderer/src/components/native-chat/session/structured/read/use-structured-agent-session-read.test.tsx": 3081, "src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.clear-send.test.tsx": 2804, "src/renderer/src/components/native-chat/pane/actions/use-structured-native-chat-submit-reveal.test.ts": 2304, - "src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx": 870, "src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856, "src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094, "src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts": 342, @@ -3784,7 +3773,6 @@ "src/renderer/src/components/terminal-pane/emulation/terminal-capability-replies.test.ts": 131, "src/renderer/src/components/terminal-pane/clipboard/terminal-clipboard-paste.test.ts": 76, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-runtime-catalog-owner.test.ts": 872, - "src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts": 527, "src/renderer/src/components/terminal-pane/emulation/terminal-idle-cursor-reset.test.ts": 190, "src/renderer/src/components/terminal-pane/input/ime/terminal-ime-forwarder-space-claim.test.ts": 257, "src/renderer/src/components/terminal-pane/input/ime/terminal-ime-hangul-terminating-digit.test.ts": 545, @@ -4002,7 +3990,6 @@ "src/renderer/src/lib/workspace/persistence/workspace-session-host-emptied-fields.test.ts": 279, "src/renderer/src/lib/workspace/persistence/workspace-session-ssh-partition-ownership.test.ts": 309, "src/renderer/src/lib/workspace/persistence/workspace-session-ssh-partition-round-trip.test.ts": 1775, - "src/renderer/src/lib/workspace/search/tabs/workspace-tab-palette-activation.store.test.ts": 1994, "src/renderer/src/lib/workspace/ownership/workspace-terminal-host-authority.test.ts": 2066, "src/renderer/src/lib/workspace/activation/worktree-activation-created-agent.test.ts": 2295, "src/renderer/src/lib/workspace/activation/worktree-activation-structured-chat-surface.test.ts": 2043, @@ -4271,7 +4258,6 @@ "src/shared/ai-vault/search/ai-vault-search-contract.test.ts": 148, "src/shared/ai-vault/search/ai-vault-search-status-fallback.test.ts": 175, "src/shared/ai-vault/scanning/ai-vault-session-depth.test.ts": 78, - "src/shared/ai-vault/session-display/ai-vault-session-filters.test.ts": 176, "src/shared/ansi-escape-sequences-consumers.test.ts": 140, "src/shared/antigravity-generation-plan.test.ts": 122, "src/shared/automatic-work-run-marker.test.ts": 93, @@ -4596,7 +4582,6 @@ "src/shared/ssh-retained-payload-admission.test.ts": 69, "src/shared/startup-command-staging.node-pty.test.ts": 2207, "src/shared/structured-session-message-contracts.test.ts": 411, - "src/shared/task-query.test.ts": 55, "src/shared/program-status/terminal-agent-status-processor.test.ts": 74, "src/shared/terminal/input/terminal-composer-draft.test.ts": 73, "src/shared/terminal/links/terminal-github-pr-link-detector.test.ts": 61, @@ -4672,7 +4657,6 @@ "src/shared/workspace-layout/commands/workspace-layout-open-in-new-group.test.ts": 195, "src/shared/workspace-layout/editor-tabs/workspace-layout-owned-editor-id.test.ts": 334, "src/shared/workspace-layout/commands/workspace-layout-process-rules.test.ts": 201, - "src/shared/workspace-layout/commands/workspace-layout-ratio-commands.test.ts": 156, "src/shared/workspace-layout/published-layout/workspace-layout-records.test.ts": 325, "src/shared/workspace-layout/commands/workspace-layout-resume-record.test.ts": 370, "src/shared/workspace-layout/commands/workspace-layout-simulator-tab.test.ts": 159, diff --git a/mobile/src/session/native-chat/input/session-options/MobileNativeChatSessionOptionPickers.test.ts b/mobile/src/session/native-chat/input/session-options/MobileNativeChatSessionOptionPickers.test.ts index 53b168062e8..a6812ea9e67 100644 --- a/mobile/src/session/native-chat/input/session-options/MobileNativeChatSessionOptionPickers.test.ts +++ b/mobile/src/session/native-chat/input/session-options/MobileNativeChatSessionOptionPickers.test.ts @@ -148,31 +148,6 @@ describe('MobileNativeChatSessionOptionPickers', () => { renderer = null }) - it('names both the saved and running permission on the model pill and in the drill-in', () => { - mount([MODEL_DESCRIPTOR, DEFERRED_PERMISSION_DESCRIPTOR], false, 'permissionMode') - expect(pill('Model').props.accessibilityLabel).toMatch(/Full access.*Ask for approval$/) - const texts = findAllByHostType(findByHostType(renderer!.root, 'BottomDrawer'), 'Text').map( - (node) => node.props.children - ) - expect(texts.some((text) => /Full access.*Ask for approval/.test(String(text)))).toBe(true) - }) - - it('shows the saved permission as the home row value and the running one in its subtitle', () => { - mount([MODEL_DESCRIPTOR, DEFERRED_PERMISSION_DESCRIPTOR], false, 'model') - const row = renderer!.root.find( - (node) => - String(node.type) === 'Pressable' && - typeof node.props.accessibilityLabel === 'string' && - node.props.accessibilityLabel.startsWith('Permissions') - ) - expect(row.props.accessibilityLabel).toMatch(/Full access.*Ask for approval/) - const texts = findAllByHostType(row, 'Text').map((node) => String(node.props.children)) - expect(texts).toContain('Full access') - expect( - texts.some((text) => !text.includes('Full access') && text.includes('Ask for approval')) - ).toBe(true) - }) - it('consumes a refused page without replay, then permits a fresh open and permission pick', async () => { const placeholder: SessionOptionDescriptor = { ...MODEL_DESCRIPTOR, @@ -209,11 +184,3 @@ const PERMISSION_DESCRIPTOR: SessionOptionDescriptor = { transport: 'agent-session', settable: true } - -const DEFERRED_PERMISSION_DESCRIPTOR: SessionOptionDescriptor = { - ...PERMISSION_DESCRIPTOR, - kind: { type: 'select', currentValue: 'full-access', choices: PERMISSION_CHOICES }, - valueSource: 'dispatched', - activeValue: 'ask', - description: 'Full access' -} diff --git a/mobile/src/worktree/workspace-list/workspace-list-sections-desktop-parity.test.ts b/mobile/src/worktree/workspace-list/workspace-list-sections-desktop-parity.test.ts deleted file mode 100644 index 9d0fa8acb34..00000000000 --- a/mobile/src/worktree/workspace-list/workspace-list-sections-desktop-parity.test.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { NO_WORKSPACE_ROW_FILTERS } from '../../../../src/shared/workspace-view/workspace-row-filters' -import { describe, expect, it } from 'vitest' -import { getRepoExecutionHostId } from '../../../../src/shared/execution-host' -import { - PROJECT_SECTION_PARITY_ROWS, - PROJECT_SECTION_PARITY_SERVED -} from '../../../../src/shared/sidebar-list/sections/project-section-parity.test-fixture' -import { buildProjectSectionCatalog } from '../project-sections/project-section-catalog' -import { readServedProjectSections } from '../project-sections/project-sections-operations' -import { buildSections } from './workspace-list-sections' -import type { Worktree } from './workspace-list-types' -import type { ServedProjectSections } from '../../../../src/shared/sidebar-list/catalog/project-section-catalog-schema' -import type { ProjectGroup } from '../../../../src/shared/project/groups/project-group-types' - -function rows(): Worktree[] { - const repoById = new Map(PROJECT_SECTION_PARITY_SERVED.repos.map((repo) => [repo.id, repo])) - return PROJECT_SECTION_PARITY_ROWS.flatMap((row) => { - const repo = repoById.get(row.repoId) - return repo - ? [ - { - worktreeId: row.id, - repoId: row.repoId, - hostId: getRepoExecutionHostId(repo), - repo: repo.displayName, - branch: 'feature', - displayName: row.id, - path: `${repo.path}-${row.id}`, - lastActivityAt: row.lastActivityAt, - liveTerminalCount: 0, - hasAttachedPty: false, - unread: false, - isPinned: false, - linkedPR: null - } - ] - : [] - }) -} - -function headers(catalog: ReturnType) { - return buildSections( - rows(), - 'recent', - { ...NO_WORKSPACE_ROW_FILTERS }, - '', - 'repo', - new Set(), - catalog - ).map((section) => ({ key: section.key, label: section.title })) -} - -describe('Project grouping on the phone', () => { - it("groups by repo from an older desktop's own repos when it serves no catalog", () => { - const desktopRepos = PROJECT_SECTION_PARITY_SERVED.repos.filter( - (repo) => repo.executionHostId === 'local' - ) - - expect(headers(buildProjectSectionCatalog(null, desktopRepos, [], null, 'manual'))).toEqual([ - { key: 'repo:m4-orca-two', label: 'orca' }, - { key: 'repo:win-orca', label: 'orca' }, - { key: 'repo:local-workspace', label: 'orca/orca' }, - { key: 'repo:local-stably', label: 'stably/orca' }, - { key: 'repo:m4-orca', label: 'orca' }, - { key: 'repo:local-assets', label: 'design-assets' } - ]) - }) -}) - -function group(id: string, name: string, fields: Partial = {}): ProjectGroup { - return { - id, - name, - parentPath: null, - parentGroupId: null, - createdFrom: 'manual', - tabOrder: 0, - isCollapsed: false, - color: null, - createdAt: 1, - updatedAt: 1, - ...fields - } -} - -function row(worktreeId: string, repoId: string, fields: Partial = {}): Worktree { - return { - worktreeId, - repoId, - repo: repoId, - branch: worktreeId, - displayName: worktreeId, - path: `/src/${worktreeId}`, - liveTerminalCount: 0, - hasAttachedPty: false, - unread: false, - isPinned: false, - linkedPR: null, - ...fields - } -} - -describe('Project groups on the phone', () => { - const repos: ServedProjectSections['repos'] = [ - { id: 'infra-tf', displayName: 'infra-tf', path: '/src/infra-tf', projectGroupId: 'g-infra' }, - { id: 'dotfiles', displayName: 'dotfiles', path: '/src/dotfiles', projectGroupOrder: 1000 }, - { id: 'orca-docs', displayName: 'orca-docs', path: '/src/orca-docs', projectGroupId: 'g-docs' }, - { - id: 'orca-mobile', - displayName: 'orca-mobile', - path: '/src/orca-mobile', - projectGroupId: 'g-orca', - projectGroupOrder: 1000 - }, - { - id: 'orca', - displayName: 'orca', - path: '/src/orca', - projectGroupId: 'g-orca', - projectGroupOrder: 0 - } - ] - const groups = [ - group('g-infra', 'Infra', { rootProjectOrder: 2000, createdFrom: 'folder-scan' }), - group('g-docs', 'Docs', { parentGroupId: 'g-orca' }), - group('g-orca', 'Orca', { rootProjectOrder: 0 }) - ] - const worktrees = [ - row('wt-infra', 'infra-tf'), - row('wt-dotfiles', 'dotfiles'), - row('wt-docs', 'orca-docs'), - row('wt-mobile', 'orca-mobile'), - row('wt-orca', 'orca'), - row('scratch', 'folder-workspace:g-infra', { workspaceKind: 'folder-workspace' }), - // An agent's worktree started from the folder workspace nests under it. - row('wt-agent', 'infra-tf', { parentWorktreeId: 'scratch' }) - ] - - function tree(collapsed: Set) { - return buildSections( - worktrees, - 'name', - { ...NO_WORKSPACE_ROW_FILTERS }, - '', - 'repo', - new Set(), - buildProjectSectionCatalog( - { repos, projects: [], setups: [], projectOrderBy: 'manual', projectGroups: groups }, - [], - [], - null, - 'manual' - ), - undefined, - collapsed - ).map((section) => [ - section.key, - section.projectGroupDepth ?? 0, - section.count ?? null, - section.data.map( - ({ row, view }) => - `${row.worktreeId}@${view.projectGroupDepth ?? 0}${view.lineageDepth ? '+' : ''}` - ) - ]) - } - - it('nests projects and folders under groups in the desktop sidebar order', () => { - expect(tree(new Set())).toEqual([ - ['project-group:g-orca', 0, 3, []], - ['repo:orca', 1, null, ['wt-orca@1']], - ['repo:orca-mobile', 1, null, ['wt-mobile@1']], - ['project-group:g-docs', 1, 1, []], - ['repo:orca-docs', 2, null, ['wt-docs@2']], - ['repo:dotfiles', 0, null, ['wt-dotfiles@0']], - ['project-group:g-infra', 0, 2, ['scratch@1', 'wt-agent@1+']], - // wt-agent still counts in its own project, as on the desktop. - ['repo:infra-tf', 1, 2, ['wt-infra@1']] - ]) - }) - - it('hides everything under a collapsed group, nested groups included', () => { - expect(tree(new Set(['project-group:g-orca'])).map(([key]) => key)).toEqual([ - 'project-group:g-orca', - 'repo:dotfiles', - 'project-group:g-infra', - 'repo:infra-tf' - ]) - }) -}) - -describe('readServedProjectSections', () => { - it.each(['forbidden', 'method_not_found'])( - 'reads an older desktop that answers %s as serving none', - (code) => { - expect( - readServedProjectSections({ id: 'sections', ok: false, error: { code, message: code } }) - ).toEqual({ kind: 'answered', value: null }) - } - ) - - it('keeps the last catalog after a timeout or a dropped reply', () => { - expect( - readServedProjectSections({ - id: 'sections', - ok: false, - error: { code: 'timeout', message: 'timed out' } - }) - ).toEqual({ kind: 'kept' }) - expect(readServedProjectSections(null)).toEqual({ kind: 'kept' }) - }) -}) diff --git a/src/main/claude-usage/scanner-long-context.test.ts b/src/main/claude-usage/scanner-long-context.test.ts deleted file mode 100644 index f082f5c959f..00000000000 --- a/src/main/claude-usage/scanner-long-context.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import type * as NodeOs from 'node:os' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { scanClaudeUsageFiles } from './scanner' -import type { ClaudeUsagePersistedFile } from './types' - -const { homedirMock } = vi.hoisted(() => ({ homedirMock: vi.fn<() => string>() })) - -vi.mock('node:os', async () => ({ - ...(await vi.importActual('node:os')), - homedir: homedirMock -})) - -vi.mock('../claude-accounts/profiles/routing/claude-profile-installed-router', () => ({ - claudeProfileHistoryDirs: () => [] -})) - -type ScanResult = Awaited> - -let root: string -let transcriptPath: string - -beforeEach(async () => { - root = await mkdtemp(join(tmpdir(), 'orca-claude-usage-long-context-')) - homedirMock.mockReturnValue(root) - const projectDir = join(root, '.claude', 'projects', 'project-a') - await mkdir(projectDir, { recursive: true }) - transcriptPath = join(projectDir, 'long-context-session.jsonl') - vi.resetModules() -}) - -afterEach(async () => { - await rm(root, { recursive: true, force: true }) -}) - -function assistantRow(key: string, model: string, cacheReadTokens: number): string { - return `${JSON.stringify({ - type: 'assistant', - sessionId: 'long-context-session', - timestamp: '2026-10-09T12:00:00.000Z', - cwd: join(root, 'workspace'), - requestId: `request-${key}`, - message: { - id: `message-${key}`, - model, - usage: { input_tokens: 1_000, output_tokens: 500, cache_read_input_tokens: cacheReadTokens } - } - })}\n` -} - -// Resume checkpoints require at least MIN_RESUMABLE_PREFIX_BYTES. - -async function scan(previous: ClaudeUsagePersistedFile[] = []): Promise { - const { scanClaudeUsageFiles } = await import('./scanner') - return scanClaudeUsageFiles([], previous, undefined, []) -} - -describe('Claude usage long-context subsets', () => { - it('records only requests whose prompt crosses their own model threshold', async () => { - await writeFile( - transcriptPath, - assistantRow('haiku-long', 'claude-haiku-5-5', 100_000) + - assistantRow('haiku-short', 'claude-haiku-5-5', 98_000) + - assistantRow('sonnet-short', 'claude-sonnet-4-5', 150_000) + - assistantRow('flat', 'claude-sonnet-4-6', 500_000) - ) - - const result = await scan() - - const byModel = new Map(result.dailyAggregates.map((row) => [row.model, row])) - expect(byModel.get('claude-haiku-5-5')?.longContext).toEqual({ - inputTokens: 1_000, - outputTokens: 500, - cacheReadTokens: 100_000, - cacheWriteTokens: 0, - cacheWrite1hTokens: 0 - }) - expect(byModel.get('claude-haiku-5-5')?.cacheReadTokens).toBe(198_000) - expect(byModel.get('claude-sonnet-4-5')?.longContext).toBeUndefined() - expect(byModel.get('claude-sonnet-4-6')?.longContext).toBeUndefined() - expect(result.sessions[0]?.locationBreakdown[0]?.longContext?.cacheReadTokens).toBe(100_000) - }) -}) diff --git a/src/main/claude-usage/scanner-scan.test.ts b/src/main/claude-usage/scanner-scan.test.ts deleted file mode 100644 index 56f7e2549c2..00000000000 --- a/src/main/claude-usage/scanner-scan.test.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type * as Os from 'node:os' - -const tempRoots: string[] = [] - -async function makeClaudeProjectsRoot(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-claude-usage-')) - tempRoots.push(root) - await mkdir(join(root, '.claude', 'projects', 'project-a'), { recursive: true }) - await mkdir(join(root, '.claude', 'transcripts'), { recursive: true }) - return root -} - -afterEach(async () => { - vi.doUnmock('os') - vi.doUnmock('fs/promises') - vi.resetModules() - await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('scanClaudeUsageFiles', () => { - it('scans transcript files from the configured Claude projects directory', async () => { - const root = await makeClaudeProjectsRoot() - const projectDir = join(root, '.claude', 'projects', 'project-a') - const transcriptsDir = join(root, '.claude', 'transcripts') - const firstFile = join(projectDir, 'a.jsonl') - const secondFile = join(projectDir, 'b.jsonl') - const transcriptFile = join(transcriptsDir, 'ses_123.jsonl') - - await writeFile( - firstFile, - [ - JSON.stringify({ - type: 'assistant', - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:00.000Z', - cwd: '/workspace/repo-a', - message: { - model: 'claude-sonnet-4-6', - usage: { - input_tokens: 100, - output_tokens: 20, - cache_read_input_tokens: 10, - cache_creation_input_tokens: 5 - } - } - }), - JSON.stringify({ type: 'user', sessionId: 'session-1' }) - ].join('\n') - ) - await writeFile( - secondFile, - JSON.stringify({ - type: 'assistant', - sessionId: 'session-2', - timestamp: '2026-04-10T10:00:00.000Z', - cwd: '/outside/repo-b', - message: { - model: 'claude-sonnet-4-6', - usage: { - input_tokens: 50, - output_tokens: 10 - } - } - }) - ) - await writeFile( - transcriptFile, - JSON.stringify({ - type: 'assistant', - timestamp: '2026-04-11T10:00:00.000Z', - cwd: '/workspace/repo-a/packages/app', - message: { - model: 'claude-sonnet-4-6', - usage: { - input_tokens: 70, - output_tokens: 15, - cache_read_input_tokens: 20 - } - } - }) - ) - - vi.resetModules() - vi.doMock('os', async () => ({ - ...(await vi.importActual('os')), - homedir: () => root - })) - const { scanClaudeUsageFiles } = await import('./scanner') - - const result = await scanClaudeUsageFiles([ - { - repoId: 'repo-1', - worktreeId: 'worktree-1', - path: '/workspace/repo-a', - displayName: 'Repo A' - } - ]) - - expect(result.processedFiles.map((file) => [file.path, file.lineCount])).toEqual([ - [firstFile, 2], - [secondFile, 1], - [transcriptFile, 1] - ]) - expect(result.sessions.map((session) => session.sessionId)).toEqual([ - 'ses_123', - 'session-2', - 'session-1' - ]) - expect(result.dailyAggregates).toHaveLength(3) - expect(result.dailyAggregates[0]?.projectLabel).toBe('Repo A') - expect(result.dailyAggregates[2]?.projectLabel).toBe('Repo A') - }) - - it('dedupes fork copies when only message.id is present (no requestId)', async () => { - const root = await makeClaudeProjectsRoot() - const projectDir = join(root, '.claude', 'projects', 'project-a') - const originalFile = join(projectDir, 'aaaa-original.jsonl') - const forkFile = join(projectDir, 'bbbb-fork.jsonl') - - const turn = (sessionId: string, messageId: string, inputTokens: number): string => - JSON.stringify({ - type: 'assistant', - sessionId, - timestamp: '2026-04-09T10:00:00.000Z', - cwd: '/workspace/repo-a', - message: { - id: messageId, - model: 'claude-sonnet-4-6', - usage: { input_tokens: inputTokens, output_tokens: 10 } - } - }) - - await writeFile(originalFile, turn('session-1', 'msg_1', 100)) - await writeFile( - forkFile, - [turn('session-2', 'msg_1', 100), turn('session-2', 'msg_2', 50)].join('\n') - ) - - vi.resetModules() - vi.doMock('os', async () => ({ - ...(await vi.importActual('os')), - homedir: () => root - })) - const { scanClaudeUsageFiles } = await import('./scanner') - - const result = await scanClaudeUsageFiles([]) - expect(result.dailyAggregates.reduce((sum, row) => sum + row.inputTokens, 0)).toBe(150) - expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['msg:msg_1']) - expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['msg:msg_2']) - }) - - it('dedupes fork copies via uuid when message ids are absent', async () => { - const root = await makeClaudeProjectsRoot() - const projectDir = join(root, '.claude', 'projects', 'project-a') - const originalFile = join(projectDir, 'aaaa-original.jsonl') - const forkFile = join(projectDir, 'bbbb-fork.jsonl') - - const turn = (sessionId: string, uuid: string, inputTokens: number): string => - JSON.stringify({ - type: 'assistant', - sessionId, - uuid, - timestamp: '2026-04-09T10:00:00.000Z', - cwd: '/workspace/repo-a', - message: { - model: 'claude-sonnet-4-6', - usage: { input_tokens: inputTokens, output_tokens: 10 } - } - }) - - await writeFile(originalFile, turn('session-1', 'uuid-1', 100)) - await writeFile( - forkFile, - [turn('session-2', 'uuid-1', 100), turn('session-2', 'uuid-2', 40)].join('\n') - ) - - vi.resetModules() - vi.doMock('os', async () => ({ - ...(await vi.importActual('os')), - homedir: () => root - })) - const { scanClaudeUsageFiles } = await import('./scanner') - - const result = await scanClaudeUsageFiles([]) - expect(result.dailyAggregates.reduce((sum, row) => sum + row.inputTokens, 0)).toBe(140) - expect(result.processedFiles[0]?.ownedDedupeKeys).toEqual(['uuid:uuid-1']) - expect(result.processedFiles[1]?.ownedDedupeKeys).toEqual(['uuid:uuid-2']) - }) -}) diff --git a/src/main/claude-usage/scanner.test.ts b/src/main/claude-usage/scanner.test.ts deleted file mode 100644 index a552c84501c..00000000000 --- a/src/main/claude-usage/scanner.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { parseClaudeUsageFile, parseClaudeUsageRecord } from './transcript-record-parser' -import { attributeClaudeUsageTurns } from './worktree-attribution' - -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { join } from 'node:path' -import { tmpdir } from 'node:os' - -describe('parseClaudeUsageRecord', () => { - it('clamps a 1-hour breakdown that exceeds the reported cache-write total', () => { - const parsed = parseClaudeUsageRecord( - JSON.stringify({ - type: 'assistant', - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:00.000Z', - message: { - model: 'claude-sonnet-4-6', - usage: { - input_tokens: 100, - output_tokens: 25, - cache_creation_input_tokens: 100, - cache_creation: { ephemeral_1h_input_tokens: 400 } - } - } - }) - ) - - expect(parsed?.cacheWriteTokens).toBe(100) - expect(parsed?.cacheWrite1hTokens).toBe(100) - }) - - it('merges duplicate streamed assistant usage by message and request id', async () => { - const root = await mkdtemp(join(tmpdir(), 'orca-claude-dedupe-')) - const filePath = join(root, 'session.jsonl') - try { - await writeFile( - filePath, - [ - JSON.stringify({ - type: 'assistant', - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:00.000Z', - requestId: 'req-1', - message: { - id: 'msg-1', - model: 'claude-sonnet-4-6', - usage: { - input_tokens: 100, - output_tokens: 25, - cache_read_input_tokens: 10, - cache_creation_input_tokens: 5 - } - } - }), - JSON.stringify({ - type: 'assistant', - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:01.000Z', - requestId: 'req-1', - message: { - id: 'msg-1', - model: 'claude-sonnet-4-6', - usage: { - input_tokens: 120, - output_tokens: 30, - cache_read_input_tokens: 12, - cache_creation_input_tokens: 7 - } - } - }) - ].join('\n') - ) - - await expect(parseClaudeUsageFile(filePath)).resolves.toEqual([ - { - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:00.000Z', - model: 'claude-sonnet-4-6', - cwd: null, - gitBranch: null, - inputTokens: 120, - outputTokens: 30, - cacheReadTokens: 12, - cacheWriteTokens: 7, - cacheWrite1hTokens: 0 - } - ]) - } finally { - await rm(root, { recursive: true, force: true }) - } - }) -}) - -describe('Claude usage aggregation', () => { - it('attributes nested cwd paths to the containing worktree', async () => { - const attributed = await attributeClaudeUsageTurns( - [ - { - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:00.000Z', - model: 'claude-sonnet-4-6', - cwd: '/workspace/repo-a/packages/app', - gitBranch: 'feature/a', - inputTokens: 100, - outputTokens: 20, - cacheReadTokens: 10, - cacheWriteTokens: 5, - cacheWrite1hTokens: 0 - } - ], - new Map([ - [ - '/workspace/repo-a', - { - repoId: 'repo-1', - worktreeId: 'repo-1::/workspace/repo-a', - path: '/workspace/repo-a', - displayName: 'Repo A' - } - ] - ]) - ) - - expect(attributed[0]?.projectKey).toBe('worktree:repo-1::/workspace/repo-a') - expect(attributed[0]?.projectLabel).toBe('Repo A') - }) -}) diff --git a/src/main/codex-usage/codex-usage-long-context-billing.test.ts b/src/main/codex-usage/codex-usage-long-context-billing.test.ts deleted file mode 100644 index d095211610f..00000000000 --- a/src/main/codex-usage/codex-usage-long-context-billing.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { describe, expect, it } from 'vitest' - -import { parseCodexUsageRecord, type CodexUsageParseContext } from './codex-usage-record-parser' - -type Usage = { input: number; cached: number; output: number } - -function usageJson({ input, cached, output }: Usage) { - return { - input_tokens: input, - cached_input_tokens: cached, - output_tokens: output, - reasoning_output_tokens: 0, - total_tokens: input + output - } -} - -function tokenCountLine(timestamp: string, total: Usage, last?: Usage): string { - return JSON.stringify({ - timestamp, - type: 'event_msg', - payload: { - type: 'token_count', - info: { - total_token_usage: usageJson(total), - ...(last ? { last_token_usage: usageJson(last) } : {}) - } - } - }) -} - -function createContext(): CodexUsageParseContext { - return { - sessionId: 'session-1', - sessionCwd: '/workspace/repo', - currentCwd: '/workspace/repo', - currentModel: 'gpt-6-astra', - previousTotals: null - } -} - -function requestLines(requests: { timestamp: string; usage: Usage }[]): string[] { - const total: Usage = { input: 0, cached: 0, output: 0 } - return requests.map(({ timestamp, usage }) => { - total.input += usage.input - total.cached += usage.cached - total.output += usage.output - return tokenCountLine(timestamp, { ...total }, usage) - }) -} - -describe('per-request long-context classification', () => { - it('classifies a request as long only when its prompt exceeds 272,000 tokens', () => { - const context = createContext() - const [atThreshold, overThreshold] = requestLines([ - { - timestamp: '2026-04-09T10:00:00.000Z', - usage: { input: 272_000, cached: 200_000, output: 1 } - }, - { - timestamp: '2026-04-09T10:01:00.000Z', - usage: { input: 272_001, cached: 200_000, output: 1 } - } - ]).map((line) => parseCodexUsageRecord(line, context)) - - expect(atThreshold).toMatchObject({ - longContextInputTokens: 0, - longContextCachedInputTokens: 0, - longContextOutputTokens: 0 - }) - expect(overThreshold).toMatchObject({ - longContextInputTokens: 272_001, - longContextCachedInputTokens: 200_000, - longContextOutputTokens: 1 - }) - }) - - it('never classes a total-only delta as long, since it can span several requests', () => { - const context = createContext() - const events = [ - tokenCountLine('2026-04-09T10:00:00.000Z', { input: 100_000, cached: 50_000, output: 1_000 }), - tokenCountLine('2026-04-09T10:01:00.000Z', { - input: 400_000, - cached: 200_000, - output: 3_000 - }), - tokenCountLine('2026-04-09T10:01:01.000Z', { - input: 400_000, - cached: 200_000, - output: 3_000 - }), - tokenCountLine('2026-04-09T10:02:00.000Z', { input: 500_000, cached: 250_000, output: 4_000 }) - ].map((line) => parseCodexUsageRecord(line, context)) - - expect(events.map((event) => event?.inputTokens ?? null)).toEqual([ - 100_000, - 300_000, - null, - 100_000 - ]) - expect(events.map((event) => event?.longContextInputTokens ?? null)).toEqual([0, 0, null, 0]) - expect(events[1]).toMatchObject({ - longContextCachedInputTokens: 0, - longContextOutputTokens: 0 - }) - }) -}) diff --git a/src/main/codex-usage/scanner.test.ts b/src/main/codex-usage/scanner.test.ts deleted file mode 100644 index 532ff86a1fb..00000000000 --- a/src/main/codex-usage/scanner.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -const { getPathMock } = vi.hoisted(() => ({ - getPathMock: vi.fn<(name: string) => string>() -})) - -vi.mock('electron', () => ({ - app: { - getPath: getPathMock - } -})) - -import { parseCodexUsageRecord } from './codex-usage-record-parser' - -describe('parseCodexUsageRecord', () => { - it('uses token totals only as a duplicate baseline', () => { - const context = { - sessionId: 'session-1', - sessionCwd: null, - currentCwd: null, - currentModel: null, - previousTotals: null - } - - expect( - parseCodexUsageRecord( - JSON.stringify({ - type: 'session_meta', - payload: { id: 'session-1', cwd: '/workspace/repo' } - }), - context - ) - ).toBeNull() - - expect( - parseCodexUsageRecord( - JSON.stringify({ - type: 'turn_context', - payload: { cwd: '/workspace/repo/packages/app', model: 'gpt-5.2-codex' } - }), - context - ) - ).toBeNull() - - const first = parseCodexUsageRecord( - JSON.stringify({ - timestamp: '2026-04-09T10:00:00.000Z', - type: 'event_msg', - payload: { - type: 'token_count', - info: { - total_token_usage: { - input_tokens: 1000, - cached_input_tokens: 400, - output_tokens: 250, - reasoning_output_tokens: 100, - total_tokens: 1250 - }, - last_token_usage: { - input_tokens: 1000, - cached_input_tokens: 400, - output_tokens: 250, - reasoning_output_tokens: 100, - total_tokens: 1250 - } - } - } - }), - context - ) - - const duplicate = parseCodexUsageRecord( - JSON.stringify({ - timestamp: '2026-04-09T10:00:01.000Z', - type: 'event_msg', - payload: { - type: 'token_count', - info: { - total_token_usage: { - input_tokens: 1000, - cached_input_tokens: 400, - output_tokens: 250, - reasoning_output_tokens: 100, - total_tokens: 1250 - }, - last_token_usage: { - input_tokens: 1000, - cached_input_tokens: 400, - output_tokens: 250, - reasoning_output_tokens: 100, - total_tokens: 1250 - } - } - } - }), - context - ) - - expect(first).toEqual({ - sessionId: 'session-1', - timestamp: '2026-04-09T10:00:00.000Z', - eventKey: expect.any(String), - cwd: '/workspace/repo/packages/app', - model: 'gpt-5.2-codex', - hasInferredPricing: false, - longContextInputTokens: 0, - longContextCachedInputTokens: 0, - longContextOutputTokens: 0, - inputTokens: 1000, - cachedInputTokens: 400, - outputTokens: 250, - reasoningOutputTokens: 100, - totalTokens: 1250 - }) - expect(duplicate).toBeNull() - }) - - it('uses last token usage for the first resumed-session event', () => { - const context = { - sessionId: 'session-1', - sessionCwd: '/workspace/repo', - currentCwd: '/workspace/repo', - currentModel: 'gpt-5.5', - previousTotals: null - } - - const parsed = parseCodexUsageRecord( - JSON.stringify({ - timestamp: '2026-04-09T10:00:00.000Z', - type: 'event_msg', - payload: { - type: 'token_count', - info: { - total_token_usage: { - input_tokens: 50_000, - cached_input_tokens: 40_000, - output_tokens: 5_000, - reasoning_output_tokens: 1_000, - total_tokens: 55_000 - }, - last_token_usage: { - input_tokens: 2_000, - cached_input_tokens: 1_500, - output_tokens: 500, - reasoning_output_tokens: 100, - total_tokens: 2_500 - } - } - } - }), - context - ) - - expect(parsed).toMatchObject({ - inputTokens: 2_000, - cachedInputTokens: 1_500, - outputTokens: 500, - reasoningOutputTokens: 100, - totalTokens: 2_500 - }) - }) -}) diff --git a/src/main/muse-usage/scanner.test.ts b/src/main/muse-usage/scanner.test.ts deleted file mode 100644 index 34d8768b175..00000000000 --- a/src/main/muse-usage/scanner.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { appendFile, realpath } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -vi.mock('electron', () => ({ app: { getPath: vi.fn(() => tmpdir()) } })) - -import { parseMuseUsageLine, type MuseUsageParseContext } from './muse-usage-record-parser' -import { normalizeMuseUsagePersistedFiles } from './persisted-file-normalization' -import { scanMuseUsageFiles } from './scanner' - -const MICROS = 1_790_052_419_142_353 - -function envelope( - payloadType: string, - payload: Record, - recordedAt = MICROS -): Record { - return { - schema_version: 1, - id: `record-${recordedAt}`, - stream: { kind: 'session', id: 'session-placeholder' }, - sequence: 1, - recorded_at: recordedAt, - record_type: 'event', - durability: 'durable', - causation_id: null, - payload_type: payloadType, - payload_schema_version: 1, - payload - } -} - -function metadata(workspaceRoot: string): Record { - return envelope('runtime.session.metadata', { - kind: 'metadata', - record: { workspace_root: workspaceRoot, provider_id: 'meta', build: 'x' } - }) -} - -function modelCompleted( - recordedAt: number, - usage: Record, - model?: string -): Record { - return envelope( - 'runtime.session', - { - kind: 'run', - run_id: 'run-placeholder', - event: { - kind: 'model_completed', - usage: { - cached_tokens: 0, - cache_write_tokens: 0, - cache_read_tokens: 0, - reasoning_tokens: 0, - ...usage - }, - duration_ms: 2636, - ...(model ? { model } : {}) - } - }, - recordedAt - ) -} - -function retainedFrame(children: Record[]): Record { - return { - retained_frame: true, - children: children.map((child) => ({ record_json: JSON.stringify(child) })) - } -} - -function toJsonl(records: Record[]): string { - return `${records.map((entry) => JSON.stringify(entry)).join('\n')}\n` -} - -describe('parseMuseUsageLine', () => { - it('unwraps retained_frame batches and prefers the event model', () => { - const context: MuseUsageParseContext = { sessionId: 's1', cwd: null, currentModel: 'default' } - const events = parseMuseUsageLine( - JSON.stringify( - retainedFrame([ - modelCompleted(MICROS, { input_tokens: 10, output_tokens: 5 }, 'muse-spark-1.3'), - modelCompleted(MICROS + 1, { input_tokens: 20, output_tokens: 5 }) - ]) - ), - context - ) - expect(events.map((event) => [event.model, event.totalTokens])).toEqual([ - ['muse-spark-1.3', 15], - ['default', 25] - ]) - }) -}) - -describe('scanMuseUsageFiles', () => { - let root: string - let sessionsDir: string - let worktreePath: string - - beforeEach(async () => { - root = await realpath(mkdtempSync(join(tmpdir(), 'muse-usage-'))) - sessionsDir = join(root, 'sessions') - worktreePath = join(root, 'repo') - mkdirSync(worktreePath, { recursive: true }) - }) - - afterEach(() => { - rmSync(root, { recursive: true, force: true }) - }) - - function writeSession( - day: string, - sessionId: string, - records: Record[] - ): string { - const dir = join(sessionsDir, ...day.split('-'), sessionId) - mkdirSync(dir, { recursive: true }) - const file = join(dir, 'session.jsonl') - writeFileSync(file, toJsonl(records)) - return file - } - - const worktrees = (): { - repoId: string - worktreeId: string - path: string - displayName: string - }[] => [{ repoId: 'repo-1', worktreeId: 'wt-1', path: worktreePath, displayName: 'repo/main' }] - - it('rereads a log whose cached record lost its sessions instead of reporting zero usage', async () => { - writeSession('2026-09-22', 'a', [ - metadata(worktreePath), - modelCompleted(MICROS, { input_tokens: 100, output_tokens: 10 }, 'm') - ]) - const first = await scanMuseUsageFiles(worktrees(), [], undefined, sessionsDir) - const damaged = first.processedFiles.map((file) => ({ ...file })) - for (const file of damaged) { - Reflect.deleteProperty(file, 'sessions') - } - - const second = await scanMuseUsageFiles( - worktrees(), - normalizeMuseUsagePersistedFiles(damaged), - undefined, - sessionsDir - ) - expect(second.sessions.reduce((sum, session) => sum + session.totalTokens, 0)).toBe(110) - }) - - it('counts a usage record copied into another session log once', async () => { - const shared = modelCompleted(MICROS, { input_tokens: 100, output_tokens: 10 }, 'm') - writeSession('2026-09-22', 'a-parent', [metadata(worktreePath), shared]) - const fork = writeSession('2026-09-22', 'b-fork', [ - metadata(worktreePath), - shared, - modelCompleted(MICROS + 9, { input_tokens: 5, output_tokens: 5 }, 'm') - ]) - - const first = await scanMuseUsageFiles(worktrees(), [], undefined, sessionsDir) - expect(first.sessions.reduce((sum, session) => sum + session.totalTokens, 0)).toBe(120) - expect(first.processedFiles.find((file) => file.path === fork)?.hasDeferredClaims).toBe(true) - - rmSync(join(sessionsDir, '2026', '09', '22', 'a-parent'), { recursive: true }) - const second = await scanMuseUsageFiles( - worktrees(), - first.processedFiles, - undefined, - sessionsDir - ) - expect(second.sessions).toHaveLength(1) - expect(second.sessions[0]).toMatchObject({ sessionId: 'b-fork', totalTokens: 120 }) - }) - - it('keeps distinct same-content records in one log and dedupes their copies elsewhere', async () => { - const turn = (): Record => - modelCompleted(MICROS, { input_tokens: 100, output_tokens: 10 }, 'm') - const owner = writeSession('2026-09-22', 'a-parent', [ - metadata(worktreePath), - retainedFrame([turn(), turn()]) - ]) - writeSession('2026-09-22', 'b-fork', [metadata(worktreePath), turn(), turn()]) - - const first = await scanMuseUsageFiles(worktrees(), [], undefined, sessionsDir) - const byId = new Map(first.sessions.map((session) => [session.sessionId, session])) - expect(byId.get('a-parent')).toMatchObject({ eventCount: 2, totalTokens: 220 }) - expect(byId.has('b-fork')).toBe(false) - - const second = await scanMuseUsageFiles( - worktrees(), - first.processedFiles, - undefined, - sessionsDir - ) - expect(second.sessions.reduce((sum, session) => sum + session.totalTokens, 0)).toBe(220) - await appendFile(owner, toJsonl([turn()])) - const third = await scanMuseUsageFiles( - worktrees(), - second.processedFiles, - undefined, - sessionsDir - ) - expect(third.sessions.reduce((sum, session) => sum + session.totalTokens, 0)).toBe(330) - }) -}) diff --git a/src/main/opencode-usage/scanner.test.ts b/src/main/opencode-usage/scanner.test.ts deleted file mode 100644 index 16859e750ca..00000000000 --- a/src/main/opencode-usage/scanner.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { mkdirSync, mkdtempSync, rmSync, statSync, unlinkSync, utimesSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import Database from '../sqlite/sync-database' -import { listOpenCodeDatabases } from './opencode-database-discovery' -import { parseOpenCodeUsageRow } from './opencode-usage-row-parsing' -import { scanOpenCodeUsageDatabases } from './scanner' - -const WORKTREE = '/workspace/repo' - -function createSessionTotalsSchema(db: Database.Database): void { - db.exec(` - CREATE TABLE session ( - id TEXT PRIMARY KEY, - directory TEXT, - title TEXT, - model TEXT, - cost REAL, - tokens_input INTEGER, - tokens_output INTEGER, - tokens_reasoning INTEGER, - tokens_cache_read INTEGER, - tokens_cache_write INTEGER, - time_created INTEGER, - time_updated INTEGER - ); - `) -} - -function insertSessionTotalsRow( - db: Database.Database, - sessionId: string, - inputTokens: number -): void { - db.prepare( - `INSERT INTO session ( - id, directory, title, model, cost, - tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write, - time_created, time_updated - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` - ).run( - sessionId, - `${WORKTREE}/packages/app`, - 'Session', - JSON.stringify({ providerID: 'anthropic', id: 'claude-sonnet-4-5' }), - 0.01, - inputTokens, - 100, - 0, - 0, - 0, - 1_777_777_700_000, - 1_777_777_800_000 - ) -} - -describe('parseOpenCodeUsageRow', () => { - it.each([ - [undefined, 10_125], - [125, 10_125], - [10_125, 10_125], - [20_000, 20_000] - ])('counts cache reads once with reported total %s', (total, expectedTotal) => { - const parsed = parseOpenCodeUsageRow({ - id: 'message-cache-heavy', - session_id: 'session-cache-heavy', - time_created: 1_777_777_700_000, - time_updated: null, - directory: WORKTREE, - title: null, - worktree: null, - session_model: null, - data: JSON.stringify({ - modelID: 'deepseek-v4.1-flash', - providerID: 'opencode-go', - tokens: { - input: 100, - output: 20, - reasoning: 5, - total, - cache: { read: 10_000, write: 0 } - }, - time: { completed: 1_777_777_800_000 } - }) - }) - - expect(parsed).toMatchObject({ - inputTokens: 10_100, - cachedInputTokens: 10_000, - outputTokens: 20, - reasoningOutputTokens: 5, - totalTokens: expectedTotal - }) - }) -}) - -describe('scanOpenCodeUsageDatabases', () => { - let dataRoot: string - let openCodeDir: string - let previousXdgDataHome: string | undefined - let previousOpenCodeDb: string | undefined - - beforeEach(() => { - dataRoot = mkdtempSync(join(tmpdir(), 'orca-opencode-usage-scan-')) - openCodeDir = join(dataRoot, 'opencode') - mkdirSync(openCodeDir, { recursive: true }) - previousXdgDataHome = process.env.XDG_DATA_HOME - previousOpenCodeDb = process.env.OPENCODE_DB - process.env.XDG_DATA_HOME = dataRoot - delete process.env.OPENCODE_DB - }) - - afterEach(() => { - if (previousXdgDataHome === undefined) { - delete process.env.XDG_DATA_HOME - } else { - process.env.XDG_DATA_HOME = previousXdgDataHome - } - if (previousOpenCodeDb === undefined) { - delete process.env.OPENCODE_DB - } else { - process.env.OPENCODE_DB = previousOpenCodeDb - } - rmSync(dataRoot, { recursive: true, force: true }) - }) - - function writeSessionTotalsDb(fileName: string, rows: [string, number][]): string { - const path = join(openCodeDir, fileName) - const db = new Database(path) - createSessionTotalsSchema(db) - for (const [sessionId, inputTokens] of rows) { - insertSessionTotalsRow(db, sessionId, inputTokens) - } - db.close() - return path - } - - function appendLiveSessionRow(path: string, sessionId: string, inputTokens: number): void { - const previousMtimeMs = statSync(path).mtimeMs - const db = new Database(path) - insertSessionTotalsRow(db, sessionId, inputTokens) - db.close() - // A same-page write may retain coarse mtime; force the scanner’s mtime/size fingerprint to change. - const changedAt = new Date(previousMtimeMs + 1000) - utimesSync(path, changedAt, changedAt) - } - - it('does not scan disk databases when OPENCODE_DB uses memory', async () => { - writeSessionTotalsDb('opencode.db', []) - process.env.OPENCODE_DB = ':memory:' - - await expect(listOpenCodeDatabases()).resolves.toEqual([]) - }) - - it('does not return a directory configured as OPENCODE_DB', async () => { - process.env.OPENCODE_DB = '.' - - await expect(listOpenCodeDatabases()).resolves.toEqual([]) - }) - - it('counts a session duplicated into a stale backup database exactly once', async () => { - writeSessionTotalsDb('opencode.db', [ - ['session-1', 1000], - ['session-2', 300] - ]) - writeSessionTotalsDb('opencode-backup.db', [['session-1', 400]]) - - const result = await scanOpenCodeUsageDatabases([], []) - - expect(result.sessions).toHaveLength(2) - const sessionOne = result.sessions.find((session) => session.sessionId === 'session-1') - expect(sessionOne?.totalInputTokens).toBe(1000) - expect(sessionOne?.eventCount).toBe(1) - expect( - result.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(1300) - }) - - it('still counts backup-only sessions and stays stable across cached rescans', async () => { - const canonicalPath = writeSessionTotalsDb('opencode.db', [['session-1', 1000]]) - writeSessionTotalsDb('opencode-backup.db', [ - ['session-1', 400], - ['session-9', 50] - ]) - - const first = await scanOpenCodeUsageDatabases([], []) - expect( - first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(1050) - - const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) - expect( - second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(1050) - - appendLiveSessionRow(canonicalPath, 'session-2', 200) - - const third = await scanOpenCodeUsageDatabases([], second.processedDatabases) - expect( - third.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(1250) - const sessionOne = third.sessions.find((session) => session.sessionId === 'session-1') - expect(sessionOne?.totalInputTokens).toBe(1000) - expect(sessionOne?.eventCount).toBe(1) - }) - - it('reclaims sessions when the owning live database is deleted', async () => { - const canonicalPath = writeSessionTotalsDb('opencode.db', [ - ['session-1', 1000], - ['session-2', 200] - ]) - writeSessionTotalsDb('opencode-backup.db', [ - ['session-1', 400], - ['session-9', 50] - ]) - - const first = await scanOpenCodeUsageDatabases([], []) - expect( - first.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(1250) - - unlinkSync(canonicalPath) - - const second = await scanOpenCodeUsageDatabases([], first.processedDatabases) - expect( - second.dailyAggregates.reduce((total, aggregate) => total + aggregate.inputTokens, 0) - ).toBe(450) - expect(second.sessions.map((session) => session.sessionId).sort()).toEqual([ - 'session-1', - 'session-9' - ]) - const sessionOne = second.sessions.find((session) => session.sessionId === 'session-1') - expect(sessionOne?.totalInputTokens).toBe(400) - }) -}) diff --git a/src/main/plugins/catalog/plugin-install-stats-service.test.ts b/src/main/plugins/catalog/plugin-install-stats-service.test.ts deleted file mode 100644 index 5a5603b622b..00000000000 --- a/src/main/plugins/catalog/plugin-install-stats-service.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' - -import { - PLUGIN_INSTALL_STATS_REFRESH_MS, - PluginInstallStatsService -} from './plugin-install-stats-service' - -const roots: string[] = [] - -async function tempRoot(): Promise { - const root = await mkdtemp(join(tmpdir(), 'orca-plugin-install-stats-')) - roots.push(root) - return root -} - -const NOW = Date.parse('2026-10-30T12:00:00Z') - -function stats(installs: number, generatedAt = '2026-10-30T02:00:00Z') { - return { generatedAt, installs: { 'stablyai.orca-nord-theme': installs } } -} - -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -describe('PluginInstallStatsService', () => { - it('serves a fresh disk cache after restart without refetching', async () => { - const root = await tempRoot() - const first = new PluginInstallStatsService({ - pluginsDataDir: root, - isFetchAllowed: () => true, - fetcher: async () => stats(50), - now: () => NOW - }) - await first.getInstallCounts() - await first.settled() - await utimes(join(root, 'plugin-install-stats.json'), NOW / 1000, NOW / 1000) - - const fetcher = vi.fn(async () => stats(60)) - const restarted = new PluginInstallStatsService({ - pluginsDataDir: root, - isFetchAllowed: () => true, - fetcher, - now: () => NOW - }) - expect(await restarted.getInstallCounts()).toEqual({ 'stablyai.orca-nord-theme': 50 }) - expect(fetcher).not.toHaveBeenCalled() - }) - - it('ignores a corrupt cache and an older snapshot', async () => { - const root = await tempRoot() - await writeFile(join(root, 'plugin-install-stats.json'), '{not json') - const warning = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - let now = NOW - const fetcher = vi - .fn<() => Promise>>() - .mockResolvedValueOnce(stats(20, '2026-10-30T02:00:00Z')) - .mockResolvedValueOnce(stats(5, '2026-10-29T02:00:00Z')) - const service = new PluginInstallStatsService({ - pluginsDataDir: root, - isFetchAllowed: () => true, - fetcher, - now: () => now - }) - expect(await service.getInstallCounts()).toEqual({}) - await service.settled() - now += PLUGIN_INSTALL_STATS_REFRESH_MS - await service.getInstallCounts() - await service.settled() - expect(await service.getInstallCounts()).toEqual({ 'stablyai.orca-nord-theme': 20 }) - warning.mockRestore() - }) -}) diff --git a/src/main/plugins/contributions/plugin-theme-registries.test.ts b/src/main/plugins/contributions/plugin-theme-registries.test.ts deleted file mode 100644 index c8671854b11..00000000000 --- a/src/main/plugins/contributions/plugin-theme-registries.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, describe, expect, it } from 'vitest' -import { fingerprintPluginConsent } from '../../../shared/plugins/approval/plugin-consent-fingerprint' -import { pluginManifestSchema } from '../../../shared/plugins/manifest/plugin-manifest' -import { PluginContentVerifier } from '../artifacts/plugin-content-integrity' -import type { ValidDiscoveredPlugin } from '../discovery/plugin-discovery' -import { - createPluginTerminalThemeRegistry, - createPluginThemeRegistry -} from './plugin-theme-registries' - -const roots: string[] = [] -afterEach(async () => { - await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) -}) - -async function themePlugin(files: { app?: unknown; terminal?: unknown }) { - const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-theme-registry-')) - roots.push(rootDir) - await writeFile(join(rootDir, 'app.json'), JSON.stringify(files.app ?? {})) - await writeFile(join(rootDir, 'terminal.json'), JSON.stringify(files.terminal ?? {})) - const manifest = pluginManifestSchema.parse({ - manifestVersion: 1, - id: 'midnight', - publisher: 'samples', - name: 'Midnight', - version: '1.0.0', - engines: { orca: '>=1.0.0' }, - pluginApi: 1, - contributes: { - themes: [{ id: 'midnight', title: 'Midnight', path: 'app.json' }], - terminalThemes: [{ id: 'midnight', title: 'Midnight', path: 'terminal.json' }] - } - }) - const plugin: ValidDiscoveredPlugin = { - pluginKey: 'samples.midnight', - rootDir, - manifest, - consentFingerprint: fingerprintPluginConsent(manifest), - contentHash: null, - isDev: true - } - return plugin -} - -const terminal = { - schemaVersion: 1, - mode: 'dark', - terminal: { background: '#000000', foreground: '#ffffff', red: '#ff0000' } -} - -describe('plugin theme registries', () => { - it('loads app and terminal themes under host-owned ids', async () => { - const plugin = await themePlugin({ - app: { base: 'dark', tokens: { '--background': '#101010', '--foreground': '#f0f0f0' } }, - terminal - }) - const themes = createPluginThemeRegistry(new PluginContentVerifier()) - const terminalThemes = createPluginTerminalThemeRegistry(new PluginContentVerifier()) - - await themes.reconcile([plugin], () => true) - await terminalThemes.reconcile([plugin], () => true) - - expect(themes.list()).toEqual([ - expect.objectContaining({ - id: 'plugin:samples.midnight/midnight', - pluginKey: 'samples.midnight', - pluginName: 'Midnight', - label: 'Midnight', - base: 'dark', - tokens: expect.objectContaining({ '--background': '#101010', '--card': '#101010' }) - }) - ]) - expect(terminalThemes.list()).toEqual([ - expect.objectContaining({ id: 'plugin:samples.midnight/midnight', mode: 'dark' }) - ]) - }) -}) diff --git a/src/main/telemetry/client-prompt-sampling.test.ts b/src/main/telemetry/client-prompt-sampling.test.ts index 8da878fa8c0..4b54aff290f 100644 --- a/src/main/telemetry/client-prompt-sampling.test.ts +++ b/src/main/telemetry/client-prompt-sampling.test.ts @@ -33,24 +33,6 @@ describe('prompt event sampling', () => { vi.useRealTimers() }) - it('retains 1% of prompts without spending the shared budget on discarded events', () => { - let draw = 0 - vi.spyOn(Math, 'random').mockImplementation(() => ((draw++ % 100) + 0.5) / 100) - const settingsReads = vi.mocked(state.store.getSettings).mock.calls.length - - for (let index = 0; index < 1_000; index++) { - vi.advanceTimersByTime(1_000) - track('agent_prompt_sent', prompt) - } - - expect(state.mock.capture).toHaveBeenCalledTimes(10) - expect(state.store.getSettings).toHaveBeenCalledTimes(settingsReads + 10) - expect(track('app_opened', {})).toBe(true) - for (const [message] of state.mock.capture.mock.calls.slice(0, 10)) { - expect(message.properties).toMatchObject({ ...prompt, sample_rate: 0.01 }) - } - }) - it('uses the same sampling boundary for hooks and renderer prompt sources', () => { const random = vi.spyOn(Math, 'random') for (const launch_source of ['unknown', 'sidebar', 'diff_notes_send'] as const) { @@ -67,17 +49,6 @@ describe('prompt event sampling', () => { } }) - it('does not sample workflow starts or failures', () => { - vi.spyOn(Math, 'random').mockReturnValue(0.99) - expect(track('agent_prompt_sent', prompt)).toBe(false) - expect(track('agent_started', prompt)).toBe(true) - expect(track('agent_error', { agent_kind: 'codex', error_class: 'unknown' })).toBe(true) - expect(state.mock.capture).toHaveBeenCalledTimes(2) - for (const [message] of state.mock.capture.mock.calls) { - expect(message.properties).not.toHaveProperty('sample_rate') - } - }) - it('still enforces consent and rejects raw prompt text on selected events', () => { vi.spyOn(Math, 'random').mockReturnValue(0) state.settings.telemetry!.optedIn = false diff --git a/src/main/telemetry/plugin-install-telemetry.test.ts b/src/main/telemetry/plugin-install-telemetry.test.ts index 2f45bdb6ccb..2e5eaeecc0f 100644 --- a/src/main/telemetry/plugin-install-telemetry.test.ts +++ b/src/main/telemetry/plugin-install-telemetry.test.ts @@ -1,10 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import { eventSchemas } from '../../shared/telemetry/telemetry-event-registry' -import { - pluginInstallKind, - pluginTelemetryCatalog, - trackPluginInstalled -} from './plugin-install-telemetry' +import { pluginTelemetryCatalog, trackPluginInstalled } from './plugin-install-telemetry' const telemetry = vi.hoisted(() => ({ track: vi.fn() })) vi.mock('./client', () => telemetry) @@ -26,12 +22,6 @@ describe('plugin install telemetry', () => { ).toBeNull() }) - it('tells a first install from a reinstall and an update', () => { - expect(pluginInstallKind(null, '1.0.0')).toBe('install') - expect(pluginInstallKind('1.0.0', '1.0.0')).toBe('reinstall') - expect(pluginInstallKind('1.0.0', '1.1.0')).toBe('update') - }) - it('sends nothing for a private catalog install', () => { trackPluginInstalled({ marketplaceUrl: 'https://github.com/acme/private-plugins.git', diff --git a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx b/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx deleted file mode 100644 index 20bb94a4204..00000000000 --- a/src/renderer/src/components/agent/AgentLaunchPickerMenu.search.test.tsx +++ /dev/null @@ -1,205 +0,0 @@ -// @vitest-environment happy-dom -import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { afterEach, expect, it, vi } from 'vitest' -import { useState, type ComponentProps } from 'react' -import userEvent from '@testing-library/user-event' -import type * as LaunchSetup from './AgentLaunchSetupButton' -import type { AgentLaunchSetupButton } from './AgentLaunchSetupButton' -import { AgentLaunchPickerMenu } from './AgentLaunchPickerMenu' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, - DropdownMenuSub, - DropdownMenuSubTrigger -} from '@/components/ui/dropdown-menu' -import type { AgentPickerEntry } from '../../../../shared/agent-launch/picker/agent-launch-picker' - -vi.mock('@/hooks/useShortcutLabel', () => ({ useOptionalShortcutLabel: () => null })) -vi.mock('./AgentLaunchSetupButton', async (importOriginal) => ({ - ...(await importOriginal()), - AgentLaunchSetupButton: vi.fn((props: ComponentProps) => ( - - - {props.renderAnchor?.()} - - - )) -})) -afterEach(() => { - cleanup() - vi.clearAllMocks() -}) - -it('includes blank terminal in keyboard results and filters it for agent and model searches', async () => { - const entry: AgentPickerEntry = { - agent: 'codex', - label: 'Codex', - rows: [{ agent: 'codex', kind: 'cli' }], - surfaces: ['terminal'], - defaultSurface: 'terminal', - terminal: {}, - structured: {}, - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [{ id: 'astra', label: 'Astra', isDefault: true, efforts: [] }] - } - } - const antigravity: AgentPickerEntry = { - ...entry, - agent: 'antigravity', - label: 'Antigravity', - rows: [{ agent: 'antigravity', kind: 'cli' }], - catalog: { origin: 'probe', fetchedAt: 1, models: [] } - } - function Picker({ showLeadingItem = false }: { showLeadingItem?: boolean }) { - const [selection, setSelection] = useState('') - return ( - <> - {selection} - - Open - - Custom command : undefined - } - onSelectBlankTerminal={() => setSelection('blank')} - runLaunch={(row, draft) => { - setSelection(`${row.agent}:${draft?.choices.model ?? ''}`) - }} - /> - - - - ) - } - const view = render() - const user = userEvent.setup() - const input = screen.getByRole('textbox') - await user.click(input) - await user.keyboard('{ArrowDown}') - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Blank Terminal' })) - await user.click(input) - await user.type(input, 'shell{Enter}') - expect(screen.getByLabelText('Selection').textContent).toBe('blank') - - view.rerender() - await user.click(screen.getByRole('button', { name: 'Open' })) - await user.keyboard('{ArrowDown}') - expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Custom command' })) - await user.type(screen.getByRole('textbox'), 'codex') - expect(screen.queryByRole('menuitem', { name: 'Blank Terminal' })).toBeNull() - await user.keyboard('{Enter}') - expect(screen.getByLabelText('Selection').textContent).toBe('codex:') - - await user.click(screen.getByRole('button', { name: 'Open' })) - await user.type(screen.getByRole('textbox'), 'anti') - expect(screen.queryByRole('menuitem', { name: 'Blank Terminal' })).toBeNull() - await user.keyboard('{Enter}') - expect(screen.getByLabelText('Selection').textContent).toBe('antigravity:') - - await user.click(screen.getByRole('button', { name: 'Open' })) - await user.type(screen.getByRole('textbox'), 'astra{Enter}') - expect(screen.getByLabelText('Selection').textContent).toBe('codex:astra') -}) - -it('lists an agent named by the query before other agents’ model setups', () => { - const codex: AgentPickerEntry = { - agent: 'codex', - label: 'Codex', - rows: [{ agent: 'codex', kind: 'cli' }], - surfaces: ['terminal'], - defaultSurface: 'terminal', - terminal: {}, - structured: {}, - catalog: { origin: 'probe', fetchedAt: 1, models: [] } - } - const opencode: AgentPickerEntry = { - ...codex, - agent: 'opencode', - label: 'OpenCode', - rows: [{ agent: 'opencode', kind: 'cli' }], - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [{ id: 'gpt-5-codex', label: 'GPT-5 Codex', isDefault: false, efforts: [] }] - } - } - const launch = vi.fn() - render( - - Open - - - - - ) - fireEvent.focus(screen.getByRole('textbox')) - fireEvent.change(screen.getByRole('textbox'), { target: { value: 'codex' } }) - const items = screen.getAllByRole('menuitem').map((item) => item.textContent) - expect(items[0]).toContain('Codex') - expect(items[0]).not.toContain('OpenCode') - expect(items.some((text) => text?.includes('OpenCode · GPT-5 Codex'))).toBe(true) - const highlighted = document.querySelectorAll('[data-search-default]') - expect(highlighted).toHaveLength(1) - expect(highlighted[0].textContent).toContain('Codex') - expect(highlighted[0].textContent).not.toContain('OpenCode') - fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' }) - expect(launch).toHaveBeenCalledWith({ agent: 'codex', kind: 'cli' }, undefined) -}) - -it('matches Antigravity and its model setups via the AGY acronym', async () => { - const codex: AgentPickerEntry = { - agent: 'codex', - label: 'Codex', - rows: [{ agent: 'codex', kind: 'cli' }], - surfaces: ['terminal'], - defaultSurface: 'terminal', - terminal: {}, - structured: {}, - catalog: { origin: 'probe', fetchedAt: 1, models: [] } - } - const antigravity: AgentPickerEntry = { - ...codex, - agent: 'antigravity', - label: 'Antigravity', - rows: [{ agent: 'antigravity', kind: 'cli' }], - catalog: { - origin: 'probe', - fetchedAt: 1, - models: [{ id: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro', isDefault: false, efforts: [] }] - } - } - const launch = vi.fn() - const user = userEvent.setup() - render( - - Open - - - - - ) - await user.type(screen.getByRole('textbox'), 'AGY') - expect(screen.getAllByRole('menuitem').map((item) => item.textContent)).toEqual([ - expect.stringContaining('Antigravity') - ]) - await user.keyboard('{Enter}') - expect(launch).toHaveBeenCalledWith({ agent: 'antigravity', kind: 'cli' }, undefined) - - launch.mockClear() - await user.click(screen.getByRole('button', { name: 'Open' })) - await user.type(screen.getByRole('textbox'), 'AGY Gemini{Enter}') - expect(launch).toHaveBeenCalledWith( - { agent: 'antigravity', kind: 'cli', executionHostId: undefined }, - expect.objectContaining({ - agent: 'antigravity', - choices: { model: 'gemini-2.5-pro' } - }), - antigravity - ) -}) diff --git a/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx b/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx deleted file mode 100644 index bf49a411f19..00000000000 --- a/src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx +++ /dev/null @@ -1,266 +0,0 @@ -// @vitest-environment happy-dom - -import type React from 'react' -import { cleanup, fireEvent, render } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { Repo } from '../../../../../shared/repository/repo-types' -import type { - WorkspaceLineage, - WorktreeLineage -} from '../../../../../shared/worktree/lineage-types' -import type { Worktree } from '../../../../../shared/worktree/types' -import { - folderWorkspaceKey, - worktreeWorkspaceKey -} from '../../../../../shared/workspace/identity/workspace-scope' - -type FakeStoreState = { - worktreesByRepo: Record - repos: Repo[] - projectHostSetups: never[] - worktreeLineageById: Record - workspaceLineageByChildKey: Record -} - -const storeState = vi.hoisted( - () => - ({ - worktreesByRepo: {}, - repos: [], - projectHostSetups: [], - worktreeLineageById: {}, - workspaceLineageByChildKey: {} - }) as FakeStoreState -) - -vi.mock('@/i18n/i18n', () => ({ - translate: (_key: string, fallback: string) => fallback -})) - -vi.mock('react-i18next', () => ({ - useTranslation: () => ({ t: (_key: string, fallback: string) => fallback }) -})) - -vi.mock('@/store', () => ({ - useAppStore: (selector: (state: FakeStoreState) => unknown) => selector(storeState) -})) - -vi.mock('@/components/ui/popover', async () => { - const { cloneElement, createContext, useContext, useMemo } = await import('react') - const PopoverState = createContext<{ open: boolean; onOpenChange?: (open: boolean) => void }>({ - open: false - }) - return { - Popover: ({ - children, - open = false, - onOpenChange - }: { - children: React.ReactNode - open?: boolean - onOpenChange?: (open: boolean) => void - }) => { - const value = useMemo(() => ({ open, onOpenChange }), [open, onOpenChange]) - return {children} - }, - // Radix `asChild` renders the child itself and owns its click; mirror that. - PopoverTrigger: ({ children }: { children: React.ReactElement }) => { - const { open, onOpenChange } = useContext(PopoverState) - return cloneElement(children as React.ReactElement<{ onClick?: () => void }>, { - onClick: () => onOpenChange?.(!open) - }) - }, - // Radix mounts content only while open — the property the lazy list relies on. - PopoverContent: ({ children }: { children: React.ReactNode }) => - useContext(PopoverState).open ?
{children}
: null - } -}) - -// The virtual window needs real layout the test DOM has none of; render every row. -vi.mock('@tanstack/react-virtual', () => ({ - useVirtualizer: ({ count }: { count: number }) => ({ - getTotalSize: () => count * 44, - getVirtualItems: () => - Array.from({ length: count }, (_, index) => ({ - index, - key: index, - start: index * 44, - size: 44 - })), - scrollToIndex: vi.fn(), - scrollToOffset: vi.fn() - }) -})) - -const { ComposerParentWorktreePicker } = await import('./ComposerParentWorktreePicker') - -const REPO_ID = 'repo1' - -function makeRepo(id: string): Repo { - return { - id, - path: `/src/${id}`, - displayName: id, - badgeColor: '#111111', - addedAt: 0 - } as Repo -} - -function makeWorktree(overrides: Partial & { id: string }): Worktree { - return { - repoId: REPO_ID, - path: `/work/${overrides.id}`, - head: 'abc123', - branch: 'refs/heads/feature', - isBare: false, - isMainWorktree: false, - displayName: overrides.id, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - ...overrides - } -} - -function seed(worktrees: Worktree[], repoIds: string[] = [REPO_ID]): void { - const byRepo: Record = {} - for (const worktree of worktrees) { - byRepo[worktree.repoId] = [...(byRepo[worktree.repoId] ?? []), worktree] - } - storeState.worktreesByRepo = byRepo - storeState.repos = repoIds.map(makeRepo) -} - -function trigger(): HTMLButtonElement { - const node = document.querySelector('button[role="combobox"]') - if (!node) { - throw new Error('parent picker trigger not found') - } - return node -} - -function rows(): HTMLElement[] { - return Array.from(document.querySelectorAll('[role="option"]')) -} - -function candidateLabels(): string[] { - return rows() - .slice(1) - .map((row) => row.textContent ?? '') -} - -beforeEach(() => { - storeState.worktreesByRepo = {} - storeState.repos = [] - storeState.worktreeLineageById = {} - storeState.workspaceLineageByChildKey = {} -}) - -afterEach(cleanup) - -describe('ComposerParentWorktreePicker', () => { - it('offers live folder descendants through retired roots and intermediate parents', () => { - const attached = makeWorktree({ - id: 'attached', - displayName: 'Attached', - instanceId: 'attached-instance', - removing: true, - removalRecorded: true - }) - const nested = makeWorktree({ - id: 'nested', - displayName: 'Nested', - instanceId: 'nested-instance' - }) - const bridge = makeWorktree({ - id: 'bridge', - instanceId: 'bridge-instance', - removing: true, - removalRecorded: true - }) - const leaf = makeWorktree({ id: 'leaf', displayName: 'Leaf', instanceId: 'leaf-instance' }) - const outside = makeWorktree({ id: 'outside', displayName: 'Outside' }) - seed([attached, nested, bridge, leaf, outside]) - storeState.workspaceLineageByChildKey = { - [worktreeWorkspaceKey(attached.id)]: { - childWorkspaceKey: worktreeWorkspaceKey(attached.id), - childInstanceId: attached.instanceId ?? null, - parentWorkspaceKey: folderWorkspaceKey('folder-1'), - parentInstanceId: null, - origin: 'manual', - capture: { source: 'active-workspace', confidence: 'explicit' }, - createdAt: 1 - } - } - storeState.worktreeLineageById = { - [nested.id]: { - worktreeId: nested.id, - worktreeInstanceId: 'nested-instance', - parentWorktreeId: attached.id, - parentWorktreeInstanceId: 'attached-instance', - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 2 - }, - [bridge.id]: { - worktreeId: bridge.id, - worktreeInstanceId: 'bridge-instance', - parentWorktreeId: nested.id, - parentWorktreeInstanceId: 'nested-instance', - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 3 - }, - [leaf.id]: { - worktreeId: leaf.id, - worktreeInstanceId: 'leaf-instance', - parentWorktreeId: bridge.id, - parentWorktreeInstanceId: 'bridge-instance', - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 4 - } - } - const onChange = vi.fn() - render( - - ) - fireEvent.click(trigger()) - - const labels = candidateLabels().join(' ') - expect(labels).not.toContain('Attached') - expect(labels).not.toContain('bridge') - expect(labels).toContain('Nested') - expect(labels).toContain('Leaf') - expect(labels).not.toContain('Outside') - fireEvent.click(rows().find((row) => row.textContent?.includes('Leaf'))!) - expect(onChange).toHaveBeenCalledWith('leaf') - }) - - it('closes an open popover when the drawer collapses the trigger', () => { - seed([makeWorktree({ id: 'alpha', displayName: 'Alpha' })]) - - const view = render( - - ) - fireEvent.click(trigger()) - expect(rows().length).toBeGreaterThan(0) - - view.rerender( - - ) - - expect(rows()).toHaveLength(0) - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-git-history.test.tsx b/src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-git-history.test.tsx index 6af1cc33cce..c8db808f895 100644 --- a/src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-git-history.test.tsx +++ b/src/renderer/src/components/right-sidebar/source-control/sync/use-source-control-git-history.test.tsx @@ -83,19 +83,6 @@ afterEach(() => { latest = null }) -describe('useSourceControlGitHistory branch switch', () => { - it('reloads the open list when the same workspace switches branches', async () => { - const root = await mount({ branchName: 'main' }) - await flush() - await act(async () => { - root.render() - }) - await flush() - - expect(mocks.getRuntimeGitHistory).toHaveBeenCalledTimes(2) - }) -}) - describe('useSourceControlGitHistory stale completion', () => { it('drops a stale response for a worktree the user already left and returned to', async () => { const firstA = deferred() @@ -183,38 +170,6 @@ describe('useSourceControlGitHistory stale completion', () => { expect(latest?.gitHistoryState).toEqual({ status: 'ready', result: historyResult('current-a') }) }) - it('keeps the previous result while refreshing and reports errors alongside it', async () => { - const first = deferred() - const second = deferred() - mocks.getRuntimeGitHistory - .mockReturnValueOnce(first.promise) - .mockReturnValueOnce(second.promise) - - await mount() - expect(latest?.gitHistoryState).toEqual({ status: 'loading' }) - await act(async () => { - first.resolve(historyResult('from-a')) - }) - await flush() - - void latest?.refreshGitHistory() - await flush() - expect(latest?.gitHistoryState).toEqual({ - status: 'refreshing', - result: historyResult('from-a') - }) - - await act(async () => { - second.reject(new Error('git log failed')) - }) - await flush() - expect(latest?.gitHistoryState).toEqual({ - status: 'error', - result: historyResult('from-a'), - error: 'git log failed' - }) - }) - it('prunes history for worktrees that disappear and blocks their in-flight response', async () => { const a = deferred() mocks.getRuntimeGitHistory.mockReturnValueOnce(a.promise) diff --git a/src/renderer/src/components/tab-group/SplitPaneLanding.test.tsx b/src/renderer/src/components/tab-group/SplitPaneLanding.test.tsx deleted file mode 100644 index e686d80bb3f..00000000000 --- a/src/renderer/src/components/tab-group/SplitPaneLanding.test.tsx +++ /dev/null @@ -1,282 +0,0 @@ -// @vitest-environment happy-dom -import { act } from 'react' -import { fireEvent, screen, waitFor } from '@testing-library/react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store' - -type AgentModel = - | { state: 'loading'; placeholderCount: number } - | { state: 'settled'; rows: { kind: 'terminal'; agent: 'codex' }[] } - -// Why: agent rows and files arrive from subscriptions in the app, so the fakes push updates the same way. -const mocks = vi.hoisted(() => { - const listeners = new Set<() => void>() - const data: { agentModel: AgentModel; files: string[] } = { - agentModel: { state: 'loading', placeholderCount: 0 }, - files: [] - } - return { - data, - publish(next: Partial): void { - Object.assign(data, next) - listeners.forEach((listener) => listener()) - }, - subscribe(listener: () => void): () => void { - listeners.add(listener) - return () => listeners.delete(listener) - }, - launchDefault: vi.fn(), - launchRow: vi.fn() - } -}) - -vi.mock('@/store/workspaces/selection/use-selected-worktree', () => ({ - useFileListWorktree: () => ({ path: '/repo' }) -})) -vi.mock('@/components/quick-open-file-list', async () => { - const { useSyncExternalStore } = await import('react') - return { - useRuntimeFileListForWorktree: () => ({ - files: useSyncExternalStore(mocks.subscribe, () => mocks.data.files), - loading: false, - loadError: null - }) - } -}) -vi.mock('@/hooks/useAgentDetectionTarget', async (importOriginal) => ({ - ...(await importOriginal>()), - useAgentDetectionTargetForWorktree: () => undefined -})) -vi.mock('../tab-bar/use-new-tab-agent-menu-rows', async () => { - const { useSyncExternalStore } = await import('react') - return { - useNewTabAgentMenuRows: () => useSyncExternalStore(mocks.subscribe, () => mocks.data.agentModel) - } -}) -vi.mock('../tab-bar/QuickLaunchButton', () => ({ - QuickLaunchAgentMenuItems: () =>
Agent list
, - useTabAgentMenuLaunch: () => mocks.launchRow -})) -vi.mock('../agent-tab-shortcut-launch', () => ({ - launchAgentTabShortcut: mocks.launchDefault -})) - -import { SplitPaneLanding } from './SplitPaneLanding' - -let host: HTMLDivElement -let root: Root - -function render(): void { - act(() => - root.render() - ) -} - -function input(): HTMLInputElement { - return document.querySelector('[cmdk-input]')! -} - -function type(value: string): void { - const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set - act(() => { - setter?.call(input(), value) - input().dispatchEvent(new Event('input', { bubbles: true })) - }) -} - -function press(key: string): boolean { - let notPrevented = true - act(() => { - notPrevented = fireEvent.keyDown(document.activeElement ?? input(), { - key - }) - }) - return notPrevented -} - -function highlighted(): string | null { - return ( - document.querySelector('[cmdk-item][data-selected="true"]')?.getAttribute('data-value') ?? null - ) -} - -function picker(): Element | null { - return document.querySelector('[data-testid="agent-picker"]') -} - -beforeEach(() => { - vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true) - mocks.data.agentModel = { state: 'loading', placeholderCount: 0 } - mocks.data.files = [] - useAppStore.setState(useAppStore.getInitialState(), true) - host = document.createElement('div') - document.body.append(host) - root = createRoot(host) -}) - -afterEach(() => { - act(() => root.unmount()) - host.remove() - vi.clearAllMocks() - vi.restoreAllMocks() - vi.unstubAllGlobals() -}) - -describe('SplitPaneLanding placeholder', () => { - it.each([ - [260, 'Search'], - [299, 'Search'], - [300, 'Search agents and files'], - [380, 'Search agents and files'] - ])('a %ipx card shows "%s"', (width, placeholder) => { - vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue( - new DOMRect(0, 0, width, 0) - ) - render() - - expect(input().placeholder).toBe(placeholder) - // The accessible name never shortens with the placeholder. - expect(screen.getByRole('combobox', { name: 'Search agents and files' })).toBe(input()) - }) -}) - -describe('SplitPaneLanding keyboard', () => { - it('opens with the caret in the search field and launches the default agent on Enter', () => { - render() - - expect(document.activeElement).toBe(input()) - expect(highlighted()).toBe('default-agent') - press('Enter') - expect(mocks.launchDefault).toHaveBeenCalledTimes(1) - expect(mocks.launchDefault.mock.calls[0]?.[0]).toBe('wt') - }) - - it('opens the agent picker with → only from the default row with an empty query', async () => { - render() - - press('ArrowDown') - expect(highlighted()).toBe('terminal') - press('ArrowRight') - expect(picker()).toBeNull() - - press('ArrowUp') - type(' ') - expect(highlighted()).toBe('default-agent') - expect(press('ArrowRight')).toBe(true) - expect(picker()).toBeNull() - - type('') - expect(highlighted()).toBe('default-agent') - expect(press('ArrowRight')).toBe(false) - expect(picker()).not.toBeNull() - - press('Escape') - expect(picker()).toBeNull() - await waitFor(() => expect(document.activeElement).toBe(input())) - }) - - it('clears the query on Esc and leaves an empty query alone', () => { - render() - - type('term') - expect(press('Escape')).toBe(false) - expect(input().value).toBe('') - expect(document.activeElement).toBe(input()) - - expect(press('Escape')).toBe(true) - expect(input().value).toBe('') - }) -}) - -describe('SplitPaneLanding late results', () => { - it('highlights rows that arrive above an untouched highlight, so Enter opens them', () => { - mocks.data.files = ['src/codea.ts', 'src/codeb.ts'] - render() - type('co') - press('ArrowDown') - expect(highlighted()).toBe('file:src/codeb.ts') - - type('cod') - expect(highlighted()).toBe('file:src/codea.ts') - - act(() => - mocks.publish({ - agentModel: { - state: 'settled', - rows: [{ kind: 'terminal', agent: 'codex' }] - } - }) - ) - expect(highlighted()).toBe('agent:terminal:codex') - press('Enter') - - expect(mocks.launchRow).toHaveBeenCalledWith({ - kind: 'terminal', - agent: 'codex' - }) - }) - - it.each(['pointer', 'ArrowDown', 'Home', 'End'])( - 'lets late rows lead after %s leaves selection unchanged', - (gesture) => { - mocks.data.files = ['src/codec.ts'] - render() - type('cod') - expect(highlighted()).toBe('file:src/codec.ts') - if (gesture === 'pointer') { - act(() => - fireEvent.pointerMove(document.querySelector('[cmdk-item][data-selected="true"]')!) - ) - } else { - press(gesture) - } - expect(highlighted()).toBe('file:src/codec.ts') - act(() => - mocks.publish({ - agentModel: { state: 'settled', rows: [{ kind: 'terminal', agent: 'codex' }] } - }) - ) - expect(highlighted()).toBe('agent:terminal:codex') - } - ) - - it('keeps a highlight the user moved when results change', () => { - mocks.data.files = ['docs/mark-a.md'] - render() - type('mark') - press('ArrowDown') - expect(highlighted()).toBe('file:docs/mark-a.md') - - act(() => mocks.publish({ files: ['docs/mark-b.md', 'docs/mark-a.md'] })) - - expect(highlighted()).toBe('file:docs/mark-a.md') - }) - - it('moves to the first row when the row the user moved to disappears, then follows late rows again', () => { - mocks.data.files = ['src/codec.ts', 'src/codex-b.ts'] - render() - type('cod') - press('ArrowDown') - expect(highlighted()).toBe('file:src/codex-b.ts') - - act(() => mocks.publish({ files: ['src/codec.ts'] })) - expect(highlighted()).toBe('file:src/codec.ts') - - // The user's pick is gone, so rows that arrive above take the highlight as if it were untouched. - act(() => - mocks.publish({ - agentModel: { - state: 'settled', - rows: [{ kind: 'terminal', agent: 'codex' }] - } - }) - ) - expect(highlighted()).toBe('agent:terminal:codex') - press('Enter') - expect(mocks.launchRow).toHaveBeenCalledWith({ - kind: 'terminal', - agent: 'codex' - }) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts b/src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts deleted file mode 100644 index 7fbc1dcea59..00000000000 --- a/src/renderer/src/components/terminal-pane/links/handles/terminal-handle-links.test.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' -import type { ILink } from '@xterm/xterm' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '@/runtime/rpc/compatibility/runtime-compatibility-cache' -import { - createTerminalHandleLinkProvider, - extractTerminalHandleLinks, - findTerminalHandleTarget -} from './terminal-handle-links' -import { extractOrchestrationTaskLinks } from './terminal-orchestration-task-links' -import type { TerminalLinkActionContext } from '../terminal-link-action-request' - -const mocks = await vi.hoisted(async () => { - const { acceptedAgentStatuses } = - await import('@/store/slices/agent-status/accepted-agent-statuses') - return { - activateTabAndFocusPane: vi.fn(), - focusTerminalTabSurface: vi.fn(), - revealFloatingWorkspacePanel: vi.fn(), - storeState: { - tabsByWorktree: {}, - ptyIdsByTabId: {}, - terminalLayoutsByTabId: {}, - agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})), - - runtimeAgentOrchestrationByPaneKey: {}, - setActiveWorktree: vi.fn(), - markWorktreeVisited: vi.fn(), - recordWorktreeVisit: vi.fn(), - isNavigatingHistory: false, - setActiveView: vi.fn(), - setActiveTabType: vi.fn(), - revealWorktreeInSidebar: vi.fn(), - setActiveTab: vi.fn() - } - } -}) - -vi.mock('@/store/index', () => ({ - useAppStore: { - getState: () => mocks.storeState - } -})) - -vi.mock('@/lib/workspace/tabs/activate-tab-and-focus-pane', () => ({ - activateTabAndFocusPane: mocks.activateTabAndFocusPane -})) - -vi.mock('@/components/floating-terminal/workspace/floating-workspace-panel-reveal', () => ({ - revealFloatingWorkspacePanel: mocks.revealFloatingWorkspacePanel -})) - -vi.mock('@/components/terminal-pane/input/focus/focus-terminal-tab-surface', () => ({ - focusTerminalTabSurface: mocks.focusTerminalTabSurface -})) - -type TestBufferLine = { - isWrapped: boolean - length: number - translateToString: ( - trimRight?: boolean, - startColumn?: number, - endColumn?: number, - outColumns?: number[] - ) => string -} - -function makeBufferLine(text: string, options: { isWrapped?: boolean } = {}): TestBufferLine { - return { - isWrapped: options.isWrapped ?? false, - length: text.length, - translateToString: ( - _trimRight?: boolean, - startColumn = 0, - endColumn = text.length, - outColumns?: number[] - ) => { - if (outColumns) { - outColumns.length = 0 - for (let index = startColumn; index <= endColumn; index++) { - outColumns.push(index) - } - } - return text.slice(startColumn, endColumn) - } - } -} - -function setPlatform(userAgent: string): void { - vi.stubGlobal('navigator', { userAgent }) -} - -async function collectLinks( - rows: TestBufferLine[], - bufferLineNumber = 1, - runtimeEnvironmentId: string | null = null, - linkActionContext?: TerminalLinkActionContext -): Promise { - const terminal = { - buffer: { - active: { - getLine: (y: number) => rows[y] - } - }, - clearSelection: vi.fn() - } - const provider = createTerminalHandleLinkProvider({ - getTerminal: () => terminal as never, - getRuntimeEnvironmentId: () => runtimeEnvironmentId, - linkTooltip: { textContent: '', style: { display: '' } } as unknown as HTMLElement, - getLinkActionContext: () => linkActionContext ?? null - }) - return await new Promise((resolve) => { - provider.provideLinks(bufferLineNumber, (links) => resolve(links ?? [])) - }) -} - -describe('extractTerminalHandleLinks', () => { - it('detects UUID terminal handles from orchestration output', () => { - const line = '- Terminal: term_d422ff9f-42c8-4d70-bb6a-71762b21ab95' - - expect(extractTerminalHandleLinks(line)).toEqual([ - { - handle: 'term_d422ff9f-42c8-4d70-bb6a-71762b21ab95', - startIndex: 12, - endIndex: 53 - } - ]) - }) - - it('trims sentence punctuation without matching inside longer tokens', () => { - expect(extractTerminalHandleLinks('Open term_worker, not xterm_worker.')).toEqual([ - { handle: 'term_worker', startIndex: 5, endIndex: 16 } - ]) - }) - - it('ignores overlong handle tokens', () => { - expect(extractTerminalHandleLinks(`Open term_${'a'.repeat(129)}`)).toEqual([]) - }) -}) - -describe('extractOrchestrationTaskLinks', () => { - it('detects task IDs from orchestration dispatch output', () => { - const line = 'Ran orca orchestration dispatch --task task_88f323f654c0 --to term_worker' - - expect(extractOrchestrationTaskLinks(line)).toEqual([ - { - taskId: 'task_88f323f654c0', - startIndex: 39, - endIndex: 56 - } - ]) - }) - - it('trims sentence punctuation without matching inside longer tokens', () => { - expect(extractOrchestrationTaskLinks('Open task_worker, not xtask_worker.')).toEqual([ - { taskId: 'task_worker', startIndex: 5, endIndex: 16 } - ]) - }) - - it('caps orchestration task IDs by full token length', () => { - const maxLengthTaskId = `task_${'a'.repeat(123)}` - - expect(extractOrchestrationTaskLinks(`Open ${maxLengthTaskId}`)).toEqual([ - { taskId: maxLengthTaskId, startIndex: 5, endIndex: 133 } - ]) - expect(extractOrchestrationTaskLinks(`Open task_${'a'.repeat(124)}`)).toEqual([]) - }) -}) - -describe('findTerminalHandleTarget', () => { - it('finds split-pane remote runtime handles from leaf PTY mappings', () => { - expect( - findTerminalHandleTarget('term_remote', { - tabsByWorktree: { - 'wt-1': [ - { - id: 'tab-1', - worktreeId: 'wt-1', - ptyId: null, - title: 'Terminal', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - }, - ptyIdsByTabId: { 'tab-1': ['remote:env-1@@term_remote'] }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { type: 'leaf', leafId: 'leaf-a' }, - activeLeafId: 'leaf-a', - expandedLeafId: null, - ptyIdsByLeafId: { 'leaf-a': 'remote:env-1@@term_remote' } - } - } - }) - ).toEqual({ worktreeId: 'wt-1', tabId: 'tab-1', leafId: 'leaf-a' }) - }) -}) - -describe('createTerminalHandleLinkProvider', () => { - beforeEach(() => { - vi.clearAllMocks() - setPlatform('Macintosh') - mocks.storeState.tabsByWorktree = {} - mocks.storeState.ptyIdsByTabId = {} - mocks.storeState.terminalLayoutsByTabId = {} - mocks.storeState.agentStatusByPaneKey = acceptedAgentStatuses(Object.entries({})) - mocks.storeState.runtimeAgentOrchestrationByPaneKey = {} - vi.stubGlobal('window', { - api: { - runtime: { - call: vi.fn().mockImplementation(({ method }) => { - if (method === 'orchestration.dispatchShow') { - return Promise.resolve({ - ok: true, - result: { dispatch: { assignee_handle: 'term_worker' } } - }) - } - return Promise.resolve({ - ok: true, - result: { focus: { handle: 'term_worker', tabId: 'tab-1', worktreeId: 'wt-1' } } - }) - }) - }, - runtimeEnvironments: { - call: vi.fn() - } - } - }) - }) - - afterEach(() => { - vi.unstubAllGlobals() - clearRuntimeCompatibilityCacheForTests() - }) - - it('returns task and terminal links in line order', async () => { - const links = await collectLinks([ - makeBufferLine('Dispatch --task task_worker --to term_worker') - ]) - - expect(links.map((link) => link.text)).toEqual(['task_worker', 'term_worker']) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/notifications/terminal-completion-after-exit.test.ts b/src/renderer/src/components/terminal-pane/notifications/terminal-completion-after-exit.test.ts deleted file mode 100644 index 2dc90fb00e8..00000000000 --- a/src/renderer/src/components/terminal-pane/notifications/terminal-completion-after-exit.test.ts +++ /dev/null @@ -1,201 +0,0 @@ -import { acceptedAgentStatuses } from '@/store/slices/agent-status/accepted-agent-statuses' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createTestStore } from '@/store/testing/app-store-test-fixture' -import { makeTab } from '@/store/terminals/testing/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 { setPresenceGated } from '@/hooks/agent-auto-ack-presence' -import type { GlobalSettings } from '../../../../../shared/global-settings-types' -import { reduceHostTurnEnd } from '../../../../../shared/agent-hook-listener/state/agent-hook-turn-end-timing' -import type { AgentHookEventPayload } from '../../../../../shared/agent-hook-listener/listener-event' -import { createHookListenerState } from '../../../../../shared/agent-hook-listener/listener-state' -import { normalizeHookPayload } from '../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload' -import { - observeAgentHookCompletionForNotification, - syncAgentHookCompletionNotificationSettings, - resetAgentHookCompletionNotificationCoordinators -} from '@/hooks/agent-hook-completion-notifications' - -vi.mock('@/store', () => ({ useAppStore: { getState: () => store.getState() } })) -vi.mock('../agent-completion/agent-hook-terminal-lifecycle', () => ({ - dispatchAgentHookTerminalLifecycle: vi.fn() -})) -vi.mock('@/lib/notifications/desktop-notification-sound', () => ({ - playDesktopNotificationSound: vi.fn() -})) -vi.mock('@/store/slices/worktrees/metadata/worktree-meta-persist', () => ({ - persistWorktreeMeta: vi.fn(async () => undefined) -})) - -const store = createTestStore() -const WORKSPACE = 'repo1::/tmp/completion' -const LEAF = '11111111-1111-4111-8111-111111111111' -const PANE = `tab-1:${LEAF}` -const notifications = vi.fn(async () => ({ delivered: true })) - -beforeEach(() => { - vi.useFakeTimers() - vi.setSystemTime(1000) - setPresenceGated(false) - notifications.mockClear() - vi.stubGlobal('document', { visibilityState: 'hidden', hasFocus: () => false }) - vi.stubGlobal('window', { - api: { - notifications: { dispatch: notifications }, - agentStatus: {}, - github: { enqueuePRRefresh: vi.fn(async () => undefined) } - } - }) - store.setState({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only notification policy fields are read. - settings: { experimentalTerminalAttention: true } as GlobalSettings, - repos: [{ ...TEST_REPO, executionHostId: 'local' }], - worktreesByRepo: { - repo1: [makeWorktree({ id: WORKSPACE, repoId: 'repo1', hostId: 'local' })] - }, - tabsByWorktree: { [WORKSPACE]: [makeTab({ id: 'tab-1', worktreeId: WORKSPACE, ptyId: null })] }, - unifiedTabsByWorktree: { - [WORKSPACE]: [ - makeUnifiedTab({ - id: 'tab-1', - entityId: 'tab-1', - contentType: 'terminal', - groupId: 'group-1', - worktreeId: WORKSPACE, - executionHostId: 'local' - }) - ] - }, - terminalLayoutsByTabId: { - 'tab-1': { - root: { type: 'leaf', leafId: LEAF }, - activeLeafId: LEAF, - expandedLeafId: null, - ptyIdsByLeafId: {} - } - }, - ptyIdsByTabId: {}, - agentStatusByPaneKey: acceptedAgentStatuses(Object.entries({})), - agentConversationsByPaneKey: {}, - activeWorktreeId: null, - refreshGitHubForWorktreeIfStale: vi.fn(), - unreadAgentCompletionPanes: {}, - unreadTerminalPanes: {}, - unreadTerminalTabs: {} - }) -}) - -afterEach(() => { - resetAgentHookCompletionNotificationCoordinators() - setPresenceGated(true) - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -describe('completion after the process exits with its pane still open', () => { - it.each([ - { agent: 'claude', exitAfterDelivery: false }, - { agent: 'codex', exitAfterDelivery: false }, - { agent: 'claude', exitAfterDelivery: true }, - { agent: 'codex', exitAfterDelivery: true }, - { agent: 'claude', exitAfterDelivery: false, suppressedExit: true }, - { agent: 'codex', exitAfterDelivery: false, suppressedExit: true } - ] as const)( - 'delivers $agent completion and keeps the workspace unread (exitAfterDelivery=$exitAfterDelivery)', - async (scenario) => { - const { agent, exitAfterDelivery } = scenario - const suppressedExit = 'suppressedExit' in scenario - store.setState({ - tabsByWorktree: { - [WORKSPACE]: [makeTab({ id: 'tab-1', worktreeId: WORKSPACE, ptyId: 'pty-1' })] - }, - ptyIdsByTabId: { 'tab-1': ['pty-1'] }, - terminalLayoutsByTabId: { - 'tab-1': { - ...store.getState().terminalLayoutsByTabId['tab-1'], - ptyIdsByLeafId: { [LEAF]: 'pty-1' } - } - } - }) - const listener = createHookListenerState() - let previous: AgentHookEventPayload | undefined - try { - for (const [at, hookPayload] of [ - [1000, { hook_event_name: 'UserPromptSubmit', prompt: 'finish the task' }], - [5000, { hook_event_name: 'Stop', last_assistant_message: 'Finished.' }] - ] as const) { - vi.setSystemTime(at) - const event = normalizeHookPayload( - listener, - agent, - { - paneKey: PANE, - tabId: 'tab-1', - worktreeId: WORKSPACE, - payload: { session_id: 'session-1', ...hookPayload } - }, - 'production' - ) - if (!event) { - throw new Error('Expected a normalized hook event') - } - const timing = reduceHostTurnEnd(previous, event, at, true) - previous = { ...event, ...timing } - const payload = { ...event.payload, ...timing, stateStartedAt: at } - store - .getState() - .setAgentStatus( - PANE, - payload, - undefined, - { updatedAt: at, stateStartedAt: at }, - { worktreeId: WORKSPACE, tabId: 'tab-1', connectionId: null }, - { providerSession: { key: 'session_id', id: 'session-1' } } - ) - observeAgentHookCompletionForNotification({ - paneKey: PANE, - worktreeId: WORKSPACE, - payload - }) - } - if (exitAfterDelivery) { - await vi.advanceTimersByTimeAsync(2000) - } - // Main may publish resume identity after clearing the exited process's turn claims. - store - .getState() - .recordAgentProviderSession( - PANE, - agent, - { key: 'session_id', id: 'session-1' }, - { updatedAt: Date.now() }, - { worktreeId: WORKSPACE, tabId: 'tab-1', connectionId: null } - ) - store.setState({ - ptyIdsByTabId: {}, - suppressedPtyExitIds: suppressedExit ? { 'pty-1': true } : {}, - terminalLayoutsByTabId: { - 'tab-1': { ...store.getState().terminalLayoutsByTabId['tab-1'], ptyIdsByLeafId: {} } - } - }) - store.getState().removeAgentStatus(PANE) - syncAgentHookCompletionNotificationSettings() - await vi.advanceTimersByTimeAsync(2000) - expect(notifications).toHaveBeenCalledWith( - expect.objectContaining({ - source: 'agent-task-complete', - agentType: agent, - workspaceExecutionHostId: 'local', - paneKey: PANE, - worktreeId: WORKSPACE - }) - ) - expect(store.getState().worktreesByRepo.repo1[0].isUnread).toBe(true) - expect(store.getState().agentStatusByPaneKey.get(PANE)).toBeUndefined() - } finally { - resetAgentHookCompletionNotificationCoordinators() - } - } - ) -}) diff --git a/src/renderer/src/hooks/useDetectedAgents.test.tsx b/src/renderer/src/hooks/useDetectedAgents.test.tsx index 9c0222389df..86f3346d8f5 100644 --- a/src/renderer/src/hooks/useDetectedAgents.test.tsx +++ b/src/renderer/src/hooks/useDetectedAgents.test.tsx @@ -111,35 +111,6 @@ beforeEach(() => { } as unknown as Window['api'] }) -it('loads complete Settings inventory even when the automatic inventory is already cached', async () => { - useAppStore.getState().clearLocalDetectedAgents() - detectLocalAgents.mockImplementation((args) => - Promise.resolve(args?.enabledOnly ? ['claude'] : ['claude', 'kiro']) - ) - await useAppStore.getState().ensureDetectedAgents() - const container = document.createElement('div') - document.body.appendChild(container) - const root = createRoot(container) - roots.push(root) - await act(async () => { - root.render(createElement(HookProbe, { target: { kind: 'local' }, inventory: 'all' })) - }) - await flushEffects() - expect(latestHookResult?.detectedIds).toEqual(['claude', 'kiro']) - expect(useAppStore.getState().detectedAgentIds).toEqual(['claude']) - expect(detectLocalAgents.mock.calls.map(([args]) => args?.enabledOnly === true)).toEqual([ - true, - false - ]) - refreshLocalAgents.mockResolvedValueOnce({ agents: ['claude', 'codex', 'kiro'] }) - await act(async () => { - await latestHookResult?.refresh() - }) - expect(latestHookResult?.detectedIds).toEqual(['claude', 'codex', 'kiro']) - expect(refreshLocalAgents.mock.lastCall?.[0]?.enabledOnly).not.toBe(true) - expect(useAppStore.getState().detectedAgentIds).toEqual(['claude', 'codex', 'kiro']) -}) - describe('Floating Workspace authority', () => { it('advertises native Windows agents beside an active WSL project', async () => { const activeResult: { current: UseDetectedAgentsResult | null } = { current: null } diff --git a/src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts b/src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts index b87f733d8fd..a66a72f4068 100644 --- a/src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts +++ b/src/renderer/src/lib/monaco-languages/monarch-embed-entry-recursion.test.ts @@ -3,12 +3,7 @@ import { EMBED_ENTRY_REST_OF_LINE_BUDGET, MAX_TOKENIZATION_LINE_LENGTH } from './monarch-embed-entry-budget' -import { - createMonarchTokenizer, - endEmbeddedLanguages, - measureNestedDepth, - tokenizeLines -} from './monarch-tokenizer-test-harness' +import { createMonarchTokenizer, measureNestedDepth } from './monarch-tokenizer-test-harness' import { astroMonarchLanguage } from './register-astro' import { glimmerTsMonarchLanguage } from './register-glimmer' import { svelteMonarchLanguage } from './register-svelte' @@ -76,42 +71,6 @@ describe.each([ ) } ) - - it('tokenizes interpolations without dropping the embed', () => { - // Regression: monarch honours `nextEmbedded` on a zero-width match only - // when the token is `@rematch`; with any other token it hits the - // no-progress `continue` and silently drops the pending embed. Both - // grammars then reached a `nextEmbedded: '@pop'` rule with no embed - // active and threw "cannot pop embedded language if not inside one" on - // the *first* interpolation — the error seen in the field. - const measurement = measureNestedDepth(createMonarchTokenizer(languageId, language), [ - '

a {first} b {second} c

' - ]) - - expect(measurement.error).toBeUndefined() - // Depth > 0 proves the embeds were really entered, not silently skipped. - expect(measurement.maxNestedDepth).toBeGreaterThan(0) - }) - - it.each([ - ['script', 'ts', 'typescript'], - ['style', 'scss', 'scss'] - ])('re-embeds a %s body after an over-budget opening line', (tag, lang, embeddedLanguageId) => { - // The opening tag plus code on the same line pushes the tag close past the - // budget, so the body starts unembedded. Every following short line must - // recover the embed (and the `lang=` language) instead of leaving the whole - // block unhighlighted until the closing tag. - const embeds = endEmbeddedLanguages( - tokenizeLines(createMonarchTokenizer(languageId, language), [ - `<${tag} lang="${lang}">a = "${'x'.repeat(EMBED_ENTRY_REST_OF_LINE_BUDGET)}"`, - ' b', - ' c', - `` - ]) - ) - - expect(embeds).toEqual([null, embeddedLanguageId, embeddedLanguageId, null]) - }) }) describe('vue embed-entry recursion', () => { @@ -136,32 +95,6 @@ describe('vue embed-entry recursion', () => { ramp.at(-1) as number ) }) - - it.each([ - ['script', 'ts', 'typescript'], - ['style', 'scss', 'scss'] - ])('re-embeds a %s body after an over-budget opening line', (tag, lang, embeddedLanguageId) => { - const embeds = endEmbeddedLanguages( - tokenizeLines(createMonarchTokenizer('vue', vueMonarchLanguage), [ - `<${tag} lang="${lang}">a = "${'x'.repeat(EMBED_ENTRY_REST_OF_LINE_BUDGET)}"`, - ' b', - `` - ]) - ) - - expect(embeds).toEqual([null, embeddedLanguageId, null]) - }) - - it('tokenizes a template interpolation without dropping the embed', () => { - const measurement = measureNestedDepth(createMonarchTokenizer('vue', vueMonarchLanguage), [ - '' - ]) - - expect(measurement.error).toBeUndefined() - expect(measurement.maxNestedDepth).toBeGreaterThan(0) - }) }) describe('glimmer embed-entry recursion', () => { @@ -185,20 +118,4 @@ describe('glimmer embed-entry recursion', () => { expect(measurement.maxNestedDepth).toBeLessThanOrEqual(EMBED_ENTRY_REST_OF_LINE_BUDGET) } }) - - it('re-embeds script and template after over-budget lines', () => { - const long = 'x'.repeat(EMBED_ENTRY_REST_OF_LINE_BUDGET) - const embeds = endEmbeddedLanguages( - tokenizeLines(createMonarchTokenizer('glimmer-ts', glimmerTsMonarchLanguage), [ - `const s = "${long}"`, - 'const b = 1', - `', - 'const c = 1' - ]) - ) - - expect(embeds).toEqual([null, 'typescript', null, 'handlebars', null, 'typescript']) - }) }) diff --git a/src/renderer/src/lib/workspace/search/tabs/workspace-tab-palette-activation.store.test.ts b/src/renderer/src/lib/workspace/search/tabs/workspace-tab-palette-activation.store.test.ts deleted file mode 100644 index b1caa131072..00000000000 --- a/src/renderer/src/lib/workspace/search/tabs/workspace-tab-palette-activation.store.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, expect, it, vi } from 'vitest' -import { useAppStore } from '@/store/index' -import type { Tab } from '../../../../../../shared/workspace-layout/tab-groups/tab-types' -import type { Worktree } from '../../../../../../shared/worktree/types' - -vi.mock('../../activation/worktree-activation', () => ({ - activateAndRevealWorkspace: () => true -})) -vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ - callRuntimeRpc: vi.fn(async () => undefined) -})) - -import { activateWorkspaceTabPaletteResult } from './workspace-tab-palette-activation' -import { - getClientHostedBrowserRowSelection, - selectClientHostedBrowserRow -} from '../../../../runtime/browser/client-hosting/client-hosted-browser-row-state' - -const initialState = useAppStore.getInitialState() -afterEach(() => { - useAppStore.setState(initialState, true) - document.body.innerHTML = '' -}) - -const worktree: Worktree = { - id: 'wt', - repoId: 'repo', - path: '/workspace', - head: '', - branch: 'main', - isBare: false, - isMainWorktree: true, - displayName: 'Workspace', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0 -} - -it('keeps the selected diff active when an editor for the same file shares its group', () => { - const editor: Tab = { - id: 'editor', - entityId: 'file', - groupId: 'group', - worktreeId: 'wt', - contentType: 'editor', - label: 'app.ts', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0 - } - useAppStore.setState( - { - ...initialState, - worktreesByRepo: { repo: [worktree] }, - activeWorktreeId: 'wt', - groupsByWorktree: { - wt: [{ id: 'group', worktreeId: 'wt', activeTabId: 'editor', tabOrder: ['editor', 'diff'] }] - }, - activeGroupIdByWorktree: { wt: 'group' }, - unifiedTabsByWorktree: { wt: [editor, { ...editor, id: 'diff', contentType: 'diff' }] }, - openFiles: [ - { - id: 'file', - worktreeId: 'wt', - filePath: '/workspace/app.ts', - relativePath: 'app.ts', - language: 'typescript', - isDirty: false, - mode: 'edit' - } - ] - }, - true - ) - - expect( - activateWorkspaceTabPaletteResult({ - worktreeId: 'wt', - groupId: 'group', - tabId: 'diff', - entityId: 'file', - contentType: 'diff' - }) - ).toEqual({ status: 'activated' }) - expect(useAppStore.getState().groupsByWorktree.wt[0].activeTabId).toBe('diff') - expect(useAppStore.getState().activeFileId).toBe('file') -}) - -it('shows the selected chat even when a paired-device page placeholder covered it', () => { - const chat: Tab = { - id: 'chat', - entityId: 'session', - groupId: 'group', - worktreeId: 'wt', - contentType: 'agent-session', - agentSessionAgent: 'claude', - label: 'Claude', - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 0 - } - useAppStore.setState( - { - ...initialState, - worktreesByRepo: { repo: [worktree] }, - activeWorktreeId: 'wt', - groupsByWorktree: { - wt: [{ id: 'group', worktreeId: 'wt', activeTabId: 'chat', tabOrder: ['chat'] }] - }, - activeGroupIdByWorktree: { wt: 'group' }, - unifiedTabsByWorktree: { wt: [chat] } - }, - true - ) - selectClientHostedBrowserRow({ - worktreeId: 'wt', - browserPageId: 'page-on-phone', - groupId: 'group', - groupActiveTabIdAtSelection: 'chat' - }) - - expect( - activateWorkspaceTabPaletteResult({ - worktreeId: 'wt', - groupId: 'group', - tabId: 'chat', - entityId: 'session', - contentType: 'agent-session' - }) - ).toEqual({ status: 'activated' }) - expect(getClientHostedBrowserRowSelection()).toBeNull() - expect(useAppStore.getState().activeTabType).toBe('agent-session') -}) diff --git a/src/shared/ai-vault/session-display/ai-vault-session-filters.test.ts b/src/shared/ai-vault/session-display/ai-vault-session-filters.test.ts deleted file mode 100644 index 5e8768b3529..00000000000 --- a/src/shared/ai-vault/session-display/ai-vault-session-filters.test.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { AiVaultSession } from '../contracts/ai-vault-types' -import { filterAiVaultSessions, groupAiVaultSessions } from './ai-vault-session-filters' -import './ai-vault-session-display' - -const baseSession: AiVaultSession = { - id: 'claude:1', - executionHostId: 'local', - agent: 'claude', - sessionId: 'session-1', - title: 'Implement vault filters', - cwd: '/Users/ada/repo/app', - branch: 'feature/vault', - model: 'claude-sonnet-4-5', - filePath: '/Users/ada/.claude/projects/session-1.jsonl', - codexHome: null, - createdAt: '2026-05-01T10:00:00.000Z', - updatedAt: '2026-05-01T10:10:00.000Z', - modifiedAt: '2026-05-01T10:10:00.000Z', - messageCount: 4, - totalTokens: 1200, - previewMessages: [ - { role: 'user', text: 'add the scope tabs', timestamp: null }, - { role: 'assistant', text: 'done — added Workspace/Project/All', timestamp: null } - ], - queuedMessageCount: 0, - subagentTranscriptCount: 0, - resumeCommand: "cd '/Users/ada/repo/app' && claude --resume 'session-1'", - subagent: null -} - -const otherSession: AiVaultSession = { - ...baseSession, - id: 'codex:2', - agent: 'codex', - sessionId: 'session-2', - title: 'Repair terminal tabs', - cwd: '/Users/ada/other/packages/ui', - branch: 'fix/terminal', - filePath: '/Users/ada/.codex/sessions/session-2.jsonl', - previewMessages: [] -} - -describe('/shared ai-vault-session-filters (lifted core)', () => { - it('filters by agent, workspace scope, and plain/repo/path query terms', () => { - expect( - filterAiVaultSessions( - [ - baseSession, - otherSession, - { ...baseSession, id: 'wrong-agent', agent: 'codex' }, - { ...baseSession, id: 'outside-scope', cwd: '/outside/repo/app' }, - { ...baseSession, id: 'wrong-text', title: 'Unrelated request', branch: null }, - { ...baseSession, id: 'wrong-repo', cwd: '/Users/ada/repo/other/app' }, - { - ...baseSession, - id: 'wrong-path', - cwd: '/Users/ada/repo/lib', - filePath: '/transcripts/session.jsonl' - } - ], - { - query: 'vault repo:repo path:app', - agents: ['claude'], - scope: 'workspace', - sort: 'updated', - activeWorktreePaths: ['/Users/ada/repo'], - hideEmptySessions: true - } - ).map((session) => session.id) - ).toEqual(['claude:1']) - }) - - it('folds the project-grouping fallback onto the resolved folder project key', () => { - const resolved = { ...baseSession, cwd: '/Users/ada/repo/app' } - const unresolved = { ...baseSession, id: 'claude:2', cwd: '/Users/ada/repo/app/' } - // Key literal, not folderGroupKey(), so the test still fails if both builders drift together. - const groups = groupAiVaultSessions([resolved, unresolved], 'project', { - sessionProjectById: new Map([ - [ - resolved.id, - { kind: 'folder' as const, key: 'folder:/Users/ada/repo/app', label: 'repo/app' } - ] - ]) - }) - expect(groups).toHaveLength(1) - expect(groups[0].sessions).toHaveLength(2) - }) -}) - -describe('filterAiVaultSessions symlinked workspace', () => { - it('keeps a session recorded under the real path when the host aliased it to the workspace', () => { - const recordedUnderRealPath: AiVaultSession = { - ...baseSession, - cwd: '/data/src/repo', - cwdAliases: ['/Users/ada/repo'] - } - - const filtered = filterAiVaultSessions([recordedUnderRealPath], { - query: '', - agents: ['claude'], - scope: 'workspace', - sort: 'updated', - activeWorktreePaths: ['/Users/ada/repo'], - hideEmptySessions: false - }) - - expect(filtered.map((entry) => entry.cwd)).toEqual(['/data/src/repo']) - }) -}) diff --git a/src/shared/github/projects/project-group-sort.test.ts b/src/shared/github/projects/project-group-sort.test.ts deleted file mode 100644 index 4afe4773f74..00000000000 --- a/src/shared/github/projects/project-group-sort.test.ts +++ /dev/null @@ -1,348 +0,0 @@ -import { describe, expect, it } from 'vitest' -import type { - GitHubProjectField, - GitHubProjectRow, - GitHubProjectSort, - GitHubProjectTable, - GitHubProjectView -} from './project-types' -import { sortRows, groupRows } from './project-group-sort' - -const singleSelectField: GitHubProjectField = { - kind: 'single-select', - id: 'F_status', - name: 'Status', - dataType: 'SINGLE_SELECT', - options: [ - { id: 'opt_a', name: 'Todo', color: 'GRAY' }, - { id: 'opt_b', name: 'In Progress', color: 'YELLOW' } - ] -} - -const assigneesField: GitHubProjectField = { - kind: 'field', - id: 'F_assignees', - name: 'Assignees', - dataType: 'ASSIGNEES' -} - -const numberField: GitHubProjectField = { - kind: 'field', - id: 'F_points', - name: 'Story Points', - dataType: 'NUMBER' -} - -function makeRow( - id: string, - position: number, - values: GitHubProjectRow['fieldValuesByFieldId'], - parentIssue: GitHubProjectRow['content']['parentIssue'] = null -): GitHubProjectRow { - return { - id, - itemType: 'ISSUE', - content: { - number: 1, - title: id, - body: null, - url: null, - state: 'open', - stateReason: null, - isDraft: null, - repository: 'acme/repo', - assignees: [], - labels: [], - parentIssue, - issueType: null - }, - fieldValuesByFieldId: values, - updatedAt: '2026-01-01T00:00:00Z', - position - } -} - -function makeView(field: GitHubProjectField, sort?: GitHubProjectSort): GitHubProjectView { - return { - id: 'V_1', - number: 1, - name: 'Default', - layout: 'TABLE_LAYOUT', - filter: '', - fields: [field], - groupByFields: [], - sortByFields: sort ? [sort] : [] - } -} - -function makeTable(view: GitHubProjectView, rows: GitHubProjectRow[]): GitHubProjectTable { - return { - project: { - id: 'P', - owner: 'acme', - ownerType: 'organization', - number: 1, - title: 'P', - url: '' - }, - selectedView: view, - rows, - totalCount: rows.length, - parentFieldDropped: false - } -} - -describe('sortRows', () => { - it('does not produce NaN when both rows reference unknown single-select options', () => { - // Avoid Infinity - Infinity producing NaN and bypassing the position tie-break for orphaned options. - const view = makeView(singleSelectField, { - direction: 'ASC', - field: singleSelectField - }) - const rows = [ - makeRow('rB', 5, { - F_status: { - kind: 'single-select', - fieldId: 'F_status', - optionId: 'orphan_2', - name: 'Gone', - color: 'GRAY' - } - }), - makeRow('rA', 1, { - F_status: { - kind: 'single-select', - fieldId: 'F_status', - optionId: 'orphan_1', - name: 'Gone', - color: 'GRAY' - } - }) - ] - const sorted = sortRows(makeTable(view, rows), rows) - expect(sorted.map((r) => r.id)).toEqual(['rA', 'rB']) - }) - - it('sorts an empty user list last in both directions, like a missing value', () => { - const rows = [ - makeRow('empty-list', 0, { - F_assignees: { kind: 'users', fieldId: 'F_assignees', users: [] } - }), - makeRow('alice', 1, { - F_assignees: { - kind: 'users', - fieldId: 'F_assignees', - users: [{ login: 'alice', name: null, avatarUrl: null }] - } - }), - makeRow('no-value', 2, {}) - ] - - for (const direction of ['ASC', 'DESC'] as const) { - const view = makeView(assigneesField, { direction, field: assigneesField }) - const sorted = sortRows(makeTable(view, rows), rows) - expect(sorted.map((r) => r.id)).toEqual(['alice', 'empty-list', 'no-value']) - } - }) -}) - -describe('groupRows', () => { - it('groups a present-but-empty user list with the missing-value rows', () => { - const view = { ...makeView(assigneesField), groupByFields: [assigneesField] } - const rows = [ - makeRow('empty-list', 0, { - F_assignees: { kind: 'users', fieldId: 'F_assignees', users: [] } - }), - makeRow('alice', 1, { - F_assignees: { - kind: 'users', - fieldId: 'F_assignees', - users: [{ login: 'alice', name: null, avatarUrl: null }] - } - }), - makeRow('no-value', 2, {}) - ] - - const groups = groupRows(makeTable(view, rows), rows) - - expect(groups.map((group) => [group.label, group.rows.map((r) => r.id)])).toEqual([ - ['alice', ['alice']], - ['No Assignees', ['empty-list', 'no-value']] - ]) - }) - - it('orders number-field groups by value, not by the rendered label', () => { - const view = { ...makeView(numberField), groupByFields: [numberField] } - const rows = [8, 10, -2, 2, -10, 1].map((points, index) => - makeRow(`p${index}`, index, { - F_points: { kind: 'number', fieldId: 'F_points', number: points } - }) - ) - - const groups = groupRows(makeTable(view, rows), rows) - - expect(groups.map((group) => group.label)).toEqual(['-10', '-2', '1', '2', '8', '10']) - }) - - it('groups by Parent issue from row content, since GitHub returns no field value for it', () => { - const parentField: GitHubProjectField = { - kind: 'field', - id: 'F_parent', - name: 'Parent issue', - dataType: 'PARENT_ISSUE' - } - const view = { ...makeView(parentField), groupByFields: [parentField] } - const parent = (repo: string, number: number) => ({ - number, - title: `Parent ${number}`, - url: `https://github.com/${repo}/issues/${number}` - }) - const rows = [ - makeRow('a1', 0, {}, parent('acme/repo', 101)), - makeRow('b', 1, {}, parent('acme/repo', 9)), - makeRow('orphan', 2, {}), - makeRow('a2', 3, {}, parent('acme/repo', 101)), - makeRow('other-repo', 4, {}, parent('acme/other', 101)) - ] - - const groups = groupRows(makeTable(view, rows), rows) - - expect(groups.map((group) => [group.label, group.rows.map((r) => r.id)])).toEqual([ - ['#9', ['b']], - ['#101', ['a1', 'a2']], - ['#101', ['other-repo']], - ['No Parent issue', ['orphan']] - ]) - }) -}) - -it('uses the first iteration ordering and metadata when legacy field IDs repeat', () => { - const field: GitHubProjectField = { - kind: 'iteration', - id: 'iteration', - name: 'Iteration', - dataType: 'ITERATION', - iterations: [ - { id: 'a', title: 'First', startDate: '2026-01-01', duration: 7, completed: true }, - { id: 'b', title: 'Second', startDate: '2026-02-01', duration: 14, completed: false }, - { id: 'a', title: 'Duplicate', startDate: '2026-03-01', duration: 21, completed: false } - ] - } - const rows = ['b', 'a'].map((id, index) => - makeRow(id, index, { - iteration: { - kind: 'iteration', - fieldId: 'iteration', - iterationId: id, - title: id, - startDate: '2026-01-01', - duration: 7 - } - }) - ) - const table = makeTable( - { ...makeView(field, { field, direction: 'ASC' }), groupByFields: [field] }, - rows - ) - expect(sortRows(table, rows).map((row) => row.id)).toEqual(['a', 'b']) - expect(groupRows(table, rows)[0].iteration).toEqual({ - startDate: '2026-01-01', - duration: 7, - completed: true - }) -}) - -it('sorts content-backed parents with absent values last and secondary sorts before positions', () => { - const field: GitHubProjectField = { - kind: 'field', - id: 'parent', - name: 'Parent issue', - dataType: 'PARENT_ISSUE' - } - const parent = (repo: string, number: number) => ({ - number, - title: 'Parent', - url: `https://github.com/${repo}/issues/${number}` - }) - const rows = [ - makeRow('high', 0, {}, parent('acme/repo', 101)), - makeRow('low', 1, {}, parent('acme/repo', 9)), - makeRow('absent', 2, { parent: { kind: 'number', fieldId: 'parent', number: 1 } }), - makeRow( - 'same', - 3, - { F_points: { kind: 'number', fieldId: 'F_points', number: 1 } }, - parent('acme/other', 101) - ) - ] - rows[0].fieldValuesByFieldId.F_points = { kind: 'number', fieldId: 'F_points', number: 9 } - for (const [direction, expected] of [ - ['ASC', ['low', 'same', 'high', 'absent']], - ['DESC', ['same', 'high', 'low', 'absent']] - ] as const) { - const view = { - ...makeView(field), - sortByFields: [ - { field, direction }, - { field: numberField, direction: 'ASC' as const } - ] - } - expect(sortRows(makeTable(view, rows), rows).map((row) => row.id)).toEqual(expected) - } -}) - -it('groups repositories from content and orders synthetic progress groups numerically', () => { - const field: GitHubProjectField = { - kind: 'field', - id: 'repo', - name: 'Repository', - dataType: 'REPOSITORY' - } - const rows = [makeRow('z', 0, {}), makeRow('a', 1, {}), makeRow('empty', 2, {})] - rows[0].content.repository = 'acme/z' - rows[1].content.repository = 'acme/a' - rows[2].content.repository = null - const table = makeTable( - { ...makeView(field, { field, direction: 'DESC' }), groupByFields: [field] }, - rows - ) - expect( - groupRows(table, rows).map((group) => [group.label, group.rows.map((row) => row.id)]) - ).toEqual([ - ['acme/a', ['a']], - ['acme/z', ['z']], - ['No Repository', ['empty']] - ]) - expect(sortRows(table, rows).map((row) => row.id)).toEqual(['z', 'a', 'empty']) - const progress: GitHubProjectField = { - kind: 'field', - id: 'progress', - name: 'Sub-issues progress', - dataType: 'SUB_ISSUES_PROGRESS' - } - const progressRows = [90, 100, 20, 0].map((percent, index) => { - const row = makeRow(`p${percent}`, index, {}) - row.content.subIssuesProgress = { - completed: percent / 10, - total: percent === 0 ? 0 : 10, - percentCompleted: percent - } - return row - }) - const progressTable = makeTable( - { ...makeView(progress, { field: progress, direction: 'DESC' }), groupByFields: [progress] }, - progressRows - ) - expect(groupRows(progressTable, progressRows).map((group) => group.label)).toEqual([ - '2/10 (20%)', - '9/10 (90%)', - '10/10 (100%)', - 'No Sub-issues progress' - ]) - expect(sortRows(progressTable, progressRows).map((row) => row.id)).toEqual([ - 'p100', - 'p90', - 'p20', - 'p0' - ]) -}) diff --git a/src/shared/sidebar-list/sections/project-section-parity.test-fixture.ts b/src/shared/sidebar-list/sections/project-section-parity.test-fixture.ts deleted file mode 100644 index aed686c0160..00000000000 --- a/src/shared/sidebar-list/sections/project-section-parity.test-fixture.ts +++ /dev/null @@ -1,249 +0,0 @@ -// Host answers both the desktop sidebar's and the phone's Project grouping tests run on. -import type { MobileProjectSectionCatalog } from '../../mobile-project-sections-contract' -import type { ExecutionHostId } from '../../execution-host' -import { - projectHostSetupProjectionFromRepos, - type ProjectHostSetupProjection -} from '../../project/host-setup/project-host-setup-projection' -import type { Repo } from '../../repository/repo-types' -import type { RuntimeClientTarget } from '../../remote-runtime/host-catalog/runtime-client-target' - -const orcaRemote = { - canonicalKey: 'github.com/stablyai/orca', - remoteName: 'origin', - remoteUrl: 'git@github.com:stablyai/orca.git' -} - -function hostRepo(id: string, path: string, displayName = 'orca'): Repo { - return { - id, - path, - displayName, - badgeColor: '#737373', - addedAt: 1, - ...(displayName === 'orca' ? { gitRemoteIdentity: orcaRemote } : {}) - } -} - -export type ParityHostAnswer = { - target: RuntimeClientTarget - hostId: ExecutionHostId - /** In the host's own repo.list order. */ - repos: Repo[] - /** The host's project.list/projectHostSetup.list rows; null for a host that predates them. */ - lists: ProjectHostSetupProjection | null -} - -const localRepos = [ - hostRepo('local-stably', '/Users/jinwoo/stably/orca'), - hostRepo('local-assets', '/Users/jinwoo/design-assets', 'design-assets'), - hostRepo('local-workspace', '/Users/jinwoo/orca/workspaces/orca/orca') -] -const windowsRepo = hostRepo('win-orca', 'C:/Users/jinwo/orca/orca') - -// Several local checkouts plus copies of the same project on two servers. -export const PROJECT_SECTION_PARITY_HOSTS: readonly ParityHostAnswer[] = [ - { - target: { kind: 'local' }, - hostId: 'local', - repos: localRepos, - lists: projectHostSetupProjectionFromRepos(localRepos) - }, - { - target: { kind: 'environment', environmentId: 'windows2' }, - hostId: 'runtime:windows2', - repos: [windowsRepo], - // A server's own catalog rows: its project name and an imported setup on its local host. - lists: { - projects: [ - { - id: 'github:stablyai/orca', - displayName: 'Orca', - badgeColor: '#737373', - providerIdentity: { provider: 'github', owner: 'stablyai', repo: 'orca' }, - sourceRepoIds: [windowsRepo.id], - createdAt: 5, - updatedAt: 5 - } - ], - setups: [ - { - id: 'win-setup', - projectId: 'github:stablyai/orca', - hostId: 'local', - repoId: windowsRepo.id, - path: windowsRepo.path, - displayName: 'orca', - setupState: 'ready', - setupMethod: 'imported-existing-folder', - createdAt: 5, - updatedAt: 5 - } - ] - } - }, - { - target: { kind: 'environment', environmentId: 'm4air' }, - hostId: 'runtime:m4air', - repos: [ - hostRepo('m4-orca', '/Users/m4air/orca/orca'), - hostRepo('m4-orca-two', '/Users/m4air/orca-two/orca') - ], - lists: null - } -] - -/** Workspace rows; activity order differs from catalog order, so Recent and Manual disagree. */ -export const PROJECT_SECTION_PARITY_ROWS: readonly { - id: string - repoId: string - lastActivityAt: number -}[] = [ - { id: 'wt-m4-two', repoId: 'm4-orca-two', lastActivityAt: 90 }, - { id: 'wt-win', repoId: 'win-orca', lastActivityAt: 70 }, - { id: 'wt-workspace', repoId: 'local-workspace', lastActivityAt: 50 }, - { id: 'wt-stably', repoId: 'local-stably', lastActivityAt: 30 }, - { id: 'wt-m4', repoId: 'm4-orca', lastActivityAt: 10 } -] - -// Same-host checkouts still need path prefixes; other machines do not. -const STABLY = { - key: 'project:github:stablyai/orca::setup:local-stably', - label: 'stably/orca' -} -const WORKSPACE = { - key: 'project:github:stablyai/orca::setup:local-workspace', - label: 'orca/orca' -} -// Why 'orca', not the server's 'Orca': the later host's derived project name wins the merge. -const WINDOWS = { key: 'project:github:stablyai/orca', label: 'orca' } -const M4 = { key: 'project:github:stablyai/orca::setup:m4-orca', label: 'orca/orca' } -const M4_TWO = { - key: 'project:github:stablyai/orca::setup:m4-orca-two', - label: 'orca-two/orca' -} -const ASSETS = { key: 'project:repo:local-assets', label: 'design-assets' } - -export const PROJECT_SECTION_PARITY_HEADERS = { - recent: [M4_TWO, WINDOWS, WORKSPACE, STABLY, M4, ASSETS], - manual: [STABLY, ASSETS, WORKSPACE, WINDOWS, M4, M4_TWO] -} as const - -/** What main serves the phone for these answers (the renderer's published catalog). */ -export const PROJECT_SECTION_PARITY_SERVED: MobileProjectSectionCatalog = { - repos: [ - { - id: 'local-stably', - displayName: 'orca', - path: '/Users/jinwoo/stably/orca', - badgeColor: '#737373', - addedAt: 1, - executionHostId: 'local' - }, - { - id: 'local-assets', - displayName: 'design-assets', - path: '/Users/jinwoo/design-assets', - badgeColor: '#737373', - addedAt: 1, - executionHostId: 'local' - }, - { - id: 'local-workspace', - displayName: 'orca', - path: '/Users/jinwoo/orca/workspaces/orca/orca', - badgeColor: '#737373', - addedAt: 1, - executionHostId: 'local' - }, - { - id: 'win-orca', - displayName: 'orca', - path: 'C:/Users/jinwo/orca/orca', - badgeColor: '#737373', - addedAt: 1, - executionHostId: 'runtime:windows2' - }, - { - id: 'm4-orca', - displayName: 'orca', - path: '/Users/m4air/orca/orca', - badgeColor: '#737373', - addedAt: 1, - executionHostId: 'runtime:m4air' - }, - { - id: 'm4-orca-two', - displayName: 'orca', - path: '/Users/m4air/orca-two/orca', - badgeColor: '#737373', - addedAt: 1, - executionHostId: 'runtime:m4air' - } - ], - projects: [ - { id: 'repo:local-assets', displayName: 'design-assets' }, - { id: 'github:stablyai/orca', displayName: 'orca' } - ], - setups: [ - { - id: 'local-stably', - projectId: 'github:stablyai/orca', - hostId: 'local', - repoId: 'local-stably', - path: '/Users/jinwoo/stably/orca', - displayName: 'orca', - setupMethod: 'legacy-repo' - }, - { - id: 'local-assets', - projectId: 'repo:local-assets', - hostId: 'local', - repoId: 'local-assets', - path: '/Users/jinwoo/design-assets', - displayName: 'design-assets', - setupMethod: 'legacy-repo' - }, - { - id: 'local-workspace', - projectId: 'github:stablyai/orca', - hostId: 'local', - repoId: 'local-workspace', - path: '/Users/jinwoo/orca/workspaces/orca/orca', - displayName: 'orca', - setupMethod: 'legacy-repo' - }, - { - id: 'win-setup', - projectId: 'github:stablyai/orca', - hostId: 'runtime:windows2', - repoId: 'win-orca', - path: 'C:/Users/jinwo/orca/orca', - displayName: 'orca', - setupMethod: 'imported-existing-folder', - connectionId: null, - executionHostId: 'runtime:windows2' - }, - { - id: 'm4-orca', - projectId: 'github:stablyai/orca', - hostId: 'runtime:m4air', - repoId: 'm4-orca', - path: '/Users/m4air/orca/orca', - displayName: 'orca', - setupMethod: 'legacy-repo', - executionHostId: 'runtime:m4air' - }, - { - id: 'm4-orca-two', - projectId: 'github:stablyai/orca', - hostId: 'runtime:m4air', - repoId: 'm4-orca-two', - path: '/Users/m4air/orca-two/orca', - displayName: 'orca', - setupMethod: 'legacy-repo', - executionHostId: 'runtime:m4air' - } - ], - projectOrderBy: 'manual' -} diff --git a/src/shared/work-items/task-query.test.ts b/src/shared/work-items/task-query.test.ts deleted file mode 100644 index 9af615a88dc..00000000000 --- a/src/shared/work-items/task-query.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - hasExplicitTaskScope, - parseTaskQuery, - serializeTaskQuery, - stripRepoQualifiers -} from './task-query' - -describe('hasExplicitTaskScope', () => { - it('recognizes scope qualifiers and their quoted values', () => { - for (const query of ['is:issue', 'IS:PR', 'is:pull-request', 'is:"pr"']) { - expect(hasExplicitTaskScope(query)).toBe(true) - } - }) - - it('keeps quoted phrases and values of other qualifiers as search text', () => { - for (const query of ['"is:pr"', "'is:issue'", 'label:is:pr', 'title:"is:pull-request"']) { - expect(hasExplicitTaskScope(query)).toBe(false) - expect(parseTaskQuery(query).scope).toBe('all') - } - }) -}) - -describe('parseTaskQuery', () => { - it('widens scope to all regardless of issue and PR token order', () => { - const parsed = parseTaskQuery('is:pr is:issue') - expect(parsed.scope).toBe('all') - }) - - it('keeps draft scoped to open PRs even when a later token says issue', () => { - const parsed = parseTaskQuery('is:draft is:issue') - expect(parsed.scope).toBe('pr') - expect(parsed.state).toBe('open') - expect(parsed.draft).toBe(true) - }) - - it('extracts assignee, author, label, and review qualifiers', () => { - const parsed = parseTaskQuery( - 'assignee:@me author:alice author:bob review-requested:@me label:bug free text' - ) - expect(parsed.assignee).toBe('@me') - expect(parsed.authors).toEqual(['alice', 'bob']) - expect(parsed.reviewRequested).toBe('@me') - expect(parsed.scope).toBe('pr') // review-requested forces pr - expect(parsed.labels).toEqual(['bug']) - expect(parsed.freeText).toBe('free text') - }) - - it('keeps review qualifiers scoped to PRs even when a later token says issue', () => { - const parsed = parseTaskQuery('review-requested:@me is:issue') - expect(parsed.scope).toBe('pr') - expect(parsed.reviewRequested).toBe('@me') - }) -}) - -describe('stripRepoQualifiers', () => { - it('re-quotes a standalone token that contains whitespace', () => { - // Re-quote standalone phrases or serialization would split them into separate search tokens. - const stripped = stripRepoQualifiers('"needs review" repo:x/y') - expect(stripped).toBe('"needs review"') - }) -}) - -describe('serializeTaskQuery', () => { - it('quotes label values containing whitespace', () => { - const parsed = parseTaskQuery('label:"needs review"') - expect(parsed.labels).toEqual(['needs review']) - expect(parsed.freeText).toBe('') - expect(serializeTaskQuery(parsed)).toContain('label:"needs review"') - }) - - it('serializes all state so filter changes do not fall back to the default open state', () => { - const raw = serializeTaskQuery(parseTaskQuery('is:pr state:all')) - expect(raw).toBe('is:pr state:all') - }) -}) diff --git a/src/shared/workspace-layout/commands/workspace-layout-ratio-commands.test.ts b/src/shared/workspace-layout/commands/workspace-layout-ratio-commands.test.ts deleted file mode 100644 index 7ebcdf77cae..00000000000 --- a/src/shared/workspace-layout/commands/workspace-layout-ratio-commands.test.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { applyLayoutCommand } from '../workspace-layout-commands' -import type { LayoutCommand } from '../workspace-layout-command-types' -import { build, terminalTab, testContext, WS } from './workspace-layout-command.test-fixture' -import type { WorkspaceLayoutModel } from '../workspace-layout-model' - -const context = testContext() - -function setup() { - const ctx = testContext() - const { model, results } = build(ctx, [ - { type: 'createTerminalTab', workspace: WS }, - { type: 'createTerminalTab', workspace: WS } - ]) - const [first, second] = results - const split = build( - ctx, - [ - { - type: 'splitPane', - workspace: WS, - tabId: first!.tabId!, - leafId: first!.leafId!, - direction: 'vertical' - } - ], - model - ) - return { - ctx, - model: split.model, - tabA: first!.tabId!, - leafA: first!.leafId!, - leafA2: split.results[0]!.leafId!, - tabB: second!.tabId! - } -} - -function refusal(model: WorkspaceLayoutModel, command: LayoutCommand) { - const result = applyLayoutCommand(model, command, context) - return result.ok ? 'applied' : result.code -} - -describe('divider ratios through main', () => { - it('setPaneRatios applies divider intents to main’s own tree, and refuses a path with no split', () => { - const { model, tabA } = setup() - const applied = applyLayoutCommand( - model, - { type: 'setPaneRatios', workspace: WS, tabId: tabA, ratios: [{ path: '', ratio: 0.3 }] }, - context - ) - expect(applied.ok && terminalTab(applied.model, tabA).panes!.root).toMatchObject({ - type: 'split', - ratio: 0.3 - }) - // Back to even is saved as no ratio, as the window saves it. - const even = applied.ok - ? applyLayoutCommand( - applied.model, - { type: 'setPaneRatios', workspace: WS, tabId: tabA, ratios: [{ path: '', ratio: 0.5 }] }, - context - ) - : applied - expect(even.ok && terminalTab(even.model, tabA).panes!.root).not.toHaveProperty('ratio') - expect( - refusal(model, { - type: 'setPaneRatios', - workspace: WS, - tabId: tabA, - ratios: [{ path: 'first', ratio: 0.3 }] - }) - ).toBe('pane_structure_changed') - }) - - it('setGroupRatios applies divider intents to main’s own groups, and refuses a path with no split', () => { - const { model, tabB } = setup() - const groupId = model.workspaces[WS]!.groups[0]!.id - const split = applyLayoutCommand( - model, - { - type: 'splitGroup', - workspace: WS, - tabId: tabB, - besideGroupId: groupId, - direction: 'right' - }, - context - ) - if (!split.ok) { - throw new Error('expected a group split') - } - const applied = applyLayoutCommand( - split.model, - { type: 'setGroupRatios', workspace: WS, ratios: [{ path: '', ratio: 0.7 }] }, - context - ) - expect(applied.ok && applied.model.workspaces[WS]!.groupLayout).toMatchObject({ - type: 'split', - ratio: 0.7 - }) - expect( - refusal(split.model, { - type: 'setGroupRatios', - workspace: WS, - ratios: [{ path: 'second', ratio: 0.7 }] - }) - ).toBe('group_set_changed') - expect( - refusal(model, { type: 'setGroupRatios', workspace: WS, ratios: [{ path: '', ratio: 0.7 }] }) - ).toBe('group_set_changed') - }) - - it('applies an intent only to the split it means: a path now naming another split moves nothing', () => { - const { model, tabA, leafA, leafA2 } = setup() - const before = terminalTab(model, tabA).panes!.root - const meant = { direction: 'vertical', first: leafA, second: leafA2 } - expect( - refusal(model, { - type: 'setPaneRatios', - workspace: WS, - tabId: tabA, - ratios: [{ path: '', ratio: 0.3, split: meant }] - }) - ).toBe('applied') - // Main's panes moved on: the root split is now another one. - for (const split of [ - { ...meant, first: leafA2, second: leafA }, - { ...meant, direction: 'horizontal' } - ]) { - const refused = applyLayoutCommand( - model, - { - type: 'setPaneRatios', - workspace: WS, - tabId: tabA, - ratios: [{ path: '', ratio: 0.3, split }] - }, - context - ) - expect(refused.ok ? 'applied' : refused.code).toBe('pane_structure_changed') - expect(terminalTab(model, tabA).panes!.root).toEqual(before) - } - }) -})