From 69978c93f58b1ed7e8d6c4da81edc73fc4243ee5 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Wed, 25 Mar 2026 22:34:20 -0700 Subject: [PATCH] test: expand test coverage and extract worktree logic into testable module (#108) Add comprehensive tests for worktree parsing, GitHub check status derivation, hooks YAML parsing, persistence store, layout serialization, store cascades, and terminal helpers. Extract pure functions from worktrees.ts into worktree-logic.ts for better testability. Co-authored-by: Claude Opus 4.6 --- src/main/git/worktree.test.ts | 128 +++++++ src/main/github/client.test.ts | 180 +++++++++- src/main/github/client.ts | 4 +- src/main/hooks.test.ts | 163 +++++++++ src/main/hooks.ts | 2 +- src/main/ipc/worktree-logic.test.ts | 256 ++++++++++++++ src/main/ipc/worktree-logic.ts | 147 ++++++++ src/main/ipc/worktrees.ts | 121 ++----- src/main/persistence.test.ts | 319 ++++++++++++++++++ .../terminal-pane/keyboard-handlers.ts | 4 +- .../layout-serialization.test.ts | 246 ++++++++++++++ src/renderer/src/lib/agent-status.test.ts | 125 ++++++- .../src/store/slices/store-cascades.test.ts | 296 ++++++++++++++++ .../slices/store-session-cascades.test.ts | 258 ++++++++++++++ .../src/store/slices/terminal-helpers.test.ts | 72 ++++ 15 files changed, 2212 insertions(+), 109 deletions(-) create mode 100644 src/main/hooks.test.ts create mode 100644 src/main/ipc/worktree-logic.test.ts create mode 100644 src/main/ipc/worktree-logic.ts create mode 100644 src/main/persistence.test.ts create mode 100644 src/renderer/src/components/terminal-pane/layout-serialization.test.ts create mode 100644 src/renderer/src/store/slices/store-cascades.test.ts create mode 100644 src/renderer/src/store/slices/store-session-cascades.test.ts create mode 100644 src/renderer/src/store/slices/terminal-helpers.test.ts diff --git a/src/main/git/worktree.test.ts b/src/main/git/worktree.test.ts index b91876441..e86cf37bb 100644 --- a/src/main/git/worktree.test.ts +++ b/src/main/git/worktree.test.ts @@ -38,4 +38,132 @@ bare } ]) }) + + it('returns empty array for empty string input', () => { + expect(parseWorktreeList('')).toEqual([]) + }) + + it('returns empty array for whitespace-only input', () => { + expect(parseWorktreeList(' \n\n \n ')).toEqual([]) + }) + + it('parses a single worktree block', () => { + const output = `worktree /single-repo +HEAD aaa111 +branch refs/heads/main +` + expect(parseWorktreeList(output)).toEqual([ + { + path: '/single-repo', + head: 'aaa111', + branch: 'refs/heads/main', + isBare: false + } + ]) + }) + + it('parses a detached HEAD worktree (no branch line)', () => { + const output = `worktree /repo-detached +HEAD abc123 +detached +` + expect(parseWorktreeList(output)).toEqual([ + { + path: '/repo-detached', + head: 'abc123', + branch: '', + isBare: false + } + ]) + }) + + it('handles extra blank lines between blocks', () => { + const output = `worktree /repo-a +HEAD aaa111 +branch refs/heads/main + + +worktree /repo-b +HEAD bbb222 +branch refs/heads/dev +` + expect(parseWorktreeList(output)).toEqual([ + { + path: '/repo-a', + head: 'aaa111', + branch: 'refs/heads/main', + isBare: false + }, + { + path: '/repo-b', + head: 'bbb222', + branch: 'refs/heads/dev', + isBare: false + } + ]) + }) + + it('returns entry with empty head when HEAD line is missing', () => { + const output = `worktree /repo-no-head +branch refs/heads/main +` + expect(parseWorktreeList(output)).toEqual([ + { + path: '/repo-no-head', + head: '', + branch: 'refs/heads/main', + isBare: false + } + ]) + }) + + it('correctly captures worktree path with spaces', () => { + const output = `worktree /path/to/my worktree +HEAD ccc333 +branch refs/heads/main +` + expect(parseWorktreeList(output)).toEqual([ + { + path: '/path/to/my worktree', + head: 'ccc333', + branch: 'refs/heads/main', + isBare: false + } + ]) + }) + + it('parses multiple bare entries mixed with regular entries', () => { + const output = `worktree /bare-one +HEAD 0000000 +bare + +worktree /regular +HEAD abc123 +branch refs/heads/main + +worktree /bare-two +HEAD 1111111 +bare +` + expect(parseWorktreeList(output)).toEqual([ + { + path: '/bare-one', + head: '0000000', + branch: '', + isBare: true + }, + { + path: '/regular', + head: 'abc123', + branch: 'refs/heads/main', + isBare: false + }, + { + path: '/bare-two', + head: '1111111', + branch: '', + isBare: true + } + ]) + }) }) diff --git a/src/main/github/client.test.ts b/src/main/github/client.test.ts index 37b6709cc..9ae29bd4d 100644 --- a/src/main/github/client.test.ts +++ b/src/main/github/client.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { deriveCheckStatus, mapPRState } from './client' +import { deriveCheckStatus, mapPRState, mapCheckStatus, mapCheckConclusion } from './client' describe('mapPRState', () => { it('returns draft when an open PR is marked as draft', () => { @@ -11,6 +11,24 @@ describe('mapPRState', () => { expect(mapPRState('CLOSED', true)).toBe('closed') expect(mapPRState('OPEN')).toBe('open') }) + + it('handles lowercase inputs', () => { + expect(mapPRState('merged')).toBe('merged') + expect(mapPRState('closed')).toBe('closed') + expect(mapPRState('open')).toBe('open') + }) + + it('returns open for undefined state', () => { + expect(mapPRState(undefined as unknown as string)).toBe('open') + }) + + it('returns open for null state', () => { + expect(mapPRState(null as unknown as string)).toBe('open') + }) + + it('returns open for unknown state', () => { + expect(mapPRState('UNKNOWN')).toBe('open') + }) }) describe('deriveCheckStatus', () => { @@ -19,6 +37,10 @@ describe('deriveCheckStatus', () => { expect(deriveCheckStatus([])).toBe('neutral') }) + it('returns neutral for undefined input', () => { + expect(deriveCheckStatus(undefined)).toBe('neutral') + }) + it('returns failure when a failed check is present', () => { expect(deriveCheckStatus([{ status: 'QUEUED' }, { conclusion: 'FAILURE' }])).toBe('failure') }) @@ -32,4 +54,160 @@ describe('deriveCheckStatus', () => { 'success' ) }) + + it('returns failure when mixed success and failure', () => { + expect(deriveCheckStatus([{ conclusion: 'SUCCESS' }, { conclusion: 'FAILURE' }])).toBe( + 'failure' + ) + }) + + it('returns pending when mixed success and pending', () => { + expect(deriveCheckStatus([{ conclusion: 'SUCCESS' }, { status: 'QUEUED' }])).toBe('pending') + }) + + it('returns success when all checks succeed', () => { + expect( + deriveCheckStatus([ + { conclusion: 'SUCCESS' }, + { conclusion: 'SUCCESS' }, + { conclusion: 'SUCCESS' } + ]) + ).toBe('success') + }) + + it('returns failure when a single failure is among many successes', () => { + expect( + deriveCheckStatus([ + { conclusion: 'SUCCESS' }, + { conclusion: 'SUCCESS' }, + { conclusion: 'FAILURE' }, + { conclusion: 'SUCCESS' } + ]) + ).toBe('failure') + }) + + it('returns failure for TIMED_OUT conclusion', () => { + expect(deriveCheckStatus([{ conclusion: 'SUCCESS' }, { conclusion: 'TIMED_OUT' }])).toBe( + 'failure' + ) + }) + + it('returns failure for CANCELLED conclusion', () => { + expect(deriveCheckStatus([{ conclusion: 'CANCELLED' }])).toBe('failure') + }) + + it('handles checks with state field instead of conclusion (FAILURE)', () => { + expect(deriveCheckStatus([{ state: 'FAILURE' }])).toBe('failure') + }) + + it('handles checks with state field instead of conclusion (ERROR)', () => { + expect(deriveCheckStatus([{ state: 'ERROR' }])).toBe('failure') + }) + + it('handles checks with state field PENDING', () => { + expect(deriveCheckStatus([{ state: 'PENDING' }])).toBe('pending') + }) + + it('returns pending for QUEUED status', () => { + expect(deriveCheckStatus([{ status: 'QUEUED' }])).toBe('pending') + }) + + it('returns pending for PENDING status', () => { + expect(deriveCheckStatus([{ status: 'PENDING' }])).toBe('pending') + }) + + it('failure takes priority over pending', () => { + expect( + deriveCheckStatus([ + { status: 'IN_PROGRESS' }, + { conclusion: 'FAILURE' }, + { conclusion: 'SUCCESS' } + ]) + ).toBe('failure') + }) +}) + +describe('mapCheckStatus', () => { + it('maps PENDING to queued', () => { + expect(mapCheckStatus('PENDING')).toBe('queued') + }) + + it('maps QUEUED to queued', () => { + expect(mapCheckStatus('QUEUED')).toBe('queued') + }) + + it('maps IN_PROGRESS to in_progress', () => { + expect(mapCheckStatus('IN_PROGRESS')).toBe('in_progress') + }) + + it('maps SUCCESS to completed', () => { + expect(mapCheckStatus('SUCCESS')).toBe('completed') + }) + + it('maps any other value to completed', () => { + expect(mapCheckStatus('FAILURE')).toBe('completed') + expect(mapCheckStatus('UNKNOWN')).toBe('completed') + }) + + it('handles lowercase inputs', () => { + expect(mapCheckStatus('pending')).toBe('queued') + expect(mapCheckStatus('in_progress')).toBe('in_progress') + }) +}) + +describe('mapCheckConclusion', () => { + it('maps SUCCESS to success', () => { + expect(mapCheckConclusion('SUCCESS')).toBe('success') + }) + + it('maps PASS to success', () => { + expect(mapCheckConclusion('PASS')).toBe('success') + }) + + it('maps FAILURE to failure', () => { + expect(mapCheckConclusion('FAILURE')).toBe('failure') + }) + + it('maps FAIL to failure', () => { + expect(mapCheckConclusion('FAIL')).toBe('failure') + }) + + it('maps CANCELLED to cancelled', () => { + expect(mapCheckConclusion('CANCELLED')).toBe('cancelled') + }) + + it('maps TIMED_OUT to timed_out', () => { + expect(mapCheckConclusion('TIMED_OUT')).toBe('timed_out') + }) + + it('maps SKIPPED to skipped', () => { + expect(mapCheckConclusion('SKIPPED')).toBe('skipped') + }) + + it('maps PENDING to pending', () => { + expect(mapCheckConclusion('PENDING')).toBe('pending') + }) + + it('maps QUEUED to pending', () => { + expect(mapCheckConclusion('QUEUED')).toBe('pending') + }) + + it('maps IN_PROGRESS to pending', () => { + expect(mapCheckConclusion('IN_PROGRESS')).toBe('pending') + }) + + it('maps NEUTRAL to neutral', () => { + expect(mapCheckConclusion('NEUTRAL')).toBe('neutral') + }) + + it('returns null for unknown values', () => { + expect(mapCheckConclusion('UNKNOWN')).toBeNull() + expect(mapCheckConclusion('FOO')).toBeNull() + }) + + it('handles lowercase inputs', () => { + expect(mapCheckConclusion('success')).toBe('success') + expect(mapCheckConclusion('failure')).toBe('failure') + expect(mapCheckConclusion('pending')).toBe('pending') + }) }) diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 2bac7ba95..7601546dc 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -185,7 +185,7 @@ export async function updatePRTitle( } } -function mapCheckStatus(state: string): PRCheckDetail['status'] { +export function mapCheckStatus(state: string): PRCheckDetail['status'] { const s = state?.toUpperCase() if (s === 'PENDING' || s === 'QUEUED') { return 'queued' @@ -196,7 +196,7 @@ function mapCheckStatus(state: string): PRCheckDetail['status'] { return 'completed' } -function mapCheckConclusion(state: string): PRCheckDetail['conclusion'] { +export function mapCheckConclusion(state: string): PRCheckDetail['conclusion'] { const s = state?.toUpperCase() if (s === 'SUCCESS' || s === 'PASS') { return 'success' diff --git a/src/main/hooks.test.ts b/src/main/hooks.test.ts new file mode 100644 index 000000000..2f48bff92 --- /dev/null +++ b/src/main/hooks.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it, vi } from 'vitest' +import { parseOrcaYaml } from './hooks' + +// Mock fs and path used by loadHooks +vi.mock('fs', () => ({ + readFileSync: vi.fn(), + existsSync: vi.fn() +})) + +describe('parseOrcaYaml', () => { + it('parses YAML with setup script only', () => { + const yaml = `scripts:\n setup: |\n echo "setting up"\n npm install\n` + const result = parseOrcaYaml(yaml) + expect(result).toEqual({ + scripts: { + setup: 'echo "setting up"\nnpm install' + } + }) + }) + + it('parses YAML with archive script only', () => { + const yaml = `scripts:\n archive: |\n echo "archiving"\n` + const result = parseOrcaYaml(yaml) + expect(result).toEqual({ + scripts: { + archive: 'echo "archiving"' + } + }) + }) + + it('parses YAML with both setup and archive', () => { + const yaml = [ + 'scripts:', + ' setup: |', + ' echo "setup"', + ' npm install', + ' archive: |', + ' echo "archive"', + ' rm -rf node_modules' + ].join('\n') + const result = parseOrcaYaml(yaml) + expect(result).toEqual({ + scripts: { + setup: 'echo "setup"\nnpm install', + archive: 'echo "archive"\nrm -rf node_modules' + } + }) + }) + + it('returns null when there is no scripts block', () => { + const yaml = `other:\n key: value\n` + expect(parseOrcaYaml(yaml)).toBeNull() + }) + + it('returns null when scripts block has no setup or archive', () => { + const yaml = `scripts:\n unknown: |\n echo "nope"\n` + expect(parseOrcaYaml(yaml)).toBeNull() + }) + + it('handles multiline block scalar scripts', () => { + const yaml = ['scripts:', ' setup: |', ' line1', ' line2', ' line3'].join('\n') + const result = parseOrcaYaml(yaml) + expect(result).toEqual({ + scripts: { + setup: 'line1\nline2\nline3' + } + }) + }) + + it('stops parsing when it hits another top-level key', () => { + const yaml = ['scripts:', ' setup: |', ' echo "setup"', 'other:', ' key: value'].join('\n') + const result = parseOrcaYaml(yaml) + expect(result).toEqual({ + scripts: { + setup: 'echo "setup"' + } + }) + }) + + it('returns null for empty string', () => { + expect(parseOrcaYaml('')).toBeNull() + }) +}) + +describe('getEffectiveHooks', () => { + // We need to dynamically import after mocking + const makeRepo = (hookSettings?: { + mode: 'auto' | 'override' + scripts: { setup: string; archive: string } + }) => ({ + id: 'test-id', + path: '/test/repo', + displayName: 'Test Repo', + badgeColor: '#000', + addedAt: Date.now(), + hookSettings + }) + + it('auto mode with yaml hooks uses yaml hooks', async () => { + const fs = await import('fs') + vi.mocked(fs.existsSync).mockReturnValue(true) + vi.mocked(fs.readFileSync).mockReturnValue('scripts:\n setup: |\n echo "yaml setup"\n') + + // Re-import to pick up mocks + const { getEffectiveHooks } = await import('./hooks') + const repo = makeRepo({ mode: 'auto', scripts: { setup: '', archive: '' } }) + const result = getEffectiveHooks(repo) + + expect(result).toEqual({ + scripts: { + setup: 'echo "yaml setup"' + } + }) + }) + + it('auto mode with no yaml hooks but UI scripts uses UI scripts', async () => { + const fs = await import('fs') + vi.mocked(fs.existsSync).mockReturnValue(false) + + const { getEffectiveHooks } = await import('./hooks') + const repo = makeRepo({ + mode: 'auto', + scripts: { setup: 'echo "ui setup"', archive: '' } + }) + const result = getEffectiveHooks(repo) + + expect(result).toEqual({ + scripts: { + setup: 'echo "ui setup"' + } + }) + }) + + it('override mode always uses UI scripts, ignores yaml', async () => { + const fs = await import('fs') + vi.mocked(fs.existsSync).mockReturnValue(true) + vi.mocked(fs.readFileSync).mockReturnValue('scripts:\n setup: |\n echo "yaml setup"\n') + + const { getEffectiveHooks } = await import('./hooks') + const repo = makeRepo({ + mode: 'override', + scripts: { setup: 'echo "ui override"', archive: '' } + }) + const result = getEffectiveHooks(repo) + + expect(result).toEqual({ + scripts: { + setup: 'echo "ui override"' + } + }) + }) + + it('returns null when no hooks at all', async () => { + const fs = await import('fs') + vi.mocked(fs.existsSync).mockReturnValue(false) + + const { getEffectiveHooks } = await import('./hooks') + const repo = makeRepo({ mode: 'auto', scripts: { setup: '', archive: '' } }) + const result = getEffectiveHooks(repo) + + expect(result).toBeNull() + }) +}) diff --git a/src/main/hooks.ts b/src/main/hooks.ts index f5433e2ac..932840875 100644 --- a/src/main/hooks.ts +++ b/src/main/hooks.ts @@ -11,7 +11,7 @@ type HookName = keyof OrcaHooks['scripts'] * Parse a simple orca.yaml file. Handles only the `scripts:` block with * multiline string values (YAML block scalar `|`). */ -function parseOrcaYaml(content: string): OrcaHooks | null { +export function parseOrcaYaml(content: string): OrcaHooks | null { const hooks: OrcaHooks = { scripts: {} } // Match top-level "scripts:" block diff --git a/src/main/ipc/worktree-logic.test.ts b/src/main/ipc/worktree-logic.test.ts new file mode 100644 index 000000000..ecc568fc0 --- /dev/null +++ b/src/main/ipc/worktree-logic.test.ts @@ -0,0 +1,256 @@ +import { join } from 'path' +import { describe, expect, it } from 'vitest' +import { + sanitizeWorktreeName, + ensurePathWithinWorkspace, + computeBranchName, + computeWorktreePath, + shouldSetDisplayName, + mergeWorktree, + parseWorktreeId, + formatWorktreeRemovalError +} from './worktree-logic' + +describe('sanitizeWorktreeName', () => { + it('replaces spaces with hyphens', () => { + expect(sanitizeWorktreeName('my feature')).toBe('my-feature') + }) + + it('collapses multiple spaces to a single hyphen', () => { + expect(sanitizeWorktreeName('my big feature')).toBe('my-big-feature') + }) + + it('trims leading and trailing whitespace', () => { + expect(sanitizeWorktreeName(' padded name ')).toBe('padded-name') + }) + + it('returns the name unchanged when there are no spaces', () => { + expect(sanitizeWorktreeName('no-spaces')).toBe('no-spaces') + }) + + it('strips unsafe characters', () => { + expect(sanitizeWorktreeName('feat@#$ure')).toBe('feat-ure') + }) + + it('collapses consecutive hyphens', () => { + expect(sanitizeWorktreeName('a---b')).toBe('a-b') + }) + + it('strips leading/trailing dots and hyphens', () => { + expect(sanitizeWorktreeName('.hidden-')).toBe('hidden') + }) + + it('throws for empty name', () => { + expect(() => sanitizeWorktreeName('')).toThrow('Invalid worktree name') + }) + + it('throws for whitespace-only name', () => { + expect(() => sanitizeWorktreeName(' ')).toThrow('Invalid worktree name') + }) +}) + +describe('ensurePathWithinWorkspace', () => { + it('returns resolved path when within workspace', () => { + const result = ensurePathWithinWorkspace('/workspace/feature', '/workspace') + expect(result).toBe('/workspace/feature') + }) + + it('throws when path traverses outside workspace', () => { + expect(() => ensurePathWithinWorkspace('/workspace/../outside', '/workspace')).toThrow( + 'Invalid worktree path' + ) + }) +}) + +describe('computeBranchName', () => { + it('prefixes with git username when branchPrefix is git-username and username is present', () => { + expect(computeBranchName('feature', { branchPrefix: 'git-username' }, 'jdoe')).toBe( + 'jdoe/feature' + ) + }) + + it('returns bare name when branchPrefix is git-username but username is null', () => { + expect(computeBranchName('feature', { branchPrefix: 'git-username' }, null)).toBe('feature') + }) + + it('prefixes with custom value when branchPrefix is custom', () => { + expect( + computeBranchName('feature', { branchPrefix: 'custom', branchPrefixCustom: 'team' }, null) + ).toBe('team/feature') + }) + + it('returns bare name when branchPrefix is custom but custom value is empty', () => { + expect( + computeBranchName('feature', { branchPrefix: 'custom', branchPrefixCustom: '' }, null) + ).toBe('feature') + }) + + it('returns bare name when branchPrefix is none', () => { + expect(computeBranchName('feature', { branchPrefix: 'none' }, 'jdoe')).toBe('feature') + }) +}) + +describe('computeWorktreePath', () => { + it('nests under repo name when nestWorkspaces is true', () => { + expect( + computeWorktreePath('feature', '/repos/my-project', { + nestWorkspaces: true, + workspaceDir: '/workspaces' + }) + ).toBe(join('/workspaces', 'my-project', 'feature')) + }) + + it('uses flat layout when nestWorkspaces is false', () => { + expect( + computeWorktreePath('feature', '/repos/my-project', { + nestWorkspaces: false, + workspaceDir: '/workspaces' + }) + ).toBe(join('/workspaces', 'feature')) + }) + + it('strips .git suffix from repo path when nesting', () => { + expect( + computeWorktreePath('feature', '/repos/my-project.git', { + nestWorkspaces: true, + workspaceDir: '/workspaces' + }) + ).toBe(join('/workspaces', 'my-project', 'feature')) + }) +}) + +describe('shouldSetDisplayName', () => { + it('returns false when requestedName matches both branchName and sanitizedName', () => { + expect(shouldSetDisplayName('feature', 'feature', 'feature')).toBe(false) + }) + + it('returns true when requestedName differs from sanitizedName (had spaces)', () => { + expect(shouldSetDisplayName('my feature', 'my-feature', 'my-feature')).toBe(true) + }) + + it('returns true when branchName differs due to prefix', () => { + expect(shouldSetDisplayName('feature', 'jdoe/feature', 'feature')).toBe(true) + }) +}) + +describe('mergeWorktree', () => { + const baseGit = { + path: '/workspaces/feature', + head: 'abc123', + branch: 'refs/heads/feature-x', + isBare: false + } + + it('merges with full metadata', () => { + const meta = { + displayName: 'My Feature', + comment: 'WIP', + linkedIssue: 42, + linkedPR: 10, + isArchived: true, + isUnread: true, + sortOrder: 5 + } + const result = mergeWorktree('repo1', baseGit, meta) + expect(result).toEqual({ + id: 'repo1::/workspaces/feature', + repoId: 'repo1', + path: '/workspaces/feature', + head: 'abc123', + branch: 'refs/heads/feature-x', + isBare: false, + displayName: 'My Feature', + comment: 'WIP', + linkedIssue: 42, + linkedPR: 10, + isArchived: true, + isUnread: true, + sortOrder: 5 + }) + }) + + it('uses defaults when metadata is undefined', () => { + const result = mergeWorktree('repo1', baseGit, undefined) + expect(result.displayName).toBe('feature-x') + expect(result.comment).toBe('') + expect(result.linkedIssue).toBeNull() + expect(result.linkedPR).toBeNull() + expect(result.isArchived).toBe(false) + expect(result.isUnread).toBe(false) + expect(result.sortOrder).toBe(0) + }) + + it('strips refs/heads/ prefix from branch for display name', () => { + const result = mergeWorktree('repo1', baseGit, undefined) + expect(result.displayName).toBe('feature-x') + }) + + it('falls back to basename when bare worktree has no branch', () => { + const bareGit = { + path: '/workspaces/bare-repo', + head: '000000', + branch: '', + isBare: true + } + const result = mergeWorktree('repo1', bareGit, undefined) + expect(result.displayName).toBe('bare-repo') + }) +}) + +describe('parseWorktreeId', () => { + it('parses valid "repoId::path" format', () => { + expect(parseWorktreeId('repo1::/workspaces/feature')).toEqual({ + repoId: 'repo1', + worktreePath: '/workspaces/feature' + }) + }) + + it('handles paths containing colons', () => { + expect(parseWorktreeId('repo1::C:/Users/test')).toEqual({ + repoId: 'repo1', + worktreePath: 'C:/Users/test' + }) + }) + + it('throws on invalid format without ::', () => { + expect(() => parseWorktreeId('invalid-id')).toThrow('Invalid worktreeId: invalid-id') + }) +}) + +describe('formatWorktreeRemovalError', () => { + const path = '/workspaces/feature' + + it('returns fallback for non-Error input', () => { + expect(formatWorktreeRemovalError('oops', path, false)).toBe( + `Failed to delete worktree at ${path}.` + ) + }) + + it('includes stderr when present on Error', () => { + const error = Object.assign(new Error('generic'), { stderr: 'branch not clean' }) + expect(formatWorktreeRemovalError(error, path, false)).toBe( + `Failed to delete worktree at ${path}. branch not clean` + ) + }) + + it('falls back to message when no stderr/stdout', () => { + const error = new Error('something went wrong') + expect(formatWorktreeRemovalError(error, path, false)).toBe( + `Failed to delete worktree at ${path}. something went wrong` + ) + }) + + it('uses force text when force is true', () => { + expect(formatWorktreeRemovalError('oops', path, true)).toBe( + `Failed to force delete worktree at ${path}.` + ) + }) + + it('returns fallback when Error has empty message and no streams', () => { + const error = new Error(' ') + error.message = '' + expect(formatWorktreeRemovalError(error, path, false)).toBe( + `Failed to delete worktree at ${path}.` + ) + }) +}) diff --git a/src/main/ipc/worktree-logic.ts b/src/main/ipc/worktree-logic.ts new file mode 100644 index 000000000..48b8e7a1b --- /dev/null +++ b/src/main/ipc/worktree-logic.ts @@ -0,0 +1,147 @@ +import { basename, join, resolve, relative, isAbsolute } from 'path' +import type { Worktree, WorktreeMeta } from '../../shared/types' + +/** + * Sanitize a worktree name for use in branch names and directory paths. + * Strips unsafe characters and collapses runs of special chars to a single hyphen. + */ +export function sanitizeWorktreeName(input: string): string { + const sanitized = input + .trim() + .replace(/[\\/]+/g, '-') + .replace(/\s+/g, '-') + .replace(/[^A-Za-z0-9._-]+/g, '-') + .replace(/-+/g, '-') + .replace(/^[.-]+|[.-]+$/g, '') + + if (!sanitized || sanitized === '.' || sanitized === '..') { + throw new Error('Invalid worktree name') + } + + return sanitized +} + +/** + * Ensure a target path is within the workspace directory (prevent path traversal). + */ +export function ensurePathWithinWorkspace(targetPath: string, workspaceDir: string): string { + const resolvedWorkspaceDir = resolve(workspaceDir) + const resolvedTargetPath = resolve(targetPath) + const rel = relative(resolvedWorkspaceDir, resolvedTargetPath) + + if (isAbsolute(rel) || rel.startsWith('..')) { + throw new Error('Invalid worktree path') + } + + return resolvedTargetPath +} + +/** + * Compute the full branch name by applying the configured prefix strategy. + */ +export function computeBranchName( + sanitizedName: string, + settings: { branchPrefix: string; branchPrefixCustom?: string }, + gitUsername: string | null +): string { + if (settings.branchPrefix === 'git-username') { + if (gitUsername) { + return `${gitUsername}/${sanitizedName}` + } + } else if (settings.branchPrefix === 'custom' && settings.branchPrefixCustom) { + return `${settings.branchPrefixCustom}/${sanitizedName}` + } + return sanitizedName +} + +/** + * Compute the filesystem path where the worktree directory will be created. + */ +export function computeWorktreePath( + sanitizedName: string, + repoPath: string, + settings: { nestWorkspaces: boolean; workspaceDir: string } +): string { + if (settings.nestWorkspaces) { + const repoName = basename(repoPath).replace(/\.git$/, '') + return join(settings.workspaceDir, repoName, sanitizedName) + } + return join(settings.workspaceDir, sanitizedName) +} + +/** + * Determine whether a display name should be persisted. + * A display name is set only when the user's requested name differs from + * both the branch name and the sanitized name (i.e. it was modified). + */ +export function shouldSetDisplayName( + requestedName: string, + branchName: string, + sanitizedName: string +): boolean { + return !(branchName === requestedName && sanitizedName === requestedName) +} + +/** + * Merge raw git worktree info with persisted user metadata into a full Worktree. + */ +export function mergeWorktree( + repoId: string, + git: { path: string; head: string; branch: string; isBare: boolean }, + meta: WorktreeMeta | undefined +): Worktree { + const branchShort = git.branch.replace(/^refs\/heads\//, '') + return { + id: `${repoId}::${git.path}`, + repoId, + path: git.path, + head: git.head, + branch: git.branch, + isBare: git.isBare, + displayName: meta?.displayName || branchShort || basename(git.path), + comment: meta?.comment || '', + linkedIssue: meta?.linkedIssue ?? null, + linkedPR: meta?.linkedPR ?? null, + isArchived: meta?.isArchived ?? false, + isUnread: meta?.isUnread ?? false, + sortOrder: meta?.sortOrder ?? 0 + } +} + +/** + * Parse a composite worktreeId ("repoId::worktreePath") into its parts. + */ +export function parseWorktreeId(worktreeId: string): { repoId: string; worktreePath: string } { + const sepIdx = worktreeId.indexOf('::') + if (sepIdx === -1) { + throw new Error(`Invalid worktreeId: ${worktreeId}`) + } + return { + repoId: worktreeId.slice(0, sepIdx), + worktreePath: worktreeId.slice(sepIdx + 2) + } +} + +/** + * Format a human-readable error message for worktree removal failures. + */ +export function formatWorktreeRemovalError( + error: unknown, + worktreePath: string, + force: boolean +): string { + const fallback = force + ? `Failed to force delete worktree at ${worktreePath}.` + : `Failed to delete worktree at ${worktreePath}.` + + if (!(error instanceof Error)) { + return fallback + } + + const errorWithStreams = error as Error & { stderr?: string; stdout?: string } + const details = [errorWithStreams.stderr, errorWithStreams.stdout, error.message] + .map((value) => value?.trim()) + .find(Boolean) + + return details ? `${fallback} ${details}` : fallback +} diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 51a0d6648..c6fcd2728 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -1,12 +1,21 @@ import type { BrowserWindow } from 'electron' import { ipcMain } from 'electron' import { execFileSync } from 'child_process' -import { join, basename, resolve, relative, isAbsolute } from 'path' import type { Store } from '../persistence' import type { Worktree, WorktreeMeta } from '../../shared/types' import { listWorktrees, addWorktree, removeWorktree } from '../git/worktree' import { getGitUsername, getDefaultBaseRef, getAvailableBranchName } from '../git/repo' import { getEffectiveHooks, loadHooks, runHook, hasHooksFile } from '../hooks' +import { + sanitizeWorktreeName, + computeBranchName, + computeWorktreePath, + ensurePathWithinWorkspace, + shouldSetDisplayName, + mergeWorktree, + parseWorktreeId, + formatWorktreeRemovalError +} from './worktree-logic' export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store): void { // Remove any previously registered handlers so we can re-register them @@ -62,26 +71,12 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store const sanitizedName = sanitizeWorktreeName(args.name) // Compute branch name with prefix - let branchName = sanitizedName - if (settings.branchPrefix === 'git-username') { - const username = getGitUsername(repo.path) - if (username) { - branchName = `${username}/${sanitizedName}` - } - } else if (settings.branchPrefix === 'custom' && settings.branchPrefixCustom) { - branchName = `${settings.branchPrefixCustom}/${sanitizedName}` - } - + const username = getGitUsername(repo.path) + let branchName = computeBranchName(sanitizedName, settings, username) branchName = await getAvailableBranchName(repo.path, branchName) // Compute worktree path - let worktreePath: string - if (settings.nestWorkspaces) { - const repoName = basename(repo.path).replace(/\.git$/, '') - worktreePath = join(settings.workspaceDir, repoName, sanitizedName) - } else { - worktreePath = join(settings.workspaceDir, sanitizedName) - } + let worktreePath = computeWorktreePath(sanitizedName, repo.path, settings) worktreePath = ensurePathWithinWorkspace(worktreePath, settings.workspaceDir) // Determine base branch @@ -109,10 +104,13 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store } const worktreeId = `${repo.id}::${worktreePath}` - const metaUpdates: Partial = - branchName === requestedName && sanitizedName === requestedName - ? {} - : { displayName: requestedName } + const metaUpdates: Partial = shouldSetDisplayName( + requestedName, + branchName, + sanitizedName + ) + ? { displayName: requestedName } + : {} const meta = store.setWorktreeMeta(worktreeId, metaUpdates) const worktree = mergeWorktree(repo.id, created, meta) @@ -185,87 +183,8 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store }) } -function mergeWorktree( - repoId: string, - git: { path: string; head: string; branch: string; isBare: boolean }, - meta: WorktreeMeta | undefined -): Worktree { - const branchShort = git.branch.replace(/^refs\/heads\//, '') - return { - id: `${repoId}::${git.path}`, - repoId, - path: git.path, - head: git.head, - branch: git.branch, - isBare: git.isBare, - displayName: meta?.displayName || branchShort || basename(git.path), - comment: meta?.comment || '', - linkedIssue: meta?.linkedIssue ?? null, - linkedPR: meta?.linkedPR ?? null, - isArchived: meta?.isArchived ?? false, - isUnread: meta?.isUnread ?? false, - sortOrder: meta?.sortOrder ?? 0 - } -} - -function sanitizeWorktreeName(input: string): string { - const sanitized = input - .trim() - .replace(/[\\/]+/g, '-') - .replace(/\s+/g, '-') - .replace(/[^A-Za-z0-9._-]+/g, '-') - .replace(/-+/g, '-') - .replace(/^[.-]+|[.-]+$/g, '') - - if (!sanitized || sanitized === '.' || sanitized === '..') { - throw new Error('Invalid worktree name') - } - - return sanitized -} - -function ensurePathWithinWorkspace(targetPath: string, workspaceDir: string): string { - const resolvedWorkspaceDir = resolve(workspaceDir) - const resolvedTargetPath = resolve(targetPath) - const rel = relative(resolvedWorkspaceDir, resolvedTargetPath) - - if (isAbsolute(rel) || rel.startsWith('..')) { - throw new Error('Invalid worktree path') - } - - return resolvedTargetPath -} - -function parseWorktreeId(worktreeId: string): { repoId: string; worktreePath: string } { - const sepIdx = worktreeId.indexOf('::') - if (sepIdx === -1) { - throw new Error(`Invalid worktreeId: ${worktreeId}`) - } - return { - repoId: worktreeId.slice(0, sepIdx), - worktreePath: worktreeId.slice(sepIdx + 2) - } -} - function notifyWorktreesChanged(mainWindow: BrowserWindow, repoId: string): void { if (!mainWindow.isDestroyed()) { mainWindow.webContents.send('worktrees:changed', { repoId }) } } - -function formatWorktreeRemovalError(error: unknown, worktreePath: string, force: boolean): string { - const fallback = force - ? `Failed to force delete worktree at ${worktreePath}.` - : `Failed to delete worktree at ${worktreePath}.` - - if (!(error instanceof Error)) { - return fallback - } - - const errorWithStreams = error as Error & { stderr?: string; stdout?: string } - const details = [errorWithStreams.stderr, errorWithStreams.stdout, error.message] - .map((value) => value?.trim()) - .find(Boolean) - - return details ? `${fallback} ${details}` : fallback -} diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts new file mode 100644 index 000000000..c087a7c7e --- /dev/null +++ b/src/main/persistence.test.ts @@ -0,0 +1,319 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { writeFileSync, readFileSync, rmSync, mkdtempSync, mkdirSync } from 'fs' +import { join } from 'path' +import { tmpdir } from 'os' +import type { Repo } from '../shared/types' + +// Shared mutable state so the electron mock can reference a per-test directory +const testState = { dir: '' } + +vi.mock('electron', () => ({ + app: { + getPath: () => testState.dir + } +})) + +vi.mock('./git/repo', () => ({ + getGitUsername: vi.fn().mockReturnValue('testuser') +})) + +/** Reset modules and dynamically import Store so DATA_FILE picks up the current testState.dir */ +async function createStore() { + vi.resetModules() + const { Store } = await import('./persistence') + return new Store() +} + +function dataFile(): string { + return join(testState.dir, 'orca-data.json') +} + +function writeDataFile(data: unknown): void { + mkdirSync(testState.dir, { recursive: true }) + writeFileSync(dataFile(), JSON.stringify(data, null, 2), 'utf-8') +} + +function readDataFile(): unknown { + return JSON.parse(readFileSync(dataFile(), 'utf-8')) +} + +const makeRepo = (overrides: Partial = {}): Repo => ({ + id: 'r1', + path: '/repo', + displayName: 'test', + badgeColor: '#fff', + addedAt: 1, + ...overrides +}) + +describe('Store', () => { + beforeEach(() => { + testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-')) + }) + + afterEach(() => { + rmSync(testState.dir, { recursive: true, force: true }) + }) + + // ── 1. Defaults when no file exists ────────────────────────────────── + + it('returns empty repos when no data file exists', async () => { + const store = await createStore() + expect(store.getRepos()).toEqual([]) + }) + + it('returns default settings when no data file exists', async () => { + const store = await createStore() + const settings = store.getSettings() + expect(settings.branchPrefix).toBe('git-username') + expect(settings.theme).toBe('system') + expect(settings.terminalFontSize).toBe(14) + }) + + it('returns default UI state when no data file exists', async () => { + const store = await createStore() + const ui = store.getUI() + expect(ui.sidebarWidth).toBe(280) + expect(ui.groupBy).toBe('none') + expect(ui.lastActiveRepoId).toBeNull() + }) + + // ── 2. Load from existing valid file ───────────────────────────────── + + it('reads repos from an existing data file', async () => { + const repo = makeRepo() + writeDataFile({ + schemaVersion: 1, + repos: [repo], + worktreeMeta: {}, + settings: {}, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) + + const store = await createStore() + const repos = store.getRepos() + expect(repos).toHaveLength(1) + expect(repos[0].id).toBe('r1') + expect(repos[0].gitUsername).toBe('testuser') + }) + + // ── 3. Corrupt JSON → falls back to defaults ──────────────────────── + + it('falls back to defaults when data file contains invalid JSON', async () => { + mkdirSync(testState.dir, { recursive: true }) + writeFileSync(dataFile(), '{{{invalid json', 'utf-8') + + const store = await createStore() + expect(store.getRepos()).toEqual([]) + expect(store.getSettings().theme).toBe('system') + }) + + // ── 4. Schema migration: merges with defaults ─────────────────────── + + it('merges loaded data with defaults for missing fields', async () => { + writeDataFile({ + schemaVersion: 1, + repos: [makeRepo()], + worktreeMeta: {}, + settings: { theme: 'dark' }, + githubCache: { pr: {}, issue: {} } + // ui and workspaceSession intentionally omitted + }) + + const store = await createStore() + // ui should have defaults + const ui = store.getUI() + expect(ui.sidebarWidth).toBe(280) + // settings should preserve the overridden value + expect(store.getSettings().theme).toBe('dark') + // repos should be loaded + expect(store.getRepos()).toHaveLength(1) + }) + + // ── 5. addRepo and getRepo ────────────────────────────────────────── + + it('addRepo stores a repo retrievable by getRepo', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + + const fetched = store.getRepo('r1') + expect(fetched).toBeDefined() + expect(fetched!.displayName).toBe('test') + expect(fetched!.gitUsername).toBe('testuser') + }) + + it('getRepo returns undefined for nonexistent id', async () => { + const store = await createStore() + expect(store.getRepo('nonexistent')).toBeUndefined() + }) + + // ── 6. removeRepo cleans up worktree meta ────────────────────────── + + it('removeRepo deletes the repo and its worktree meta', async () => { + const store = await createStore() + store.addRepo(makeRepo({ id: 'r1' })) + store.addRepo(makeRepo({ id: 'r2', path: '/repo2' })) + + store.setWorktreeMeta('r1::/path/wt1', { displayName: 'wt1' }) + store.setWorktreeMeta('r1::/path/wt2', { displayName: 'wt2' }) + store.setWorktreeMeta('r2::/other', { displayName: 'other' }) + + store.removeRepo('r1') + + expect(store.getRepo('r1')).toBeUndefined() + expect(store.getWorktreeMeta('r1::/path/wt1')).toBeUndefined() + expect(store.getWorktreeMeta('r1::/path/wt2')).toBeUndefined() + expect(store.getWorktreeMeta('r2::/other')).toBeDefined() + expect(store.getWorktreeMeta('r2::/other')!.displayName).toBe('other') + }) + + // ── 7. updateRepo ────────────────────────────────────────────────── + + it('updateRepo modifies the repo in place', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + + const updated = store.updateRepo('r1', { displayName: 'renamed' }) + expect(updated).not.toBeNull() + expect(updated!.displayName).toBe('renamed') + expect(store.getRepo('r1')!.displayName).toBe('renamed') + }) + + it('updateRepo returns null for nonexistent id', async () => { + const store = await createStore() + expect(store.updateRepo('nope', { displayName: 'x' })).toBeNull() + }) + + // ── 8. setWorktreeMeta and getWorktreeMeta ───────────────────────── + + it('setWorktreeMeta creates meta with defaults for missing fields', async () => { + const store = await createStore() + const meta = store.setWorktreeMeta('wt1', { displayName: 'my-wt' }) + + expect(meta.displayName).toBe('my-wt') + expect(meta.comment).toBe('') + expect(meta.linkedIssue).toBeNull() + expect(meta.isArchived).toBe(false) + expect(typeof meta.sortOrder).toBe('number') + }) + + it('setWorktreeMeta merges with existing meta', async () => { + const store = await createStore() + store.setWorktreeMeta('wt1', { displayName: 'first', comment: 'hello' }) + const updated = store.setWorktreeMeta('wt1', { comment: 'updated' }) + + expect(updated.displayName).toBe('first') + expect(updated.comment).toBe('updated') + }) + + // ── 9. Settings: get/update ──────────────────────────────────────── + + it('updateSettings merges partial updates', async () => { + const store = await createStore() + const initial = store.getSettings() + expect(initial.theme).toBe('system') + + const updated = store.updateSettings({ theme: 'dark', terminalFontSize: 16 }) + expect(updated.theme).toBe('dark') + expect(updated.terminalFontSize).toBe(16) + // Other fields preserved + expect(updated.branchPrefix).toBe('git-username') + }) + + // ── 10. flush writes synchronously ───────────────────────────────── + + it('flush writes state to disk synchronously', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + store.flush() + + const persisted = readDataFile() as { repos: Repo[] } + expect(persisted.repos).toHaveLength(1) + expect(persisted.repos[0].id).toBe('r1') + }) + + // ── 11. Debounced save ───────────────────────────────────────────── + + it('debounced save writes data after the delay', async () => { + vi.useFakeTimers() + try { + const store = await createStore() + store.addRepo(makeRepo()) + + // Before the debounce fires, file should not exist yet (or be stale) + vi.advanceTimersByTime(100) + // The 300ms debounce hasn't elapsed yet + + vi.advanceTimersByTime(300) + // Now the save should have fired + + const persisted = readDataFile() as { repos: Repo[] } + expect(persisted.repos).toHaveLength(1) + expect(persisted.repos[0].id).toBe('r1') + } finally { + vi.useRealTimers() + } + }) + + // ── UI state ─────────────────────────────────────────────────────── + + it('updateUI merges partial updates', async () => { + const store = await createStore() + store.updateUI({ sidebarWidth: 400 }) + const ui = store.getUI() + expect(ui.sidebarWidth).toBe(400) + expect(ui.groupBy).toBe('none') // default preserved + }) + + // ── GitHub Cache ─────────────────────────────────────────────────── + + it('get/set GitHub cache round-trips', async () => { + const store = await createStore() + const cache = { + pr: { 'owner/repo#1': { data: null, fetchedAt: 1000 } }, + issue: {} + } + store.setGitHubCache(cache) + expect(store.getGitHubCache()).toEqual(cache) + }) + + // ── Workspace Session ────────────────────────────────────────────── + + it('get/set workspace session round-trips', async () => { + const store = await createStore() + const session = { + activeRepoId: 'r1', + activeWorktreeId: 'wt1', + activeTabId: 'tab1', + tabsByWorktree: {}, + terminalLayoutsByTabId: {} + } + store.setWorkspaceSession(session) + expect(store.getWorkspaceSession()).toEqual(session) + }) + + // ── getAllWorktreeMeta ───────────────────────────────────────────── + + it('getAllWorktreeMeta returns all entries', async () => { + const store = await createStore() + store.setWorktreeMeta('a', { displayName: 'A' }) + store.setWorktreeMeta('b', { displayName: 'B' }) + const all = store.getAllWorktreeMeta() + expect(Object.keys(all)).toHaveLength(2) + expect(all['a'].displayName).toBe('A') + expect(all['b'].displayName).toBe('B') + }) + + // ── removeWorktreeMeta ───────────────────────────────────────────── + + it('removeWorktreeMeta deletes a single entry', async () => { + const store = await createStore() + store.setWorktreeMeta('a', { displayName: 'A' }) + store.setWorktreeMeta('b', { displayName: 'B' }) + store.removeWorktreeMeta('a') + expect(store.getWorktreeMeta('a')).toBeUndefined() + expect(store.getWorktreeMeta('b')).toBeDefined() + }) +}) diff --git a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts index eacb74c03..df99cd141 100644 --- a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts +++ b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts @@ -11,7 +11,9 @@ function isEditableTarget(target: EventTarget | null): boolean { return true } - const editableAncestor = target.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]') + const editableAncestor = target.closest( + 'input, textarea, select, [contenteditable=""], [contenteditable="true"]' + ) return editableAncestor !== null } diff --git a/src/renderer/src/components/terminal-pane/layout-serialization.test.ts b/src/renderer/src/components/terminal-pane/layout-serialization.test.ts new file mode 100644 index 000000000..bb33f43a3 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/layout-serialization.test.ts @@ -0,0 +1,246 @@ +import { describe, expect, it, beforeAll } from 'vitest' + +// --------------------------------------------------------------------------- +// Provide a minimal HTMLElement so `instanceof HTMLElement` passes in Node env +// --------------------------------------------------------------------------- +class MockHTMLElement { + classList: { contains: (cls: string) => boolean } + dataset: Record + children: MockHTMLElement[] + style: Record + firstElementChild: MockHTMLElement | null + + constructor(opts: { + classList?: string[] + dataset?: Record + children?: MockHTMLElement[] + style?: Record + firstElementChild?: MockHTMLElement | null + }) { + const classes = opts.classList ?? [] + this.classList = { contains: (cls: string) => classes.includes(cls) } + this.dataset = opts.dataset ?? {} + this.children = opts.children ?? [] + this.style = opts.style ?? {} + this.firstElementChild = opts.firstElementChild ?? null + } +} + +beforeAll(() => { + // Expose globally so `child instanceof HTMLElement` works inside the module + ;(globalThis as unknown as Record).HTMLElement = MockHTMLElement +}) + +// Now import the module *after* HTMLElement is defined on globalThis. +// Vitest hoists imports, so we use dynamic import inside tests instead? +// Actually vitest hoists `beforeAll` too, but the global assignment happens +// before the imported module's runtime code runs since the module only uses +// HTMLElement at call-time (not at import-time). Let's verify. + +import { + paneLeafId, + buildFontFamily, + serializePaneTree, + serializeTerminalLayout, + EMPTY_LAYOUT +} from './layout-serialization' + +// --------------------------------------------------------------------------- +// Helper to create mock elements +// --------------------------------------------------------------------------- +function mockElement(opts: { + classList?: string[] + dataset?: Record + children?: MockHTMLElement[] + style?: Record + firstElementChild?: MockHTMLElement | null +}): HTMLElement { + return new MockHTMLElement(opts) as unknown as HTMLElement +} + +// --------------------------------------------------------------------------- +// paneLeafId +// --------------------------------------------------------------------------- +describe('paneLeafId', () => { + it('returns "pane:0" for paneId 0', () => { + expect(paneLeafId(0)).toBe('pane:0') + }) + + it('returns "pane:1" for paneId 1', () => { + expect(paneLeafId(1)).toBe('pane:1') + }) + + it('returns "pane:42" for paneId 42', () => { + expect(paneLeafId(42)).toBe('pane:42') + }) +}) + +// --------------------------------------------------------------------------- +// buildFontFamily +// --------------------------------------------------------------------------- +describe('buildFontFamily', () => { + it('puts custom font first with SF Mono, Menlo, monospace fallbacks', () => { + const result = buildFontFamily('JetBrains Mono') + expect(result).toBe('"JetBrains Mono", "SF Mono", Menlo, monospace') + }) + + it('does not duplicate SF Mono when it is the input', () => { + const result = buildFontFamily('SF Mono') + expect(result).toBe('"SF Mono", Menlo, monospace') + }) + + it('returns SF Mono, Menlo, monospace for empty string', () => { + const result = buildFontFamily('') + expect(result).toBe('"SF Mono", Menlo, monospace') + }) + + it('treats whitespace-only string same as empty', () => { + const result = buildFontFamily(' ') + expect(result).toBe('"SF Mono", Menlo, monospace') + }) + + it('does not duplicate when font name contains "sf mono" (case-insensitive)', () => { + const result = buildFontFamily('My SF Mono Custom') + expect(result).toBe('"My SF Mono Custom", Menlo, monospace') + }) +}) + +// --------------------------------------------------------------------------- +// serializePaneTree +// --------------------------------------------------------------------------- +describe('serializePaneTree', () => { + it('returns null for null input', () => { + expect(serializePaneTree(null)).toBeNull() + }) + + it('returns a leaf node for a single pane', () => { + const pane = mockElement({ classList: ['pane'], dataset: { paneId: '1' } }) + expect(serializePaneTree(pane)).toEqual({ type: 'leaf', leafId: 'pane:1' }) + }) + + it('returns null for a pane with non-numeric paneId', () => { + const pane = mockElement({ classList: ['pane'], dataset: { paneId: 'abc' } }) + expect(serializePaneTree(pane)).toBeNull() + }) + + it('returns null for element that is neither pane nor pane-split', () => { + const el = mockElement({ classList: ['random-class'] }) + expect(serializePaneTree(el)).toBeNull() + }) + + it('returns a vertical split node with two pane children', () => { + const first = new MockHTMLElement({ classList: ['pane'], dataset: { paneId: '1' } }) + const second = new MockHTMLElement({ classList: ['pane'], dataset: { paneId: '2' } }) + const split = mockElement({ classList: ['pane-split'], children: [first, second] }) + + expect(serializePaneTree(split)).toEqual({ + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: 'pane:1' }, + second: { type: 'leaf', leafId: 'pane:2' } + }) + }) + + it('returns horizontal direction when split has is-horizontal class', () => { + const first = new MockHTMLElement({ classList: ['pane'], dataset: { paneId: '3' } }) + const second = new MockHTMLElement({ classList: ['pane'], dataset: { paneId: '4' } }) + const split = mockElement({ + classList: ['pane-split', 'is-horizontal'], + children: [first, second] + }) + + expect(serializePaneTree(split)).toEqual({ + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: 'pane:3' }, + second: { type: 'leaf', leafId: 'pane:4' } + }) + }) + + it('captures flex ratio when children have unequal flex', () => { + const first = new MockHTMLElement({ + classList: ['pane'], + dataset: { paneId: '1' }, + style: { flex: '3' } + }) + const second = new MockHTMLElement({ + classList: ['pane'], + dataset: { paneId: '2' }, + style: { flex: '1' } + }) + const split = mockElement({ classList: ['pane-split'], children: [first, second] }) + + const result = serializePaneTree(split) + expect(result).toEqual({ + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: 'pane:1' }, + second: { type: 'leaf', leafId: 'pane:2' }, + ratio: 0.75 + }) + }) + + it('omits ratio when flex values are equal (both 1)', () => { + const first = new MockHTMLElement({ + classList: ['pane'], + dataset: { paneId: '1' }, + style: { flex: '1' } + }) + const second = new MockHTMLElement({ + classList: ['pane'], + dataset: { paneId: '2' }, + style: { flex: '1' } + }) + const split = mockElement({ classList: ['pane-split'], children: [first, second] }) + + const result = serializePaneTree(split) + expect(result).not.toHaveProperty('ratio') + }) + + it('handles nested splits recursively', () => { + const leaf1 = new MockHTMLElement({ classList: ['pane'], dataset: { paneId: '1' } }) + const leaf2 = new MockHTMLElement({ classList: ['pane'], dataset: { paneId: '2' } }) + const leaf3 = new MockHTMLElement({ classList: ['pane'], dataset: { paneId: '3' } }) + + const innerSplit = new MockHTMLElement({ + classList: ['pane-split', 'is-horizontal'], + children: [leaf2, leaf3] + }) + const outerSplit = mockElement({ + classList: ['pane-split'], + children: [leaf1, innerSplit] + }) + + expect(serializePaneTree(outerSplit)).toEqual({ + type: 'split', + direction: 'vertical', + first: { type: 'leaf', leafId: 'pane:1' }, + second: { + type: 'split', + direction: 'horizontal', + first: { type: 'leaf', leafId: 'pane:2' }, + second: { type: 'leaf', leafId: 'pane:3' } + } + }) + }) +}) + +// --------------------------------------------------------------------------- +// serializeTerminalLayout +// --------------------------------------------------------------------------- +describe('serializeTerminalLayout', () => { + it('returns EMPTY_LAYOUT equivalent when root is null', () => { + const result = serializeTerminalLayout(null, null, null) + expect(result).toEqual(EMPTY_LAYOUT) + }) + + it('returns null root when root has no firstElementChild', () => { + const root = mockElement({}) as unknown as HTMLDivElement + const result = serializeTerminalLayout(root, 5, null) + expect(result).toEqual({ + root: null, + activeLeafId: 'pane:5', + expandedLeafId: null + }) + }) +}) diff --git a/src/renderer/src/lib/agent-status.test.ts b/src/renderer/src/lib/agent-status.test.ts index 91c48cf2c..6cf055e78 100644 --- a/src/renderer/src/lib/agent-status.test.ts +++ b/src/renderer/src/lib/agent-status.test.ts @@ -2,13 +2,132 @@ import { describe, expect, it } from 'vitest' import { detectAgentStatusFromTitle, clearWorkingIndicators } from './agent-status' describe('detectAgentStatusFromTitle', () => { + it('returns null for empty string', () => { + expect(detectAgentStatusFromTitle('')).toBeNull() + }) + + it('returns null for a title with no agent indicators', () => { + expect(detectAgentStatusFromTitle('bash')).toBeNull() + expect(detectAgentStatusFromTitle('vim myfile.ts')).toBeNull() + }) + + // --- Gemini symbols --- + it('detects Gemini permission symbol ✋', () => { + expect(detectAgentStatusFromTitle('✋ Gemini CLI')).toBe('permission') + }) + + it('detects Gemini working symbol ✦', () => { + expect(detectAgentStatusFromTitle('✦ Gemini CLI')).toBe('working') + }) + + it('detects Gemini idle symbol ◇', () => { + expect(detectAgentStatusFromTitle('◇ Gemini CLI')).toBe('idle') + }) + + it('Gemini permission takes precedence over working', () => { + expect(detectAgentStatusFromTitle('✋✦ Gemini CLI')).toBe('permission') + }) + + // --- Braille spinner characters --- + it('detects braille spinner ⠋ as working', () => { + expect(detectAgentStatusFromTitle('⠋ Codex is thinking')).toBe('working') + }) + + it('detects braille spinner ⠙ as working', () => { + expect(detectAgentStatusFromTitle('⠙ some task')).toBe('working') + }) + + it('detects braille spinner ⠹ as working', () => { + expect(detectAgentStatusFromTitle('⠹ aider running')).toBe('working') + }) + + it('detects braille spinner ⠸ as working', () => { + expect(detectAgentStatusFromTitle('⠸ process')).toBe('working') + }) + + it('detects braille spinner ⠼ as working', () => { + expect(detectAgentStatusFromTitle('⠼ opencode')).toBe('working') + }) + + it('detects braille spinner ⠴ as working', () => { + expect(detectAgentStatusFromTitle('⠴ loading')).toBe('working') + }) + + it('detects braille spinner ⠦ as working', () => { + expect(detectAgentStatusFromTitle('⠦ claude')).toBe('working') + }) + + it('detects braille spinner ⠧ as working', () => { + expect(detectAgentStatusFromTitle('⠧ task')).toBe('working') + }) + + // --- Agent name keyword combos --- it('detects permission requests from agent titles', () => { expect(detectAgentStatusFromTitle('Claude Code - action required')).toBe('permission') }) - it('treats braille spinners as working and Gemini symbols as idle', () => { - expect(detectAgentStatusFromTitle('⠋ Codex is thinking')).toBe('working') - expect(detectAgentStatusFromTitle('◇ Gemini CLI')).toBe('idle') + it('detects "permission" keyword with agent name', () => { + expect(detectAgentStatusFromTitle('codex - permission needed')).toBe('permission') + }) + + it('detects "waiting" keyword with agent name', () => { + expect(detectAgentStatusFromTitle('gemini waiting for input')).toBe('permission') + }) + + it('detects "ready" keyword as idle', () => { + expect(detectAgentStatusFromTitle('claude ready')).toBe('idle') + }) + + it('detects "idle" keyword as idle', () => { + expect(detectAgentStatusFromTitle('codex idle')).toBe('idle') + }) + + it('detects "done" keyword as idle', () => { + expect(detectAgentStatusFromTitle('aider done')).toBe('idle') + }) + + it('detects "working" keyword as working', () => { + expect(detectAgentStatusFromTitle('claude working on task')).toBe('working') + }) + + it('detects "thinking" keyword as working', () => { + expect(detectAgentStatusFromTitle('gemini thinking')).toBe('working') + }) + + it('detects "running" keyword as working', () => { + expect(detectAgentStatusFromTitle('opencode running tests')).toBe('working') + }) + + // --- Claude Code title prefixes --- + it('detects ". " prefix as working (Claude Code)', () => { + expect(detectAgentStatusFromTitle('. claude')).toBe('working') + }) + + it('detects "* " prefix as idle (Claude Code)', () => { + expect(detectAgentStatusFromTitle('* claude')).toBe('idle') + }) + + // --- Agent name alone defaults to idle --- + it('returns idle for bare agent name "claude"', () => { + expect(detectAgentStatusFromTitle('claude')).toBe('idle') + }) + + it('returns idle for bare agent name "codex"', () => { + expect(detectAgentStatusFromTitle('codex')).toBe('idle') + }) + + it('returns idle for bare agent name "aider"', () => { + expect(detectAgentStatusFromTitle('aider')).toBe('idle') + }) + + it('returns idle for bare agent name "opencode"', () => { + expect(detectAgentStatusFromTitle('opencode')).toBe('idle') + }) + + // --- Case insensitivity --- + it('is case-insensitive for agent names', () => { + expect(detectAgentStatusFromTitle('CLAUDE')).toBe('idle') + expect(detectAgentStatusFromTitle('Codex Working')).toBe('working') }) }) diff --git a/src/renderer/src/store/slices/store-cascades.test.ts b/src/renderer/src/store/slices/store-cascades.test.ts new file mode 100644 index 000000000..f709cff4b --- /dev/null +++ b/src/renderer/src/store/slices/store-cascades.test.ts @@ -0,0 +1,296 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { create } from 'zustand' +import type { AppState } from '../types' +import type { Worktree, TerminalTab, TerminalLayoutSnapshot } from '../../../../shared/types' +import type { OpenFile } from './editor' + +// Mock sonner (imported by repos.ts) +vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) + +// Mock agent-status (imported by terminal-helpers) +vi.mock('@/lib/agent-status', () => ({ + detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) +})) + +// Mock window.api before anything uses it +const mockApi = { + worktrees: { + list: vi.fn().mockResolvedValue([]), + create: vi.fn().mockResolvedValue({}), + remove: vi.fn().mockResolvedValue(undefined), + updateMeta: vi.fn().mockResolvedValue({}) + }, + repos: { + list: vi.fn().mockResolvedValue([]), + add: vi.fn().mockResolvedValue({}), + remove: vi.fn().mockResolvedValue(undefined), + update: vi.fn().mockResolvedValue({}), + pickFolder: vi.fn().mockResolvedValue(null) + }, + pty: { + kill: vi.fn().mockResolvedValue(undefined) + }, + gh: { + prForBranch: vi.fn().mockResolvedValue(null), + issue: vi.fn().mockResolvedValue(null) + }, + settings: { + get: vi.fn().mockResolvedValue({}), + set: vi.fn().mockResolvedValue(undefined) + }, + cache: { + getGitHub: vi.fn().mockResolvedValue(null), + setGitHub: vi.fn().mockResolvedValue(undefined) + } +} + +// @ts-expect-error -- mock +globalThis.window = { api: mockApi } + +import { createRepoSlice } from './repos' +import { createWorktreeSlice } from './worktrees' +import { createTerminalSlice } from './terminals' +import { createUISlice } from './ui' +import { createSettingsSlice } from './settings' +import { createGitHubSlice } from './github' +import { createEditorSlice } from './editor' + +function createTestStore() { + return create()((...a) => ({ + ...createRepoSlice(...a), + ...createWorktreeSlice(...a), + ...createTerminalSlice(...a), + ...createUISlice(...a), + ...createSettingsSlice(...a), + ...createGitHubSlice(...a), + ...createEditorSlice(...a) + })) +} + +// ─── Helpers ────────────────────────────────────────────────────────── + +function makeWorktree(overrides: Partial & { id: string; repoId: string }): Worktree { + return { + path: '/tmp/wt', + head: 'abc123', + branch: 'refs/heads/feature', + isBare: false, + displayName: 'feature', + comment: '', + linkedIssue: null, + linkedPR: null, + isArchived: false, + isUnread: false, + sortOrder: 0, + ...overrides + } +} + +function makeTab( + overrides: Partial & { id: string; worktreeId: string } +): TerminalTab { + return { + ptyId: null, + title: 'Terminal 1', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: Date.now(), + ...overrides + } +} + +function makeLayout(): TerminalLayoutSnapshot { + return { root: null, activeLeafId: null, expandedLeafId: null } +} + +function makeOpenFile(overrides: Partial & { id: string; worktreeId: string }): OpenFile { + return { + filePath: overrides.id, + relativePath: 'file.ts', + language: 'typescript', + isDirty: false, + mode: 'edit', + ...overrides + } +} + +// ─── Tests ──────────────────────────────────────────────────────────── + +describe('removeWorktree cascade', () => { + beforeEach(() => { + vi.clearAllMocks() + mockApi.worktrees.remove.mockResolvedValue(undefined) + }) + + it('cleans up all associated state on successful removal', async () => { + const store = createTestStore() + const worktreeId = 'repo1::/path/wt1' + + // Seed state + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/path/wt1' })] + }, + tabsByWorktree: { + [worktreeId]: [ + makeTab({ id: 'tab1', worktreeId }), + makeTab({ id: 'tab2', worktreeId, sortOrder: 1 }) + ] + }, + ptyIdsByTabId: { + tab1: ['pty1'], + tab2: ['pty2'] + }, + terminalLayoutsByTabId: { + tab1: makeLayout(), + tab2: makeLayout() + }, + deleteStateByWorktreeId: { + [worktreeId]: { isDeleting: false, error: null, canForceDelete: false } + }, + activeWorktreeId: worktreeId, + activeTabId: 'tab1', + openFiles: [makeOpenFile({ id: '/path/wt1/file.ts', worktreeId })], + activeFileId: '/path/wt1/file.ts', + activeTabType: 'editor', + activeFileIdByWorktree: { [worktreeId]: '/path/wt1/file.ts' }, + activeTabTypeByWorktree: { [worktreeId]: 'editor' } + }) + + const result = await store.getState().removeWorktree(worktreeId) + const s = store.getState() + + expect(result).toEqual({ ok: true }) + expect(s.worktreesByRepo['repo1']).toEqual([]) + expect(s.tabsByWorktree[worktreeId]).toBeUndefined() + expect(s.ptyIdsByTabId['tab1']).toBeUndefined() + expect(s.ptyIdsByTabId['tab2']).toBeUndefined() + expect(s.terminalLayoutsByTabId['tab1']).toBeUndefined() + expect(s.terminalLayoutsByTabId['tab2']).toBeUndefined() + expect(s.deleteStateByWorktreeId[worktreeId]).toBeUndefined() + expect(s.activeWorktreeId).toBeNull() + expect(s.activeTabId).toBeNull() + expect(s.openFiles).toEqual([]) + expect(s.activeFileId).toBeNull() + expect(s.activeTabType).toBe('terminal') + expect(s.activeFileIdByWorktree[worktreeId]).toBeUndefined() + expect(s.activeTabTypeByWorktree[worktreeId]).toBeUndefined() + }) + + it('sets delete state with error and canForceDelete=true on failure', async () => { + const store = createTestStore() + const worktreeId = 'repo1::/path/wt1' + + mockApi.worktrees.remove.mockRejectedValueOnce(new Error('branch has changes')) + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1' })] + }, + tabsByWorktree: { [worktreeId]: [makeTab({ id: 'tab1', worktreeId })] }, + ptyIdsByTabId: { tab1: ['pty1'] }, + terminalLayoutsByTabId: { tab1: makeLayout() }, + activeWorktreeId: worktreeId, + activeTabId: 'tab1' + }) + + const result = await store.getState().removeWorktree(worktreeId) + const s = store.getState() + + expect(result).toEqual({ ok: false, error: 'branch has changes' }) + expect(s.deleteStateByWorktreeId[worktreeId]).toEqual({ + isDeleting: false, + error: 'branch has changes', + canForceDelete: true + }) + // State NOT cleaned up + expect(s.worktreesByRepo['repo1']).toHaveLength(1) + expect(s.tabsByWorktree[worktreeId]).toHaveLength(1) + expect(s.activeWorktreeId).toBe(worktreeId) + }) + + it('sets canForceDelete=false when force=true removal fails', async () => { + const store = createTestStore() + const worktreeId = 'repo1::/path/wt1' + + mockApi.worktrees.remove.mockRejectedValueOnce(new Error('fatal error')) + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1' })] + }, + tabsByWorktree: {}, + ptyIdsByTabId: {}, + terminalLayoutsByTabId: {} + }) + + const result = await store.getState().removeWorktree(worktreeId, true) + const s = store.getState() + + expect(result).toEqual({ ok: false, error: 'fatal error' }) + expect(s.deleteStateByWorktreeId[worktreeId]).toEqual({ + isDeleting: false, + error: 'fatal error', + canForceDelete: false + }) + }) + + it('does NOT affect other worktrees', async () => { + const store = createTestStore() + const wt1 = 'repo1::/path/wt1' + const wt2 = 'repo1::/path/wt2' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [ + makeWorktree({ id: wt1, repoId: 'repo1', path: '/path/wt1' }), + makeWorktree({ id: wt2, repoId: 'repo1', path: '/path/wt2', displayName: 'wt2' }) + ] + }, + tabsByWorktree: { + [wt1]: [makeTab({ id: 'tab1', worktreeId: wt1 })], + [wt2]: [makeTab({ id: 'tab2', worktreeId: wt2 })] + }, + ptyIdsByTabId: { + tab1: ['pty1'], + tab2: ['pty2'] + }, + terminalLayoutsByTabId: { + tab1: makeLayout(), + tab2: makeLayout() + }, + activeWorktreeId: wt2, + activeTabId: 'tab2' + }) + + await store.getState().removeWorktree(wt1) + const s = store.getState() + + // wt2 is untouched + expect(s.tabsByWorktree[wt2]).toHaveLength(1) + expect(s.tabsByWorktree[wt2][0].id).toBe('tab2') + expect(s.ptyIdsByTabId['tab2']).toEqual(['pty2']) + expect(s.terminalLayoutsByTabId['tab2']).toEqual(makeLayout()) + expect(s.activeWorktreeId).toBe(wt2) + expect(s.activeTabId).toBe('tab2') + + // wt1 is gone + expect(s.worktreesByRepo['repo1'].find((w) => w.id === wt1)).toBeUndefined() + expect(s.tabsByWorktree[wt1]).toBeUndefined() + expect(s.ptyIdsByTabId['tab1']).toBeUndefined() + expect(s.terminalLayoutsByTabId['tab1']).toBeUndefined() + }) +}) diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts new file mode 100644 index 000000000..9f9f2c76f --- /dev/null +++ b/src/renderer/src/store/slices/store-session-cascades.test.ts @@ -0,0 +1,258 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { create } from 'zustand' +import type { AppState } from '../types' +import type { Worktree, TerminalTab, TerminalLayoutSnapshot } from '../../../../shared/types' + +// Mock sonner (imported by repos.ts) +vi.mock('sonner', () => ({ toast: { info: vi.fn(), success: vi.fn(), error: vi.fn() } })) + +// Mock agent-status (imported by terminal-helpers) +vi.mock('@/lib/agent-status', () => ({ + detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) +})) + +// Mock window.api before anything uses it +const mockApi = { + worktrees: { + list: vi.fn().mockResolvedValue([]), + create: vi.fn().mockResolvedValue({}), + remove: vi.fn().mockResolvedValue(undefined), + updateMeta: vi.fn().mockResolvedValue({}) + }, + repos: { + list: vi.fn().mockResolvedValue([]), + add: vi.fn().mockResolvedValue({}), + remove: vi.fn().mockResolvedValue(undefined), + update: vi.fn().mockResolvedValue({}), + pickFolder: vi.fn().mockResolvedValue(null) + }, + pty: { + kill: vi.fn().mockResolvedValue(undefined) + }, + gh: { + prForBranch: vi.fn().mockResolvedValue(null), + issue: vi.fn().mockResolvedValue(null) + }, + settings: { + get: vi.fn().mockResolvedValue({}), + set: vi.fn().mockResolvedValue(undefined) + }, + cache: { + getGitHub: vi.fn().mockResolvedValue(null), + setGitHub: vi.fn().mockResolvedValue(undefined) + } +} + +// @ts-expect-error -- mock +globalThis.window = { api: mockApi } + +import { createRepoSlice } from './repos' +import { createWorktreeSlice } from './worktrees' +import { createTerminalSlice } from './terminals' +import { createUISlice } from './ui' +import { createSettingsSlice } from './settings' +import { createGitHubSlice } from './github' +import { createEditorSlice } from './editor' + +function createTestStore() { + return create()((...a) => ({ + ...createRepoSlice(...a), + ...createWorktreeSlice(...a), + ...createTerminalSlice(...a), + ...createUISlice(...a), + ...createSettingsSlice(...a), + ...createGitHubSlice(...a), + ...createEditorSlice(...a) + })) +} + +// ─── Helpers ────────────────────────────────────────────────────────── + +function makeWorktree(overrides: Partial & { id: string; repoId: string }): Worktree { + return { + path: '/tmp/wt', + head: 'abc123', + branch: 'refs/heads/feature', + isBare: false, + displayName: 'feature', + comment: '', + linkedIssue: null, + linkedPR: null, + isArchived: false, + isUnread: false, + sortOrder: 0, + ...overrides + } +} + +function makeTab( + overrides: Partial & { id: string; worktreeId: string } +): TerminalTab { + return { + ptyId: null, + title: 'Terminal 1', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: Date.now(), + ...overrides + } +} + +function makeLayout(): TerminalLayoutSnapshot { + return { root: null, activeLeafId: null, expandedLeafId: null } +} + +// ─── Tests ──────────────────────────────────────────────────────────── + +describe('removeRepo cascade', () => { + beforeEach(() => { + vi.clearAllMocks() + mockApi.repos.remove.mockResolvedValue(undefined) + mockApi.pty.kill.mockResolvedValue(undefined) + }) + + it('cleans up all associated worktrees, tabs, ptys, and filter state', async () => { + const store = createTestStore() + const wt1 = 'repo1::/path/wt1' + const wt2 = 'repo1::/path/wt2' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + activeRepoId: 'repo1', + filterRepoIds: ['repo1'], + worktreesByRepo: { + repo1: [ + makeWorktree({ id: wt1, repoId: 'repo1', path: '/path/wt1' }), + makeWorktree({ id: wt2, repoId: 'repo1', path: '/path/wt2' }) + ] + }, + tabsByWorktree: { + [wt1]: [makeTab({ id: 'tab1', worktreeId: wt1 })], + [wt2]: [makeTab({ id: 'tab2', worktreeId: wt2 })] + }, + ptyIdsByTabId: { + tab1: ['pty1'], + tab2: ['pty2'] + }, + terminalLayoutsByTabId: { + tab1: makeLayout(), + tab2: makeLayout() + }, + activeTabId: 'tab1' + }) + + await store.getState().removeRepo('repo1') + const s = store.getState() + + expect(s.repos).toEqual([]) + expect(s.activeRepoId).toBeNull() + expect(s.filterRepoIds).not.toContain('repo1') + expect(s.worktreesByRepo['repo1']).toBeUndefined() + expect(s.tabsByWorktree[wt1]).toBeUndefined() + expect(s.tabsByWorktree[wt2]).toBeUndefined() + expect(s.ptyIdsByTabId['tab1']).toBeUndefined() + expect(s.ptyIdsByTabId['tab2']).toBeUndefined() + expect(s.terminalLayoutsByTabId['tab1']).toBeUndefined() + expect(s.terminalLayoutsByTabId['tab2']).toBeUndefined() + expect(s.activeTabId).toBeNull() + + // PTYs were killed + expect(mockApi.pty.kill).toHaveBeenCalledWith('pty1') + expect(mockApi.pty.kill).toHaveBeenCalledWith('pty2') + + // Killed PTY IDs are suppressed + expect(s.suppressedPtyExitIds['pty1']).toBe(true) + expect(s.suppressedPtyExitIds['pty2']).toBe(true) + }) +}) + +describe('hydrateWorkspaceSession', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('filters out tabs for invalid worktree IDs', () => { + const store = createTestStore() + const validWt = 'repo1::/path/wt1' + const invalidWt = 'repo1::/path/gone' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [makeWorktree({ id: validWt, repoId: 'repo1', path: '/path/wt1' })] + } + }) + + store.getState().hydrateWorkspaceSession({ + activeRepoId: 'repo1', + activeWorktreeId: invalidWt, + activeTabId: 'tab-invalid', + tabsByWorktree: { + [validWt]: [makeTab({ id: 'tab-valid', worktreeId: validWt })], + [invalidWt]: [makeTab({ id: 'tab-invalid', worktreeId: invalidWt })] + }, + terminalLayoutsByTabId: { + 'tab-valid': makeLayout(), + 'tab-invalid': makeLayout() + } + }) + + const s = store.getState() + + // Valid worktree tabs restored + expect(s.tabsByWorktree[validWt]).toHaveLength(1) + expect(s.tabsByWorktree[validWt][0].id).toBe('tab-valid') + + // Invalid worktree tabs dropped + expect(s.tabsByWorktree[invalidWt]).toBeUndefined() + + // activeWorktreeId is null because it referenced an invalid worktree + expect(s.activeWorktreeId).toBeNull() + + // activeTabId is null because it referenced an invalid tab + expect(s.activeTabId).toBeNull() + + // Terminal layouts only contain valid tabs + expect(s.terminalLayoutsByTabId['tab-valid']).toBeDefined() + expect(s.terminalLayoutsByTabId['tab-invalid']).toBeUndefined() + + // Session is marked ready + expect(s.workspaceSessionReady).toBe(true) + }) + + it('restores valid activeWorktreeId and activeTabId', () => { + const store = createTestStore() + const validWt = 'repo1::/path/wt1' + + store.setState({ + repos: [ + { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 } + ], + worktreesByRepo: { + repo1: [makeWorktree({ id: validWt, repoId: 'repo1', path: '/path/wt1' })] + } + }) + + store.getState().hydrateWorkspaceSession({ + activeRepoId: 'repo1', + activeWorktreeId: validWt, + activeTabId: 'tab1', + tabsByWorktree: { + [validWt]: [makeTab({ id: 'tab1', worktreeId: validWt })] + }, + terminalLayoutsByTabId: { + tab1: makeLayout() + } + }) + + const s = store.getState() + expect(s.activeWorktreeId).toBe(validWt) + expect(s.activeTabId).toBe('tab1') + expect(s.activeRepoId).toBe('repo1') + }) +}) diff --git a/src/renderer/src/store/slices/terminal-helpers.test.ts b/src/renderer/src/store/slices/terminal-helpers.test.ts new file mode 100644 index 000000000..1c3dcf727 --- /dev/null +++ b/src/renderer/src/store/slices/terminal-helpers.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from 'vitest' +import type { TerminalTab } from '../../../../shared/types' +import { emptyLayoutSnapshot, clearTransientTerminalState } from './terminal-helpers' + +function makeTab(overrides: Partial = {}): TerminalTab { + return { + id: 'tab-1', + ptyId: 'pty-123', + worktreeId: 'wt-1', + title: 'bash', + customTitle: null, + color: null, + sortOrder: 0, + createdAt: Date.now(), + ...overrides + } +} + +describe('emptyLayoutSnapshot', () => { + it('returns correct default structure', () => { + const snapshot = emptyLayoutSnapshot() + expect(snapshot).toEqual({ + root: null, + activeLeafId: null, + expandedLeafId: null + }) + }) +}) + +describe('clearTransientTerminalState', () => { + it('clears ptyId to null', () => { + const tab = makeTab({ ptyId: 'pty-abc' }) + const result = clearTransientTerminalState(tab, 0) + expect(result.ptyId).toBeNull() + }) + + it('uses customTitle as fallback when tab has agent status in title', () => { + const tab = makeTab({ title: '. claude', customTitle: 'My Agent' }) + const result = clearTransientTerminalState(tab, 0) + expect(result.title).toBe('My Agent') + }) + + it('uses "Terminal {index+1}" fallback when agent status in title and no customTitle', () => { + const tab = makeTab({ title: '. claude', customTitle: null }) + const result = clearTransientTerminalState(tab, 0) + expect(result.title).toBe('Terminal 1') + }) + + it('keeps original title when no agent status detected', () => { + const tab = makeTab({ title: 'bash' }) + const result = clearTransientTerminalState(tab, 0) + expect(result.title).toBe('bash') + }) + + it('uses "Terminal {index+1}" when customTitle is whitespace only', () => { + const tab = makeTab({ title: '⠋ codex running', customTitle: ' ' }) + const result = clearTransientTerminalState(tab, 0) + expect(result.title).toBe('Terminal 1') + }) + + it('index-based fallback numbering: index 0 → "Terminal 1"', () => { + const tab = makeTab({ title: '. claude', customTitle: null }) + const result = clearTransientTerminalState(tab, 0) + expect(result.title).toBe('Terminal 1') + }) + + it('index-based fallback numbering: index 2 → "Terminal 3"', () => { + const tab = makeTab({ title: '. claude', customTitle: null }) + const result = clearTransientTerminalState(tab, 2) + expect(result.title).toBe('Terminal 3') + }) +})