From 7f29249d4851761b400346c66872da4b17b375cf Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 17 Mar 2026 01:40:24 -0700 Subject: [PATCH] Major features --- electron.vite.config.ts | 3 +- package.json | 4 + pnpm-lock.yaml | 84 ++++ src/main/git/repo.ts | 98 ++++ src/main/git/worktree.ts | 87 ++++ src/main/github/client.ts | 126 +++++ src/main/hooks.ts | 126 +++++ src/main/index.ts | 170 +------ src/main/ipc/github.ts | 16 + src/main/ipc/pty.ts | 73 +++ src/main/ipc/repos.ts | 65 +++ src/main/ipc/settings.ts | 13 + src/main/ipc/shell.ts | 11 + src/main/ipc/worktrees.ts | 175 +++++++ src/main/persistence.ts | 160 ++++++ src/preload/index.d.ts | 61 ++- src/preload/index.ts | 78 ++- src/renderer/index.html | 6 +- src/renderer/src/App.tsx | 37 +- src/renderer/src/components/Landing.tsx | 26 +- src/renderer/src/components/Settings.tsx | 373 ++++++++++++++ src/renderer/src/components/Sidebar.tsx | 43 +- src/renderer/src/components/TabBar.tsx | 144 ++++++ src/renderer/src/components/Terminal.tsx | 465 +++++------------- src/renderer/src/components/TerminalPane.tsx | 260 ++++++++++ .../components/sidebar/AddWorktreeDialog.tsx | 171 +++++++ .../src/components/sidebar/GroupControls.tsx | 57 +++ .../src/components/sidebar/SearchBar.tsx | 89 ++++ .../src/components/sidebar/SidebarHeader.tsx | 34 ++ .../src/components/sidebar/SidebarToolbar.tsx | 48 ++ .../components/sidebar/StatusIndicator.tsx | 70 +++ .../src/components/sidebar/WorktreeCard.tsx | 246 +++++++++ .../sidebar/WorktreeContextMenu.tsx | 116 +++++ .../src/components/sidebar/WorktreeList.tsx | 173 +++++++ src/renderer/src/components/sidebar/index.tsx | 102 ++++ src/renderer/src/components/ui/badge.tsx | 46 ++ src/renderer/src/components/ui/button.tsx | 62 +++ src/renderer/src/components/ui/card.tsx | 75 +++ .../src/components/ui/context-menu.tsx | 222 +++++++++ src/renderer/src/components/ui/dialog.tsx | 144 ++++++ .../src/components/ui/dropdown-menu.tsx | 226 +++++++++ src/renderer/src/components/ui/hover-card.tsx | 38 ++ src/renderer/src/components/ui/input.tsx | 21 + src/renderer/src/components/ui/label.tsx | 21 + .../src/components/ui/scroll-area.tsx | 54 ++ src/renderer/src/components/ui/select.tsx | 175 +++++++ src/renderer/src/components/ui/separator.tsx | 26 + src/renderer/src/components/ui/tabs.tsx | 81 +++ .../src/components/ui/toggle-group.tsx | 82 +++ src/renderer/src/components/ui/toggle.tsx | 44 ++ src/renderer/src/components/ui/tooltip.tsx | 51 ++ src/renderer/src/hooks/useIpcEvents.ts | 22 + src/renderer/src/store.ts | 47 -- src/renderer/src/store/index.ts | 19 + src/renderer/src/store/selectors.ts | 37 ++ src/renderer/src/store/slices/github.ts | 54 ++ src/renderer/src/store/slices/repos.ts | 68 +++ src/renderer/src/store/slices/settings.ts | 33 ++ src/renderer/src/store/slices/terminals.ts | 94 ++++ src/renderer/src/store/slices/ui.ts | 55 +++ src/renderer/src/store/slices/worktrees.ts | 89 ++++ src/renderer/src/store/types.ts | 13 + src/shared/constants.ts | 40 ++ src/shared/types.ts | 104 ++++ tsconfig.node.json | 2 +- tsconfig.web.json | 3 +- 66 files changed, 5230 insertions(+), 628 deletions(-) create mode 100644 src/main/git/repo.ts create mode 100644 src/main/git/worktree.ts create mode 100644 src/main/github/client.ts create mode 100644 src/main/hooks.ts create mode 100644 src/main/ipc/github.ts create mode 100644 src/main/ipc/pty.ts create mode 100644 src/main/ipc/repos.ts create mode 100644 src/main/ipc/settings.ts create mode 100644 src/main/ipc/shell.ts create mode 100644 src/main/ipc/worktrees.ts create mode 100644 src/main/persistence.ts create mode 100644 src/renderer/src/components/Settings.tsx create mode 100644 src/renderer/src/components/TabBar.tsx create mode 100644 src/renderer/src/components/TerminalPane.tsx create mode 100644 src/renderer/src/components/sidebar/AddWorktreeDialog.tsx create mode 100644 src/renderer/src/components/sidebar/GroupControls.tsx create mode 100644 src/renderer/src/components/sidebar/SearchBar.tsx create mode 100644 src/renderer/src/components/sidebar/SidebarHeader.tsx create mode 100644 src/renderer/src/components/sidebar/SidebarToolbar.tsx create mode 100644 src/renderer/src/components/sidebar/StatusIndicator.tsx create mode 100644 src/renderer/src/components/sidebar/WorktreeCard.tsx create mode 100644 src/renderer/src/components/sidebar/WorktreeContextMenu.tsx create mode 100644 src/renderer/src/components/sidebar/WorktreeList.tsx create mode 100644 src/renderer/src/components/sidebar/index.tsx create mode 100644 src/renderer/src/components/ui/badge.tsx create mode 100644 src/renderer/src/components/ui/button.tsx create mode 100644 src/renderer/src/components/ui/card.tsx create mode 100644 src/renderer/src/components/ui/context-menu.tsx create mode 100644 src/renderer/src/components/ui/dialog.tsx create mode 100644 src/renderer/src/components/ui/dropdown-menu.tsx create mode 100644 src/renderer/src/components/ui/hover-card.tsx create mode 100644 src/renderer/src/components/ui/input.tsx create mode 100644 src/renderer/src/components/ui/label.tsx create mode 100644 src/renderer/src/components/ui/scroll-area.tsx create mode 100644 src/renderer/src/components/ui/select.tsx create mode 100644 src/renderer/src/components/ui/separator.tsx create mode 100644 src/renderer/src/components/ui/tabs.tsx create mode 100644 src/renderer/src/components/ui/toggle-group.tsx create mode 100644 src/renderer/src/components/ui/toggle.tsx create mode 100644 src/renderer/src/components/ui/tooltip.tsx create mode 100644 src/renderer/src/hooks/useIpcEvents.ts delete mode 100644 src/renderer/src/store.ts create mode 100644 src/renderer/src/store/index.ts create mode 100644 src/renderer/src/store/selectors.ts create mode 100644 src/renderer/src/store/slices/github.ts create mode 100644 src/renderer/src/store/slices/repos.ts create mode 100644 src/renderer/src/store/slices/settings.ts create mode 100644 src/renderer/src/store/slices/terminals.ts create mode 100644 src/renderer/src/store/slices/ui.ts create mode 100644 src/renderer/src/store/slices/worktrees.ts create mode 100644 src/renderer/src/store/types.ts create mode 100644 src/shared/constants.ts create mode 100644 src/shared/types.ts diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 80304cd37..02e3f6bc7 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -9,7 +9,8 @@ export default defineConfig({ renderer: { resolve: { alias: { - '@renderer': resolve('src/renderer/src') + '@renderer': resolve('src/renderer/src'), + '@': resolve('src/renderer/src') } }, plugins: [react(), tailwindcss()] diff --git a/package.json b/package.json index 19807c603..3ff1d2db1 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,9 @@ "build:linux": "electron-vite build && electron-builder --linux" }, "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@electron-toolkit/preload": "^3.0.2", "@electron-toolkit/utils": "^4.0.0", "class-variance-authority": "^0.7.1", @@ -32,6 +35,7 @@ "radix-ui": "^1.4.3", "restty": "^0.1.34", "shadcn": "^4.0.8", + "simple-git": "^3.33.0", "tailwind-merge": "^3.5.0", "tw-animate-css": "^1.4.0", "zustand": "^5.0.12" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 42aeb6a19..abd5a2345 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8,6 +8,15 @@ importers: .: dependencies: + '@dnd-kit/core': + specifier: ^6.3.1 + version: 6.3.1(react-dom@19.2.4(react@19.2.4))(react@19.2.4) + '@dnd-kit/sortable': + specifier: ^10.0.0 + version: 10.0.0(@dnd-kit/core@6.3.1(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react@19.2.4) + '@dnd-kit/utilities': + specifier: ^3.2.2 + version: 3.2.2(react@19.2.4) '@electron-toolkit/preload': specifier: ^3.0.2 version: 3.0.2(electron@41.0.2) @@ -38,6 +47,9 @@ importers: shadcn: specifier: ^4.0.8 version: 4.0.8(@types/node@25.5.0)(typescript@5.9.3) + simple-git: + specifier: ^3.33.0 + version: 3.33.0 tailwind-merge: specifier: ^3.5.0 version: 3.5.0 @@ -259,6 +271,28 @@ packages: resolution: {integrity: sha512-0cp4PsWQ/9avqTVMCtZ+GirikIA36ikvjtHweU4/j8yLtgObI0+JUPhYFScgwlteveGB1rt3Cm8UhN04XayDig==} engines: {node: '>= 8.9.0'} + '@dnd-kit/accessibility@3.1.1': + resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==} + peerDependencies: + react: '>=16.8.0' + + '@dnd-kit/core@6.3.1': + resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==} + peerDependencies: + react: '>=16.8.0' + react-dom: '>=16.8.0' + + '@dnd-kit/sortable@10.0.0': + resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==} + peerDependencies: + '@dnd-kit/core': ^6.3.0 + react: '>=16.8.0' + + '@dnd-kit/utilities@3.2.2': + resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==} + peerDependencies: + react: '>=16.8.0' + '@dotenvx/dotenvx@1.55.1': resolution: {integrity: sha512-WEuKyoe9CA7dfcFBnNbL0ndbCNcptaEYBygfFo9X1qEG+HD7xku4CYIplw6sbAHJavesZWbVBHeRSpvri0eKqw==} hasBin: true @@ -716,6 +750,12 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@kwsites/file-exists@1.1.1': + resolution: {integrity: sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==} + + '@kwsites/promise-deferred@1.1.1': + resolution: {integrity: sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==} + '@malept/cross-spawn-promise@2.0.0': resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==} engines: {node: '>= 12.13.0'} @@ -3871,6 +3911,9 @@ packages: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} + simple-git@3.33.0: + resolution: {integrity: sha512-D4V/tGC2sjsoNhoMybKyGoE+v8A60hRawKQ1iFRA1zwuDgGZCBJ4ByOzZ5J8joBbi4Oam0qiPH+GhzmSBwbJng==} + simple-update-notifier@2.0.0: resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==} engines: {node: '>=10'} @@ -4552,6 +4595,31 @@ snapshots: ajv: 6.14.0 ajv-keywords: 3.5.2(ajv@6.14.0) + '@dnd-kit/accessibility@3.1.1(react@19.2.4)': + dependencies: + react: 19.2.4 + tslib: 2.8.1 + + '@dnd-kit/core@6.3.1(react-dom@19.2.4(react@19.2.4))(react@19.2.4)': + dependencies: + '@dnd-kit/accessibility': 3.1.1(react@19.2.4) + '@dnd-kit/utilities': 3.2.2(react@19.2.4) + react: 19.2.4 + react-dom: 19.2.4(react@19.2.4) + tslib: 2.8.1 + + '@dnd-kit/sortable@10.0.0(@dnd-kit/core@6.3.1(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(react@19.2.4)': + dependencies: + '@dnd-kit/core': 6.3.1(react-dom@19.2.4(react@19.2.4))(react@19.2.4) + '@dnd-kit/utilities': 3.2.2(react@19.2.4) + react: 19.2.4 + tslib: 2.8.1 + + '@dnd-kit/utilities@3.2.2(react@19.2.4)': + dependencies: + react: 19.2.4 + tslib: 2.8.1 + '@dotenvx/dotenvx@1.55.1': dependencies: commander: 11.1.0 @@ -4917,6 +4985,14 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@kwsites/file-exists@1.1.1': + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + '@kwsites/promise-deferred@1.1.1': {} + '@malept/cross-spawn-promise@2.0.0': dependencies: cross-spawn: 7.0.6 @@ -8259,6 +8335,14 @@ snapshots: signal-exit@4.1.0: {} + simple-git@3.33.0: + dependencies: + '@kwsites/file-exists': 1.1.1 + '@kwsites/promise-deferred': 1.1.1 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + simple-update-notifier@2.0.0: dependencies: semver: 7.7.4 diff --git a/src/main/git/repo.ts b/src/main/git/repo.ts new file mode 100644 index 000000000..2ae89b857 --- /dev/null +++ b/src/main/git/repo.ts @@ -0,0 +1,98 @@ +import { execSync } from 'child_process' +import { existsSync, statSync } from 'fs' +import { join, basename } from 'path' + +/** + * Check if a path is a valid git repository (regular or bare). + */ +export function isGitRepo(path: string): boolean { + try { + if (!existsSync(path) || !statSync(path).isDirectory()) return false + // .git dir or file (for worktrees) or bare repo + if (existsSync(join(path, '.git'))) return true + // Might be a bare repo — ask git + const result = execSync('git rev-parse --is-inside-work-tree', { + cwd: path, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }).trim() + return result === 'true' + } catch { + // Also check if it's a bare repo + try { + const result = execSync('git rev-parse --is-bare-repository', { + cwd: path, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }).trim() + return result === 'true' + } catch { + return false + } + } +} + +/** + * Get a human-readable name for the repo from its path. + */ +export function getRepoName(path: string): string { + const name = basename(path) + // Strip .git suffix from bare repos + return name.endsWith('.git') ? name.slice(0, -4) : name +} + +/** + * Get the remote origin URL, or null if not set. + */ +export function getRemoteUrl(path: string): string | null { + try { + return execSync('git remote get-url origin', { + cwd: path, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }).trim() + } catch { + return null + } +} + +/** + * Get git config user.name for the repo. + */ +export function getGitUsername(path: string): string { + try { + return execSync('git config user.name', { + cwd: path, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }).trim() + } catch { + return '' + } +} + +/** + * Detect the default branch (main or master). + */ +export function getDefaultBranch(path: string): string { + try { + // Check if 'main' branch exists + execSync('git rev-parse --verify main', { + cwd: path, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }) + return 'main' + } catch { + try { + execSync('git rev-parse --verify master', { + cwd: path, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }) + return 'master' + } catch { + return 'main' + } + } +} diff --git a/src/main/git/worktree.ts b/src/main/git/worktree.ts new file mode 100644 index 000000000..9c6f13226 --- /dev/null +++ b/src/main/git/worktree.ts @@ -0,0 +1,87 @@ +import { execSync } from 'child_process' +import type { GitWorktreeInfo } from '../../shared/types' + +/** + * Parse the porcelain output of `git worktree list --porcelain`. + */ +export function parseWorktreeList(output: string): GitWorktreeInfo[] { + const worktrees: GitWorktreeInfo[] = [] + const blocks = output.trim().split('\n\n') + + for (const block of blocks) { + if (!block.trim()) continue + + const lines = block.trim().split('\n') + let path = '' + let head = '' + let branch = '' + let isBare = false + + for (const line of lines) { + if (line.startsWith('worktree ')) { + path = line.slice('worktree '.length) + } else if (line.startsWith('HEAD ')) { + head = line.slice('HEAD '.length) + } else if (line.startsWith('branch ')) { + branch = line.slice('branch '.length) + } else if (line === 'bare') { + isBare = true + } + } + + if (path) { + worktrees.push({ path, head, branch, isBare }) + } + } + + return worktrees +} + +/** + * List all worktrees for a git repo at the given path. + */ +export function listWorktrees(repoPath: string): GitWorktreeInfo[] { + try { + const output = execSync('git worktree list --porcelain', { + cwd: repoPath, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }) + return parseWorktreeList(output) + } catch { + return [] + } +} + +/** + * Create a new worktree. + * @param repoPath - Path to the main repo (or bare repo) + * @param worktreePath - Absolute path where the worktree will be created + * @param branch - Branch name for the new worktree + * @param baseBranch - Optional base branch to create from (defaults to HEAD) + */ +export function addWorktree( + repoPath: string, + worktreePath: string, + branch: string, + baseBranch?: string +): void { + const base = baseBranch ? ` ${baseBranch}` : '' + execSync(`git worktree add -b "${branch}" "${worktreePath}"${base}`, { + cwd: repoPath, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }) +} + +/** + * Remove a worktree. + */ +export function removeWorktree(repoPath: string, worktreePath: string, force = false): void { + const forceFlag = force ? ' --force' : '' + execSync(`git worktree remove "${worktreePath}"${forceFlag}`, { + cwd: repoPath, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }) +} diff --git a/src/main/github/client.ts b/src/main/github/client.ts new file mode 100644 index 000000000..9c4a8df34 --- /dev/null +++ b/src/main/github/client.ts @@ -0,0 +1,126 @@ +import { execSync } from 'child_process' +import type { PRInfo, IssueInfo, CheckStatus } from '../../shared/types' + +/** + * Get PR info for a given branch using gh CLI. + * Returns null if gh is not installed, or no PR exists for the branch. + */ +export function getPRForBranch(repoPath: string, branch: string): PRInfo | null { + try { + // Strip refs/heads/ prefix if present + const branchName = branch.replace(/^refs\/heads\//, '') + const raw = execSync( + `gh pr view "${branchName}" --json number,title,state,url,statusCheckRollup,updatedAt`, + { + cwd: repoPath, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + } + ) + const data = JSON.parse(raw) + return { + number: data.number, + title: data.title, + state: mapPRState(data.state), + url: data.url, + checksStatus: deriveCheckStatus(data.statusCheckRollup), + updatedAt: data.updatedAt + } + } catch { + return null + } +} + +/** + * Get a single issue by number. + */ +export function getIssue(repoPath: string, issueNumber: number): IssueInfo | null { + try { + const raw = execSync(`gh issue view ${issueNumber} --json number,title,state,url,labels`, { + cwd: repoPath, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }) + const data = JSON.parse(raw) + return { + number: data.number, + title: data.title, + state: data.state?.toLowerCase() === 'open' ? 'open' : 'closed', + url: data.url, + labels: (data.labels || []).map((l: { name: string }) => l.name) + } + } catch { + return null + } +} + +/** + * List issues for a repo. + */ +export function listIssues(repoPath: string, limit = 20): IssueInfo[] { + try { + const raw = execSync(`gh issue list --json number,title,state,url,labels --limit ${limit}`, { + cwd: repoPath, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }) + const data = JSON.parse(raw) as Array<{ + number: number + title: string + state: string + url: string + labels: Array<{ name: string }> + }> + return data.map((d) => ({ + number: d.number, + title: d.title, + state: d.state?.toLowerCase() === 'open' ? ('open' as const) : ('closed' as const), + url: d.url, + labels: (d.labels || []).map((l) => l.name) + })) + } catch { + return [] + } +} + +function mapPRState(state: string): PRInfo['state'] { + const s = state?.toUpperCase() + if (s === 'MERGED') return 'merged' + if (s === 'CLOSED') return 'closed' + // gh CLI returns isDraft separately, but state field is OPEN for drafts too + return 'open' +} + +function deriveCheckStatus(rollup: unknown[] | null | undefined): CheckStatus { + if (!rollup || !Array.isArray(rollup) || rollup.length === 0) return 'pending' + + let hasFailure = false + let hasPending = false + + for (const check of rollup as Array<{ status?: string; conclusion?: string; state?: string }>) { + const conclusion = check.conclusion?.toUpperCase() + const status = check.status?.toUpperCase() + const state = check.state?.toUpperCase() + + if ( + conclusion === 'FAILURE' || + conclusion === 'TIMED_OUT' || + conclusion === 'CANCELLED' || + state === 'FAILURE' || + state === 'ERROR' + ) { + hasFailure = true + } else if ( + status === 'IN_PROGRESS' || + status === 'QUEUED' || + status === 'PENDING' || + state === 'PENDING' + ) { + hasPending = true + } + } + + if (hasFailure) return 'failure' + if (hasPending) return 'pending' + return 'success' +} diff --git a/src/main/hooks.ts b/src/main/hooks.ts new file mode 100644 index 000000000..5f4b35530 --- /dev/null +++ b/src/main/hooks.ts @@ -0,0 +1,126 @@ +import { readFileSync, existsSync } from 'fs' +import { join } from 'path' +import { exec } from 'child_process' +import type { OrcaHooks } from '../shared/types' + +const HOOK_TIMEOUT = 120_000 // 2 minutes + +/** + * Parse a simple orca.yaml file. Handles only the `scripts:` block with + * multiline string values (YAML block scalar `|`). + */ +function parseOrcaYaml(content: string): OrcaHooks | null { + const hooks: OrcaHooks = { scripts: {} } + + // Match top-level "scripts:" block + const scriptsMatch = content.match(/^scripts:\s*$/m) + if (!scriptsMatch) return null + + const afterScripts = content.slice(scriptsMatch.index! + scriptsMatch[0].length) + const lines = afterScripts.split('\n') + + let currentKey: 'setup' | 'archive' | null = null + let currentValue = '' + + for (const line of lines) { + // Another top-level key (not indented) — stop parsing scripts block + if (/^\S/.test(line) && line.trim().length > 0) break + + // Indented key like " setup: |" or " archive: |" + const keyMatch = line.match(/^ (setup|archive):\s*\|?\s*$/) + if (keyMatch) { + // Save previous key + if (currentKey) { + hooks.scripts[currentKey] = currentValue.trimEnd() + } + currentKey = keyMatch[1] as 'setup' | 'archive' + currentValue = '' + continue + } + + // Content line (indented by 4+ spaces under a key) + if (currentKey && /^ /.test(line)) { + currentValue += line.slice(4) + '\n' + } + } + + // Save last key + if (currentKey) { + hooks.scripts[currentKey] = currentValue.trimEnd() + } + + if (!hooks.scripts.setup && !hooks.scripts.archive) return null + return hooks +} + +/** + * Load hooks from orca.yaml in the given repo root. + */ +export function loadHooks(repoPath: string): OrcaHooks | null { + const yamlPath = join(repoPath, 'orca.yaml') + if (!existsSync(yamlPath)) return null + + try { + const content = readFileSync(yamlPath, 'utf-8') + return parseOrcaYaml(content) + } catch { + return null + } +} + +/** + * Check whether an orca.yaml exists for a repo. + */ +export function hasHooksFile(repoPath: string): boolean { + return existsSync(join(repoPath, 'orca.yaml')) +} + +/** + * Run a named hook script in the given working directory. + */ +export function runHook( + hookName: 'setup' | 'archive', + cwd: string, + repoPath: string +): Promise<{ success: boolean; output: string }> { + const hooks = loadHooks(repoPath) + const script = hooks?.scripts[hookName] + + if (!script) { + return Promise.resolve({ success: true, output: '' }) + } + + return new Promise((resolve) => { + exec( + script, + { + cwd, + timeout: HOOK_TIMEOUT, + shell: '/bin/bash', + env: { + ...process.env, + ORCA_ROOT_PATH: repoPath, + ORCA_WORKTREE_PATH: cwd, + // Compat with conductor.json users + CONDUCTOR_ROOT_PATH: repoPath, + GHOSTX_ROOT_PATH: repoPath + } + }, + (error, stdout, stderr) => { + if (error) { + console.error(`[hooks] ${hookName} hook failed in ${cwd}:`, error.message) + resolve({ + success: false, + output: `${stdout}\n${stderr}\n${error.message}`.trim() + }) + } else { + console.log(`[hooks] ${hookName} hook completed in ${cwd}`) + resolve({ + success: true, + output: `${stdout}\n${stderr}`.trim() + }) + } + } + ) + }) +} diff --git a/src/main/index.ts b/src/main/index.ts index 01a755a5d..20cb4356a 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1,21 +1,21 @@ -import { app, shell, BrowserWindow, ipcMain, Menu, nativeImage } from 'electron' +import { app, shell, BrowserWindow, Menu, nativeImage } from 'electron' import { join } from 'path' -import { execSync } from 'child_process' import { electronApp, optimizer, is } from '@electron-toolkit/utils' import icon from '../../resources/icon.png?asset' import devIcon from '../../resources/icon-dev.png?asset' -import * as pty from 'node-pty' + +import { Store } from './persistence' +import { registerRepoHandlers } from './ipc/repos' +import { registerWorktreeHandlers } from './ipc/worktrees' +import { registerPtyHandlers, killAllPty } from './ipc/pty' +import { registerGitHubHandlers } from './ipc/github' +import { registerSettingsHandlers } from './ipc/settings' +import { registerShellHandlers } from './ipc/shell' // Enable WebGPU in Electron app.commandLine.appendSwitch('enable-features', 'Vulkan,UseSkiaGraphite') app.commandLine.appendSwitch('enable-unsafe-webgpu') -// --------------------------------------------------------------------------- -// PTY instance tracking -// --------------------------------------------------------------------------- -let ptyCounter = 0 -const ptyProcesses = new Map() - // --------------------------------------------------------------------------- // Window creation // --------------------------------------------------------------------------- @@ -56,49 +56,6 @@ function createWindow(): BrowserWindow { return mainWindow } -// --------------------------------------------------------------------------- -// Worktree helpers -// --------------------------------------------------------------------------- -interface WorktreeInfo { - path: string - head: string - branch: string - isBare: boolean -} - -function parseWorktreeList(output: string): WorktreeInfo[] { - const worktrees: WorktreeInfo[] = [] - const blocks = output.trim().split('\n\n') - - for (const block of blocks) { - if (!block.trim()) continue - - const lines = block.trim().split('\n') - let path = '' - let head = '' - let branch = '' - let isBare = false - - for (const line of lines) { - if (line.startsWith('worktree ')) { - path = line.slice('worktree '.length) - } else if (line.startsWith('HEAD ')) { - head = line.slice('HEAD '.length) - } else if (line.startsWith('branch ')) { - branch = line.slice('branch '.length) - } else if (line === 'bare') { - isBare = true - } - } - - if (path) { - worktrees.push({ path, head, branch, isBare }) - } - } - - return worktrees -} - // --------------------------------------------------------------------------- // App lifecycle // --------------------------------------------------------------------------- @@ -108,7 +65,7 @@ app.whenReady().then(() => { if (process.platform === 'darwin') { const dockIcon = nativeImage.createFromPath(is.dev ? devIcon : icon) - app.dock.setIcon(dockIcon) + app.dock?.setIcon(dockIcon) } app.on('browser-window-created', (_, window) => { @@ -165,101 +122,21 @@ app.whenReady().then(() => { ] Menu.setApplicationMenu(Menu.buildFromTemplate(template)) + // Initialize persistence + const store = new Store() + + // Create window const mainWindow = createWindow() - // ------------------------------------------------------------------------- - // PTY IPC handlers - // ------------------------------------------------------------------------- - ipcMain.handle('pty:spawn', (_event, args: { cols: number; rows: number; cwd?: string }) => { - const id = String(++ptyCounter) - const shell = process.env.SHELL || '/bin/zsh' + // Register all IPC handlers + registerRepoHandlers(mainWindow, store) + registerWorktreeHandlers(mainWindow, store) + registerPtyHandlers(mainWindow) + registerGitHubHandlers() + registerSettingsHandlers(store) + registerShellHandlers() - const ptyProcess = pty.spawn(shell, [], { - name: 'xterm-256color', - cols: args.cols, - rows: args.rows, - cwd: args.cwd || process.env.HOME || '/', - env: { - ...process.env, - TERM: 'xterm-256color', - COLORTERM: 'truecolor' - } as Record - }) - - ptyProcesses.set(id, ptyProcess) - - ptyProcess.onData((data) => { - if (!mainWindow.isDestroyed()) { - mainWindow.webContents.send('pty:data', { id, data }) - } - }) - - ptyProcess.onExit(({ exitCode }) => { - ptyProcesses.delete(id) - if (!mainWindow.isDestroyed()) { - mainWindow.webContents.send('pty:exit', { id, code: exitCode }) - } - }) - - return { id } - }) - - ipcMain.on('pty:write', (_event, args: { id: string; data: string }) => { - const proc = ptyProcesses.get(args.id) - if (proc) { - proc.write(args.data) - } - }) - - ipcMain.handle('pty:resize', (_event, args: { id: string; cols: number; rows: number }) => { - const proc = ptyProcesses.get(args.id) - if (proc) { - proc.resize(args.cols, args.rows) - } - }) - - ipcMain.handle('pty:kill', (_event, args: { id: string }) => { - const proc = ptyProcesses.get(args.id) - if (proc) { - proc.kill() - ptyProcesses.delete(args.id) - } - }) - - // ------------------------------------------------------------------------- - // Worktree IPC handlers - // ------------------------------------------------------------------------- - ipcMain.handle('worktrees:list', (_event, args: { cwd: string }): WorktreeInfo[] => { - try { - const output = execSync('git worktree list --porcelain', { - cwd: args.cwd, - encoding: 'utf-8' - }) - return parseWorktreeList(output) - } catch { - return [] - } - }) - - ipcMain.handle('worktrees:get-current', (_event): WorktreeInfo[] => { - try { - const repoRoot = execSync('git rev-parse --show-toplevel', { - encoding: 'utf-8' - }).trim() - - const output = execSync('git worktree list --porcelain', { - cwd: repoRoot, - encoding: 'utf-8' - }) - return parseWorktreeList(output) - } catch { - return [] - } - }) - - // ------------------------------------------------------------------------- // macOS re-activate - // ------------------------------------------------------------------------- app.on('activate', function () { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) @@ -269,10 +146,7 @@ app.whenReady().then(() => { // Cleanup // --------------------------------------------------------------------------- app.on('before-quit', () => { - for (const [id, proc] of ptyProcesses) { - proc.kill() - ptyProcesses.delete(id) - } + killAllPty() }) app.on('window-all-closed', () => { diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts new file mode 100644 index 000000000..243bbd5ef --- /dev/null +++ b/src/main/ipc/github.ts @@ -0,0 +1,16 @@ +import { ipcMain } from 'electron' +import { getPRForBranch, getIssue, listIssues } from '../github/client' + +export function registerGitHubHandlers(): void { + ipcMain.handle('gh:prForBranch', (_event, args: { repoPath: string; branch: string }) => { + return getPRForBranch(args.repoPath, args.branch) + }) + + ipcMain.handle('gh:issue', (_event, args: { repoPath: string; number: number }) => { + return getIssue(args.repoPath, args.number) + }) + + ipcMain.handle('gh:listIssues', (_event, args: { repoPath: string; limit?: number }) => { + return listIssues(args.repoPath, args.limit) + }) +} diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts new file mode 100644 index 000000000..47102180f --- /dev/null +++ b/src/main/ipc/pty.ts @@ -0,0 +1,73 @@ +import { BrowserWindow, ipcMain } from 'electron' +import * as pty from 'node-pty' + +let ptyCounter = 0 +const ptyProcesses = new Map() + +export function registerPtyHandlers(mainWindow: BrowserWindow): void { + ipcMain.handle('pty:spawn', (_event, args: { cols: number; rows: number; cwd?: string }) => { + const id = String(++ptyCounter) + const shellPath = process.env.SHELL || '/bin/zsh' + + const ptyProcess = pty.spawn(shellPath, [], { + name: 'xterm-256color', + cols: args.cols, + rows: args.rows, + cwd: args.cwd || process.env.HOME || '/', + env: { + ...process.env, + TERM: 'xterm-256color', + COLORTERM: 'truecolor' + } as Record + }) + + ptyProcesses.set(id, ptyProcess) + + ptyProcess.onData((data) => { + if (!mainWindow.isDestroyed()) { + mainWindow.webContents.send('pty:data', { id, data }) + } + }) + + ptyProcess.onExit(({ exitCode }) => { + ptyProcesses.delete(id) + if (!mainWindow.isDestroyed()) { + mainWindow.webContents.send('pty:exit', { id, code: exitCode }) + } + }) + + return { id } + }) + + ipcMain.on('pty:write', (_event, args: { id: string; data: string }) => { + const proc = ptyProcesses.get(args.id) + if (proc) { + proc.write(args.data) + } + }) + + ipcMain.handle('pty:resize', (_event, args: { id: string; cols: number; rows: number }) => { + const proc = ptyProcesses.get(args.id) + if (proc) { + proc.resize(args.cols, args.rows) + } + }) + + ipcMain.handle('pty:kill', (_event, args: { id: string }) => { + const proc = ptyProcesses.get(args.id) + if (proc) { + proc.kill() + ptyProcesses.delete(args.id) + } + }) +} + +/** + * Kill all PTY processes. Call on app quit. + */ +export function killAllPty(): void { + for (const [id, proc] of ptyProcesses) { + proc.kill() + ptyProcesses.delete(id) + } +} diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts new file mode 100644 index 000000000..b22888b15 --- /dev/null +++ b/src/main/ipc/repos.ts @@ -0,0 +1,65 @@ +import { BrowserWindow, dialog, ipcMain } from 'electron' +import { randomUUID } from 'crypto' +import type { Store } from '../persistence' +import type { Repo } from '../../shared/types' +import { REPO_COLORS } from '../../shared/constants' +import { isGitRepo, getRepoName } from '../git/repo' + +export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): void { + ipcMain.handle('repos:list', () => { + return store.getRepos() + }) + + ipcMain.handle('repos:add', async (_event, args: { path: string }) => { + if (!isGitRepo(args.path)) { + throw new Error(`Not a valid git repository: ${args.path}`) + } + + // Check if already added + const existing = store.getRepos().find((r) => r.path === args.path) + if (existing) return existing + + const repo: Repo = { + id: randomUUID(), + path: args.path, + displayName: getRepoName(args.path), + badgeColor: REPO_COLORS[store.getRepos().length % REPO_COLORS.length], + addedAt: Date.now() + } + + store.addRepo(repo) + notifyReposChanged(mainWindow) + return repo + }) + + ipcMain.handle('repos:remove', (_event, args: { repoId: string }) => { + store.removeRepo(args.repoId) + notifyReposChanged(mainWindow) + }) + + ipcMain.handle( + 'repos:update', + ( + _event, + args: { repoId: string; updates: Partial> } + ) => { + const updated = store.updateRepo(args.repoId, args.updates) + if (updated) notifyReposChanged(mainWindow) + return updated + } + ) + + ipcMain.handle('repos:pickFolder', async () => { + const result = await dialog.showOpenDialog(mainWindow, { + properties: ['openDirectory'] + }) + if (result.canceled || result.filePaths.length === 0) return null + return result.filePaths[0] + }) +} + +function notifyReposChanged(mainWindow: BrowserWindow): void { + if (!mainWindow.isDestroyed()) { + mainWindow.webContents.send('repos:changed') + } +} diff --git a/src/main/ipc/settings.ts b/src/main/ipc/settings.ts new file mode 100644 index 000000000..ab4dddd0b --- /dev/null +++ b/src/main/ipc/settings.ts @@ -0,0 +1,13 @@ +import { ipcMain } from 'electron' +import type { Store } from '../persistence' +import type { GlobalSettings } from '../../shared/types' + +export function registerSettingsHandlers(store: Store): void { + ipcMain.handle('settings:get', () => { + return store.getSettings() + }) + + ipcMain.handle('settings:set', (_event, args: Partial) => { + return store.updateSettings(args) + }) +} diff --git a/src/main/ipc/shell.ts b/src/main/ipc/shell.ts new file mode 100644 index 000000000..bf8b90d56 --- /dev/null +++ b/src/main/ipc/shell.ts @@ -0,0 +1,11 @@ +import { ipcMain, shell } from 'electron' + +export function registerShellHandlers(): void { + ipcMain.handle('shell:openPath', (_event, path: string) => { + shell.showItemInFolder(path) + }) + + ipcMain.handle('shell:openExternal', (_event, url: string) => { + return shell.openExternal(url) + }) +} diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts new file mode 100644 index 000000000..1ba1d56e0 --- /dev/null +++ b/src/main/ipc/worktrees.ts @@ -0,0 +1,175 @@ +import { BrowserWindow, ipcMain } from 'electron' +import { join, basename } from 'path' +import type { Store } from '../persistence' +import type { Worktree, WorktreeMeta } from '../../shared/types' +import { listWorktrees, addWorktree, removeWorktree } from '../git/worktree' +import { getGitUsername, getDefaultBranch } from '../git/repo' +import { loadHooks, runHook, hasHooksFile } from '../hooks' + +export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store): void { + ipcMain.handle('worktrees:listAll', () => { + const repos = store.getRepos() + const allWorktrees: Worktree[] = [] + + for (const repo of repos) { + const gitWorktrees = listWorktrees(repo.path) + for (const gw of gitWorktrees) { + const worktreeId = `${repo.id}::${gw.path}` + const meta = store.getWorktreeMeta(worktreeId) + allWorktrees.push(mergeWorktree(repo.id, gw, meta)) + } + } + + return allWorktrees + }) + + ipcMain.handle('worktrees:list', (_event, args: { repoId: string }) => { + const repo = store.getRepo(args.repoId) + if (!repo) return [] + + const gitWorktrees = listWorktrees(repo.path) + return gitWorktrees.map((gw) => { + const worktreeId = `${repo.id}::${gw.path}` + const meta = store.getWorktreeMeta(worktreeId) + return mergeWorktree(repo.id, gw, meta) + }) + }) + + ipcMain.handle( + 'worktrees:create', + (_event, args: { repoId: string; name: string; baseBranch?: string }) => { + const repo = store.getRepo(args.repoId) + if (!repo) throw new Error(`Repo not found: ${args.repoId}`) + + const settings = store.getSettings() + + // Compute branch name with prefix + let branchName = args.name + if (settings.branchPrefix === 'git-username') { + const username = getGitUsername(repo.path) + if (username) { + branchName = `${username}/${args.name}` + } + } else if (settings.branchPrefix === 'custom' && settings.branchPrefixCustom) { + branchName = `${settings.branchPrefixCustom}/${args.name}` + } + + // Compute worktree path + let worktreePath: string + if (settings.nestWorkspaces) { + const repoName = basename(repo.path).replace(/\.git$/, '') + worktreePath = join(settings.workspaceDir, repoName, args.name) + } else { + worktreePath = join(settings.workspaceDir, args.name) + } + + // Determine base branch + const baseBranch = args.baseBranch || getDefaultBranch(repo.path) + + addWorktree(repo.path, worktreePath, branchName, baseBranch) + + // Re-list to get the freshly created worktree info + const gitWorktrees = listWorktrees(repo.path) + const created = gitWorktrees.find((gw) => gw.path === worktreePath) + if (!created) throw new Error('Worktree created but not found in listing') + + const worktree = mergeWorktree(repo.id, created, undefined) + + // Run setup hook asynchronously (don't block the UI) + const hooks = loadHooks(repo.path) + if (hooks?.scripts.setup) { + runHook('setup', worktreePath, repo.path).then((result) => { + if (!result.success) { + console.error(`[hooks] setup hook failed for ${worktreePath}:`, result.output) + } + }) + } + + notifyWorktreesChanged(mainWindow, repo.id) + return worktree + } + ) + + ipcMain.handle( + 'worktrees:remove', + async (_event, args: { worktreeId: string; force?: boolean }) => { + const { repoId, worktreePath } = parseWorktreeId(args.worktreeId) + const repo = store.getRepo(repoId) + if (!repo) throw new Error(`Repo not found: ${repoId}`) + + // Run archive hook before removal + const hooks = loadHooks(repo.path) + if (hooks?.scripts.archive) { + const result = await runHook('archive', worktreePath, repo.path) + if (!result.success) { + console.error(`[hooks] archive hook failed for ${worktreePath}:`, result.output) + } + } + + removeWorktree(repo.path, worktreePath, args.force ?? false) + store.removeWorktreeMeta(args.worktreeId) + + notifyWorktreesChanged(mainWindow, repoId) + } + ) + + ipcMain.handle( + 'worktrees:updateMeta', + (_event, args: { worktreeId: string; updates: Partial }) => { + const meta = store.setWorktreeMeta(args.worktreeId, args.updates) + const { repoId } = parseWorktreeId(args.worktreeId) + notifyWorktreesChanged(mainWindow, repoId) + return meta + } + ) + + ipcMain.handle('hooks:check', (_event, args: { repoId: string }) => { + const repo = store.getRepo(args.repoId) + if (!repo) return { hasHooks: false, hooks: null } + + const has = hasHooksFile(repo.path) + const hooks = has ? loadHooks(repo.path) : null + return { + hasHooks: has, + hooks + } + }) +} + +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 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 }) + } +} diff --git a/src/main/persistence.ts b/src/main/persistence.ts new file mode 100644 index 000000000..3f5b1fc3d --- /dev/null +++ b/src/main/persistence.ts @@ -0,0 +1,160 @@ +import { app } from 'electron' +import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs' +import { join, dirname } from 'path' +import { homedir } from 'os' +import type { PersistedState, Repo, WorktreeMeta, GlobalSettings } from '../shared/types' +import { getDefaultPersistedState } from '../shared/constants' + +const DATA_FILE = join(app.getPath('userData'), 'orca-data.json') + +export class Store { + private state: PersistedState + private writeTimer: ReturnType | null = null + + constructor() { + this.state = this.load() + } + + private load(): PersistedState { + try { + if (existsSync(DATA_FILE)) { + const raw = readFileSync(DATA_FILE, 'utf-8') + const parsed = JSON.parse(raw) as PersistedState + // Merge with defaults in case new fields were added + const defaults = getDefaultPersistedState(homedir()) + return { + ...defaults, + ...parsed, + settings: { ...defaults.settings, ...parsed.settings }, + ui: { ...defaults.ui, ...parsed.ui } + } + } + } catch (err) { + console.error('[persistence] Failed to load state, using defaults:', err) + } + return getDefaultPersistedState(homedir()) + } + + private scheduleSave(): void { + if (this.writeTimer) clearTimeout(this.writeTimer) + this.writeTimer = setTimeout(() => { + this.writeTimer = null + try { + const dir = dirname(DATA_FILE) + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }) + writeFileSync(DATA_FILE, JSON.stringify(this.state, null, 2), 'utf-8') + } catch (err) { + console.error('[persistence] Failed to write state:', err) + } + }, 300) + } + + // ── Repos ────────────────────────────────────────────────────────── + + getRepos(): Repo[] { + return this.state.repos + } + + getRepo(id: string): Repo | undefined { + return this.state.repos.find((r) => r.id === id) + } + + addRepo(repo: Repo): void { + this.state.repos.push(repo) + this.scheduleSave() + } + + removeRepo(id: string): void { + this.state.repos = this.state.repos.filter((r) => r.id !== id) + // Clean up worktree meta for this repo + const prefix = `${id}::` + for (const key of Object.keys(this.state.worktreeMeta)) { + if (key.startsWith(prefix)) { + delete this.state.worktreeMeta[key] + } + } + this.scheduleSave() + } + + updateRepo(id: string, updates: Partial>): Repo | null { + const repo = this.state.repos.find((r) => r.id === id) + if (!repo) return null + Object.assign(repo, updates) + this.scheduleSave() + return repo + } + + // ── Worktree Meta ────────────────────────────────────────────────── + + getWorktreeMeta(worktreeId: string): WorktreeMeta | undefined { + return this.state.worktreeMeta[worktreeId] + } + + getAllWorktreeMeta(): Record { + return this.state.worktreeMeta + } + + setWorktreeMeta(worktreeId: string, meta: Partial): WorktreeMeta { + const existing = this.state.worktreeMeta[worktreeId] || getDefaultWorktreeMeta() + const updated = { ...existing, ...meta } + this.state.worktreeMeta[worktreeId] = updated + this.scheduleSave() + return updated + } + + removeWorktreeMeta(worktreeId: string): void { + delete this.state.worktreeMeta[worktreeId] + this.scheduleSave() + } + + // ── Settings ─────────────────────────────────────────────────────── + + getSettings(): GlobalSettings { + return this.state.settings + } + + updateSettings(updates: Partial): GlobalSettings { + this.state.settings = { ...this.state.settings, ...updates } + this.scheduleSave() + return this.state.settings + } + + // ── UI State ─────────────────────────────────────────────────────── + + getUI(): PersistedState['ui'] { + return this.state.ui + } + + updateUI(updates: Partial): void { + this.state.ui = { ...this.state.ui, ...updates } + this.scheduleSave() + } + + // ── Flush (for shutdown) ─────────────────────────────────────────── + + flush(): void { + if (this.writeTimer) { + clearTimeout(this.writeTimer) + this.writeTimer = null + } + try { + const dir = dirname(DATA_FILE) + if (!existsSync(dir)) mkdirSync(dir, { recursive: true }) + writeFileSync(DATA_FILE, JSON.stringify(this.state, null, 2), 'utf-8') + } catch (err) { + console.error('[persistence] Failed to flush state:', err) + } + } +} + +function getDefaultWorktreeMeta(): WorktreeMeta { + return { + displayName: '', + comment: '', + linkedIssue: null, + linkedPR: null, + isArchived: false, + isUnread: false, + sortOrder: 0 + } +} diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 47da95943..6c9fc96d5 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -1,10 +1,33 @@ import { ElectronAPI } from '@electron-toolkit/preload' +import type { + Repo, + Worktree, + WorktreeMeta, + PRInfo, + IssueInfo, + GlobalSettings, + OrcaHooks +} from '../../shared/types' -interface WorktreeInfo { - path: string - head: string - branch: string - isBare: boolean +interface ReposApi { + list: () => Promise + add: (args: { path: string }) => Promise + remove: (args: { repoId: string }) => Promise + update: (args: { + repoId: string + updates: Partial> + }) => Promise + pickFolder: () => Promise + onChanged: (callback: () => void) => () => void +} + +interface WorktreesApi { + list: (args: { repoId: string }) => Promise + listAll: () => Promise + create: (args: { repoId: string; name: string; baseBranch?: string }) => Promise + remove: (args: { worktreeId: string; force?: boolean }) => Promise + updateMeta: (args: { worktreeId: string; updates: Partial }) => Promise + onChanged: (callback: (data: { repoId: string }) => void) => () => void } interface PtyApi { @@ -16,14 +39,34 @@ interface PtyApi { onExit: (callback: (data: { id: string; code: number }) => void) => () => void } -interface WorktreesApi { - list: (cwd: string) => Promise - getCurrent: () => Promise +interface GhApi { + prForBranch: (args: { repoPath: string; branch: string }) => Promise + issue: (args: { repoPath: string; number: number }) => Promise + listIssues: (args: { repoPath: string; limit?: number }) => Promise +} + +interface SettingsApi { + get: () => Promise + set: (args: Partial) => Promise +} + +interface ShellApi { + openPath: (path: string) => Promise + openExternal: (url: string) => Promise +} + +interface HooksApi { + check: (args: { repoId: string }) => Promise<{ hasHooks: boolean; hooks: OrcaHooks | null }> } interface Api { - pty: PtyApi + repos: ReposApi worktrees: WorktreesApi + pty: PtyApi + gh: GhApi + settings: SettingsApi + shell: ShellApi + hooks: HooksApi } declare global { diff --git a/src/preload/index.ts b/src/preload/index.ts index 3e3571ff1..98f73905b 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -3,6 +3,50 @@ import { electronAPI } from '@electron-toolkit/preload' // Custom APIs for renderer const api = { + repos: { + list: (): Promise => ipcRenderer.invoke('repos:list'), + + add: (args: { path: string }): Promise => ipcRenderer.invoke('repos:add', args), + + remove: (args: { repoId: string }): Promise => ipcRenderer.invoke('repos:remove', args), + + update: (args: { repoId: string; updates: Record }): Promise => + ipcRenderer.invoke('repos:update', args), + + pickFolder: (): Promise => ipcRenderer.invoke('repos:pickFolder'), + + onChanged: (callback: () => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent) => callback() + ipcRenderer.on('repos:changed', listener) + return () => ipcRenderer.removeListener('repos:changed', listener) + } + }, + + worktrees: { + list: (args: { repoId: string }): Promise => + ipcRenderer.invoke('worktrees:list', args), + + listAll: (): Promise => ipcRenderer.invoke('worktrees:listAll'), + + create: (args: { repoId: string; name: string; baseBranch?: string }): Promise => + ipcRenderer.invoke('worktrees:create', args), + + remove: (args: { worktreeId: string; force?: boolean }): Promise => + ipcRenderer.invoke('worktrees:remove', args), + + updateMeta: (args: { + worktreeId: string + updates: Record + }): Promise => ipcRenderer.invoke('worktrees:updateMeta', args), + + onChanged: (callback: (data: { repoId: string }) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, data: { repoId: string }) => + callback(data) + ipcRenderer.on('worktrees:changed', listener) + return () => ipcRenderer.removeListener('worktrees:changed', listener) + } + }, + pty: { spawn: (opts: { cols: number; rows: number; cwd?: string }): Promise<{ id: string }> => ipcRenderer.invoke('pty:spawn', opts), @@ -32,15 +76,33 @@ const api = { } }, - worktrees: { - list: ( - cwd: string - ): Promise> => - ipcRenderer.invoke('worktrees:list', { cwd }), + gh: { + prForBranch: (args: { repoPath: string; branch: string }): Promise => + ipcRenderer.invoke('gh:prForBranch', args), - getCurrent: (): Promise< - Array<{ path: string; head: string; branch: string; isBare: boolean }> - > => ipcRenderer.invoke('worktrees:get-current') + issue: (args: { repoPath: string; number: number }): Promise => + ipcRenderer.invoke('gh:issue', args), + + listIssues: (args: { repoPath: string; limit?: number }): Promise => + ipcRenderer.invoke('gh:listIssues', args) + }, + + settings: { + get: (): Promise => ipcRenderer.invoke('settings:get'), + + set: (args: Record): Promise => + ipcRenderer.invoke('settings:set', args) + }, + + shell: { + openPath: (path: string): Promise => ipcRenderer.invoke('shell:openPath', path), + + openExternal: (url: string): Promise => ipcRenderer.invoke('shell:openExternal', url) + }, + + hooks: { + check: (args: { repoId: string }): Promise<{ hasHooks: boolean; hooks: unknown }> => + ipcRenderer.invoke('hooks:check', args) } } diff --git a/src/renderer/index.html b/src/renderer/index.html index b74c4d75d..ba84d774e 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -3,11 +3,7 @@ Orca - - + diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index fed553e4e..33c0c1aec 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -1,30 +1,29 @@ import { useEffect } from 'react' import { useAppStore } from './store' +import { useIpcEvents } from './hooks/useIpcEvents' import Sidebar from './components/Sidebar' import Terminal from './components/Terminal' import Landing from './components/Landing' +import Settings from './components/Settings' function App(): React.JSX.Element { const toggleSidebar = useAppStore((s) => s.toggleSidebar) - const showTerminal = useAppStore((s) => s.showTerminal) - const setShowTerminal = useAppStore((s) => s.setShowTerminal) - const terminalTitle = useAppStore((s) => s.terminalTitle) + const activeView = useAppStore((s) => s.activeView) + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) + const fetchRepos = useAppStore((s) => s.fetchRepos) + const fetchSettings = useAppStore((s) => s.fetchSettings) - // Enter key on landing page to spawn a new terminal + // Subscribe to IPC push events + useIpcEvents() + + // Fetch initial data useEffect(() => { - if (showTerminal) return - const onKeyDown = (e: KeyboardEvent): void => { - if (e.key === 'Enter' && !e.repeat) { - e.preventDefault() - setShowTerminal(true) - } - } - window.addEventListener('keydown', onKeyDown) - return () => window.removeEventListener('keydown', onKeyDown) - }, [showTerminal, setShowTerminal]) + fetchRepos() + fetchSettings() + }, [fetchRepos, fetchSettings]) return ( -
+
-
- {showTerminal && terminalTitle ? terminalTitle : 'Orca'} -
+
Orca
-
+
- {showTerminal ? : } + {activeView === 'settings' ? : activeWorktreeId ? : }
) diff --git a/src/renderer/src/components/Landing.tsx b/src/renderer/src/components/Landing.tsx index 3f41696ad..0ea07b42d 100644 --- a/src/renderer/src/components/Landing.tsx +++ b/src/renderer/src/components/Landing.tsx @@ -1,16 +1,26 @@ import { useAppStore } from '../store' export default function Landing(): React.JSX.Element { - const setShowTerminal = useAppStore((s) => s.setShowTerminal) + const repos = useAppStore((s) => s.repos) + const addRepo = useAppStore((s) => s.addRepo) return ( -
-
-

Orca

- - or press Enter +
+
+

Orca

+ {repos.length === 0 ? ( + <> +

Get started by adding a repository

+ + + ) : ( +

Select a worktree from the sidebar

+ )}
) diff --git a/src/renderer/src/components/Settings.tsx b/src/renderer/src/components/Settings.tsx new file mode 100644 index 000000000..da59800c0 --- /dev/null +++ b/src/renderer/src/components/Settings.tsx @@ -0,0 +1,373 @@ +import { useEffect, useState, useCallback } from 'react' +import { useAppStore } from '../store' +import { REPO_COLORS } from '../../../shared/constants' +import { ScrollArea } from './ui/scroll-area' +import { Button } from './ui/button' +import { Input } from './ui/input' +import { Label } from './ui/label' +import { Separator } from './ui/separator' +import { ArrowLeft, FolderOpen, Minus, Plus, Trash2 } from 'lucide-react' + +function Settings(): React.JSX.Element { + const settings = useAppStore((s) => s.settings) + const updateSettings = useAppStore((s) => s.updateSettings) + const fetchSettings = useAppStore((s) => s.fetchSettings) + const setActiveView = useAppStore((s) => s.setActiveView) + const repos = useAppStore((s) => s.repos) + const updateRepo = useAppStore((s) => s.updateRepo) + const removeRepo = useAppStore((s) => s.removeRepo) + + const [confirmingRemove, setConfirmingRemove] = useState(null) + const [repoHooksMap, setRepoHooksMap] = useState>({}) + + useEffect(() => { + fetchSettings() + }, [fetchSettings]) + + // Check which repos have orca.yaml hooks + useEffect(() => { + const checkHooks = async () => { + const map: Record = {} + for (const repo of repos) { + try { + const result = await window.api.hooks.check({ repoId: repo.id }) + map[repo.id] = result.hasHooks + } catch { + map[repo.id] = false + } + } + setRepoHooksMap(map) + } + if (repos.length > 0) checkHooks() + }, [repos]) + + // Apply theme immediately + const applyTheme = useCallback((theme: 'system' | 'dark' | 'light') => { + const root = document.documentElement + if (theme === 'dark') { + root.classList.add('dark') + } else if (theme === 'light') { + root.classList.remove('dark') + } else { + // system + const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches + if (prefersDark) { + root.classList.add('dark') + } else { + root.classList.remove('dark') + } + } + }, []) + + const handleBrowseWorkspace = async () => { + const path = await window.api.repos.pickFolder() + if (path) { + updateSettings({ workspaceDir: path }) + } + } + + const handleRemoveRepo = (repoId: string) => { + if (confirmingRemove === repoId) { + removeRepo(repoId) + setConfirmingRemove(null) + } else { + setConfirmingRemove(repoId) + } + } + + if (!settings) { + return ( +
+ Loading settings... +
+ ) + } + + return ( +
+ {/* Header */} +
+ +

Settings

+
+ + {/* Content */} + +
+ {/* ── Workspace ────────────────────────────────────── */} +
+

Workspace

+ + {/* Workspace Directory */} +
+ +

+ Root directory where worktree folders are created. +

+
+ updateSettings({ workspaceDir: e.target.value })} + className="flex-1 font-mono text-xs" + /> + +
+
+ + {/* Nest Workspaces */} +
+
+ +

+ Create worktrees inside a repo-named subfolder. +

+
+ +
+
+ + + + {/* ── Branch Prefix ────────────────────────────────── */} +
+

Branch Naming

+ +
+ +

+ Prefix added to branch names when creating worktrees. +

+
+ {(['git-username', 'custom', 'none'] as const).map((option) => ( + + ))} +
+ {settings.branchPrefix === 'custom' && ( + updateSettings({ branchPrefixCustom: e.target.value })} + placeholder="e.g. feature/" + className="max-w-xs mt-2" + /> + )} +
+
+ + + + {/* ── Appearance ───────────────────────────────────── */} +
+

Appearance

+ + {/* Theme */} +
+ +
+ {(['system', 'dark', 'light'] as const).map((option) => ( + + ))} +
+
+
+ + + + {/* ── Terminal ─────────────────────────────────────── */} +
+

Terminal

+ + {/* Font Size */} +
+ +
+ + { + const val = parseInt(e.target.value, 10) + if (!isNaN(val) && val >= 10 && val <= 24) { + updateSettings({ terminalFontSize: val }) + } + }} + className="w-16 text-center tabular-nums" + /> + + px +
+
+ + {/* Font Family */} +
+ + updateSettings({ terminalFontFamily: e.target.value })} + placeholder="SF Mono" + className="max-w-xs" + /> +
+
+ + + + {/* ── Repos ────────────────────────────────────────── */} +
+

Repositories

+

+ Manage display names and badge colors for your repositories. +

+ + {repos.length === 0 ? ( +

No repositories added yet.

+ ) : ( +
+ {repos.map((repo) => ( +
+ {/* Color picker */} +
+ {REPO_COLORS.map((color) => ( +
+ + {/* Display name */} + updateRepo(repo.id, { displayName: e.target.value })} + className="flex-1 h-8 text-sm" + /> + + {/* Hooks indicator */} + {repoHooksMap[repo.id] && ( + + hooks + + )} + + {/* Remove */} + +
+ ))} +
+ )} +
+ + {/* Bottom spacing */} +
+
+ +
+ ) +} + +export default Settings diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsx index 6cd7cb0ed..f14f3ce5d 100644 --- a/src/renderer/src/components/Sidebar.tsx +++ b/src/renderer/src/components/Sidebar.tsx @@ -1,42 +1 @@ -import { useEffect } from 'react' -import { useAppStore } from '../store' - -function branchDisplayName(branch: string): string { - return branch.replace(/^refs\/heads\//, '') -} - -function pathBasename(p: string): string { - return p.split('/').pop() || p -} - -export default function Sidebar(): React.JSX.Element { - const sidebarOpen = useAppStore((s) => s.sidebarOpen) - const worktrees = useAppStore((s) => s.worktrees) - const activeWorktree = useAppStore((s) => s.activeWorktree) - const setActiveWorktree = useAppStore((s) => s.setActiveWorktree) - const fetchWorktrees = useAppStore((s) => s.fetchWorktrees) - - useEffect(() => { - fetchWorktrees() - }, [fetchWorktrees]) - - return ( -
-
Worktrees
-
    - {worktrees.map((wt) => ( -
  • setActiveWorktree(wt.path)} - > - - {wt.isBare ? '(bare)' : branchDisplayName(wt.branch)} - - {pathBasename(wt.path)} -
  • - ))} -
-
- ) -} +export { default } from './sidebar/index' diff --git a/src/renderer/src/components/TabBar.tsx b/src/renderer/src/components/TabBar.tsx new file mode 100644 index 000000000..48d054d16 --- /dev/null +++ b/src/renderer/src/components/TabBar.tsx @@ -0,0 +1,144 @@ +import { useCallback, useMemo } from 'react' +import { + DndContext, + closestCenter, + PointerSensor, + useSensor, + useSensors, + type DragEndEvent +} from '@dnd-kit/core' +import { + SortableContext, + useSortable, + horizontalListSortingStrategy, + arrayMove +} from '@dnd-kit/sortable' +import { CSS } from '@dnd-kit/utilities' +import { X, Plus } from 'lucide-react' +import type { TerminalTab } from '../../../shared/types' + +interface SortableTabProps { + tab: TerminalTab + isActive: boolean + onActivate: (tabId: string) => void + onClose: (tabId: string) => void +} + +function SortableTab({ tab, isActive, onActivate, onClose }: SortableTabProps): React.JSX.Element { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ + id: tab.id + }) + + const style = { + transform: CSS.Transform.toString(transform), + transition, + zIndex: isDragging ? 10 : undefined, + opacity: isDragging ? 0.8 : 1 + } + + return ( +
{ + // Allow dnd-kit to handle drag, but also activate tab + onActivate(tab.id) + // Forward to dnd-kit listeners + listeners?.onPointerDown?.(e) + }} + > + {tab.title} + +
+ ) +} + +interface TabBarProps { + tabs: TerminalTab[] + activeTabId: string | null + worktreeId: string + onActivate: (tabId: string) => void + onClose: (tabId: string) => void + onReorder: (worktreeId: string, tabIds: string[]) => void + onNewTab: () => void +} + +export default function TabBar({ + tabs, + activeTabId, + worktreeId, + onActivate, + onClose, + onReorder, + onNewTab +}: TabBarProps): React.JSX.Element { + const sensors = useSensors( + useSensor(PointerSensor, { + activationConstraint: { distance: 5 } + }) + ) + + const tabIds = useMemo(() => tabs.map((t) => t.id), [tabs]) + + const handleDragEnd = useCallback( + (event: DragEndEvent) => { + const { active, over } = event + if (!over || active.id === over.id) return + + const oldIndex = tabIds.indexOf(active.id as string) + const newIndex = tabIds.indexOf(over.id as string) + if (oldIndex === -1 || newIndex === -1) return + + const newOrder = arrayMove(tabIds, oldIndex, newIndex) + onReorder(worktreeId, newOrder) + }, + [tabIds, worktreeId, onReorder] + ) + + return ( +
+ + +
+ {tabs.map((tab) => ( + + ))} +
+
+
+ +
+ ) +} diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index a5a63fc7a..09d399507 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -1,374 +1,163 @@ -import { useEffect, useRef } from 'react' -import { Restty, getBuiltinTheme } from 'restty' +import { useEffect, useCallback, useRef } from 'react' import { useAppStore } from '../store' - -type PtyTransport = { - connect: (options: { - url: string - cols?: number - rows?: number - callbacks: { - onConnect?: () => void - onDisconnect?: () => void - onData?: (data: string) => void - onStatus?: (shell: string) => void - onError?: (message: string, errors?: string[]) => void - onExit?: (code: number) => void - } - }) => void | Promise - disconnect: () => void - sendInput: (data: string) => boolean - resize: ( - cols: number, - rows: number, - meta?: { widthPx?: number; heightPx?: number; cellW?: number; cellH?: number } - ) => boolean - isConnected: () => boolean - destroy?: () => void | Promise -} - -// OSC 0/1/2 title regex: \x1b]N;title(\x07|\x1b\\) -// Handles both BEL and ST terminators, and partial sequences across chunks -const OSC_TITLE_RE = /\x1b\]([012]);([^\x07\x1b]*?)(?:\x07|\x1b\\)/g - -function extractLastOscTitle(data: string): string | null { - let last: string | null = null - let m: RegExpExecArray | null - OSC_TITLE_RE.lastIndex = 0 - while ((m = OSC_TITLE_RE.exec(data)) !== null) { - last = m[2] - } - return last -} - -function createIpcPtyTransport( - cwd?: string, - onPtyExit?: () => void, - onTitleChange?: (title: string) => void -): PtyTransport { - let connected = false - let ptyId: string | null = null - let storedCallbacks: { - onConnect?: () => void - onDisconnect?: () => void - onData?: (data: string) => void - onStatus?: (shell: string) => void - onError?: (message: string, errors?: string[]) => void - onExit?: (code: number) => void - } = {} - let unsubData: (() => void) | null = null - let unsubExit: (() => void) | null = null - - return { - async connect(options) { - storedCallbacks = options.callbacks - - try { - const result = await window.api.pty.spawn({ - cols: options.cols ?? 80, - rows: options.rows ?? 24, - cwd - }) - ptyId = result.id - connected = true - - unsubData = window.api.pty.onData((payload) => { - if (payload.id === ptyId) { - storedCallbacks.onData?.(payload.data) - if (onTitleChange) { - const title = extractLastOscTitle(payload.data) - if (title !== null) onTitleChange(title) - } - } - }) - - unsubExit = window.api.pty.onExit((payload) => { - if (payload.id === ptyId) { - connected = false - storedCallbacks.onExit?.(payload.code) - storedCallbacks.onDisconnect?.() - onPtyExit?.() - } - }) - - storedCallbacks.onConnect?.() - storedCallbacks.onStatus?.('shell') - } catch (err) { - const msg = err instanceof Error ? err.message : String(err) - storedCallbacks.onError?.(msg) - } - }, - - disconnect() { - if (ptyId) { - window.api.pty.kill(ptyId) - connected = false - ptyId = null - unsubData?.() - unsubExit?.() - unsubData = null - unsubExit = null - storedCallbacks.onDisconnect?.() - } - }, - - sendInput(data: string): boolean { - if (!connected || !ptyId) return false - window.api.pty.write(ptyId, data) - return true - }, - - resize(cols: number, rows: number): boolean { - if (!connected || !ptyId) return false - window.api.pty.resize(ptyId, cols, rows) - return true - }, - - isConnected() { - return connected - }, - - destroy() { - this.disconnect() - } - } -} +import TabBar from './TabBar' +import TerminalPane from './TerminalPane' export default function Terminal(): React.JSX.Element { - const containerRef = useRef(null) - const resttyRef = useRef(null) - const activeWorktree = useAppStore((s) => s.activeWorktree) + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId)! + const worktreesByRepo = useAppStore((s) => s.worktreesByRepo) + const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) + const activeTabId = useAppStore((s) => s.activeTabId) + const createTab = useAppStore((s) => s.createTab) + const closeTab = useAppStore((s) => s.closeTab) + const setActiveTab = useAppStore((s) => s.setActiveTab) + const reorderTabs = useAppStore((s) => s.reorderTabs) + const setActiveWorktree = useAppStore((s) => s.setActiveWorktree) + const tabs = tabsByWorktree[activeWorktreeId] ?? [] + const prevTabCountRef = useRef(tabs.length) + const tabBarRef = useRef(null) + + // Find the active worktree to get its path + const activeWorktree = activeWorktreeId + ? Object.values(worktreesByRepo) + .flat() + .find((w) => w.id === activeWorktreeId) + : null + + const cwd = activeWorktree?.path + + // Auto-create first tab when worktree activates useEffect(() => { - const container = containerRef.current - if (!container) return - - const cwd = activeWorktree ?? undefined - - // Map pane id -> its associated pty transport exit handler - const paneCloseQueue: number[] = [] - let closeTimer: ReturnType | null = null - - function scheduleClose(paneId: number): void { - paneCloseQueue.push(paneId) - if (closeTimer) return - // Batch close on next tick to avoid issues during restty callbacks - closeTimer = setTimeout(() => { - closeTimer = null - const restty = resttyRef.current - if (!restty) return - while (paneCloseQueue.length > 0) { - const id = paneCloseQueue.shift()! - const panes = restty.getPanes() - if (panes.length <= 1) { - // Last pane — go to landing - useAppStore.getState().setShowTerminal(false) - return - } - restty.closePane(id) - } - }, 0) + if (activeWorktreeId && tabs.length === 0) { + createTab(activeWorktreeId) } + }, [activeWorktreeId, tabs.length, createTab]) - // Track per-pane titles - const paneTitles = new Map() - let currentActivePaneId: number | null = null - - function syncTitleToStore(): void { - if (currentActivePaneId !== null) { - const title = paneTitles.get(currentActivePaneId) ?? '' - useAppStore.getState().setTerminalTitle(title) - } else { - useAppStore.getState().setTerminalTitle('') - } + // Ensure activeTabId is valid + useEffect(() => { + if (tabs.length > 0 && (!activeTabId || !tabs.find((t) => t.id === activeTabId))) { + setActiveTab(tabs[0].id) } + }, [tabs, activeTabId, setActiveTab]) - const restty = new Restty({ - root: container, - createInitialPane: false, - autoInit: false, - shortcuts: { enabled: true }, - appOptions: ({ id }) => { - const onPtyExit = (): void => { - scheduleClose(id) - } - const onTitleChange = (title: string): void => { - paneTitles.set(id, title) - if (id === currentActivePaneId) { - useAppStore.getState().setTerminalTitle(title) - } - } - return { - renderer: 'webgpu', - fontSize: 14, - fontSizeMode: 'em', - alphaBlending: 'native', - ptyTransport: createIpcPtyTransport(cwd, onPtyExit, onTitleChange) as never, - fontSources: [ - { - type: 'local' as const, - label: 'SF Mono', - matchers: ['sf mono', 'sfmono-regular'], - required: true - }, - { - type: 'local' as const, - label: 'Menlo', - matchers: ['menlo', 'menlo regular'] - } - ] - } - }, - onPaneCreated: async (pane) => { - await pane.app.init() - const theme = getBuiltinTheme('Aizen Dark') - if (theme) pane.app.applyTheme(theme, 'Aizen Dark') - pane.app.updateSize(true) - pane.app.connectPty('') - pane.canvas.focus({ preventScroll: true }) - }, - onPaneClosed: (pane) => { - paneTitles.delete(pane.id) - }, - onActivePaneChange: (pane) => { - currentActivePaneId = pane?.id ?? null - syncTitleToStore() - } - }) + // Animate tab bar height with grid transition + useEffect(() => { + const el = tabBarRef.current + if (!el) return - restty.createInitialPane({ focus: true }) - resttyRef.current = restty - - // --- Pane zoom state --- - let zoomedPaneId: number | null = null - const savedStyles: { el: HTMLElement; prop: string; prev: string }[] = [] - - function saveAndSet(el: HTMLElement, prop: string, value: string): void { - savedStyles.push({ - el, - prop, - prev: (el.style as unknown as Record)[prop] ?? '' - }) - ;(el.style as unknown as Record)[prop] = value + const showBar = tabs.length >= 2 + if (showBar) { + el.style.gridTemplateRows = '1fr' + } else { + el.style.gridTemplateRows = '0fr' } + prevTabCountRef.current = tabs.length + }, [tabs.length]) - function unzoom(): void { - if (zoomedPaneId === null) return - for (const entry of savedStyles) { - ;(entry.el.style as unknown as Record)[entry.prop] = entry.prev - } - savedStyles.length = 0 - zoomedPaneId = null - requestAnimationFrame(() => { - for (const p of restty.getPanes()) { - p.app.updateSize(true) - } - }) - } + const handleNewTab = useCallback(() => { + createTab(activeWorktreeId) + }, [activeWorktreeId, createTab]) - function togglePaneZoom(): void { - const panes = restty.getPanes() - - if (zoomedPaneId !== null) { - unzoom() + const handleCloseTab = useCallback( + (tabId: string) => { + const currentTabs = useAppStore.getState().tabsByWorktree[activeWorktreeId] ?? [] + if (currentTabs.length <= 1) { + // Last tab - deactivate worktree + closeTab(tabId) + setActiveWorktree(null) return } - if (panes.length <= 1) return - - const active = restty.getActivePane() ?? panes[0] - if (!active) return - - let current: HTMLElement = active.container - saveAndSet(current, 'flex', '1 1 100%') - - while (current.parentElement) { - const parent = current.parentElement - for (const sibling of Array.from(parent.children) as HTMLElement[]) { - if (sibling === current) continue - saveAndSet(sibling, 'display', 'none') - } - if (parent === container) break - saveAndSet(parent, 'flex', '1 1 100%') - current = parent + // If closing the active tab, switch to a neighbor + if (tabId === useAppStore.getState().activeTabId) { + const idx = currentTabs.findIndex((t) => t.id === tabId) + const nextTab = currentTabs[idx + 1] ?? currentTabs[idx - 1] + if (nextTab) setActiveTab(nextTab.id) } + closeTab(tabId) + }, + [activeWorktreeId, closeTab, setActiveTab, setActiveWorktree] + ) - zoomedPaneId = active.id - requestAnimationFrame(() => { - active.app.updateSize(true) - }) - } - - function closeActivePane(): void { - const panes = restty.getPanes() - const active = restty.getActivePane() ?? panes[0] - if (!active) return - - // If zoomed and closing the zoomed pane, unzoom first - if (zoomedPaneId === active.id) { - unzoom() - } - - if (panes.length <= 1) { - // Last pane — disconnect PTY and go to landing - active.app.disconnectPty() - useAppStore.getState().setShowTerminal(false) - return - } - // Disconnect PTY then close the pane - active.app.disconnectPty() - restty.closePane(active.id) - } + const handlePtyExit = useCallback( + (tabId: string) => { + handleCloseTab(tabId) + }, + [handleCloseTab] + ) + // Keyboard shortcuts + useEffect(() => { const onKeyDown = (e: KeyboardEvent): void => { - // Cmd+K: clear screen - if (e.metaKey && e.key === 'k' && !e.shiftKey && !e.repeat) { + // Cmd+T - new tab + if (e.metaKey && e.key === 't' && !e.shiftKey && !e.repeat) { e.preventDefault() - const pane = restty.getActivePane() ?? restty.getPanes()[0] - if (pane) { - pane.app.clearScreen() - } + handleNewTab() return } - // Cmd+W: close active pane (not the window) + // Cmd+W - close active tab if (e.metaKey && e.key === 'w' && !e.shiftKey && !e.repeat) { e.preventDefault() - closeActivePane() - return - } - - // Cmd+] / Cmd+[: cycle through panes - if (e.metaKey && !e.shiftKey && (e.key === ']' || e.key === '[') && !e.repeat) { - const panes = restty.getPanes() - if (panes.length > 1) { - e.preventDefault() - const active = restty.getActivePane() - const idx = active ? panes.findIndex((p) => p.id === active.id) : -1 - const dir = e.key === ']' ? 1 : -1 - const next = panes[(idx + dir + panes.length) % panes.length] - if (next) { - next.canvas.focus({ preventScroll: true }) - } + const currentActiveTabId = useAppStore.getState().activeTabId + if (currentActiveTabId) { + handleCloseTab(currentActiveTabId) } return } - // Cmd+Shift+Enter: toggle pane zoom - if (e.metaKey && e.shiftKey && e.key === 'Enter' && !e.repeat) { - e.preventDefault() - togglePaneZoom() + // Cmd+Shift+] and Cmd+Shift+[ - switch tabs + if (e.metaKey && e.shiftKey && (e.key === ']' || e.key === '[') && !e.repeat) { + const currentTabs = useAppStore.getState().tabsByWorktree[activeWorktreeId] ?? [] + if (currentTabs.length > 1) { + e.preventDefault() + const currentId = useAppStore.getState().activeTabId + const idx = currentTabs.findIndex((t) => t.id === currentId) + const dir = e.key === ']' ? 1 : -1 + const next = currentTabs[(idx + dir + currentTabs.length) % currentTabs.length] + if (next) setActiveTab(next.id) + } + return } } window.addEventListener('keydown', onKeyDown, { capture: true }) + return () => window.removeEventListener('keydown', onKeyDown, { capture: true }) + }, [activeWorktreeId, handleNewTab, handleCloseTab, setActiveTab]) - return () => { - window.removeEventListener('keydown', onKeyDown, { capture: true }) - if (closeTimer) clearTimeout(closeTimer) - restty.destroy() - resttyRef.current = null - } - }, [activeWorktree]) + return ( +
+ {/* Animated tab bar container using CSS grid for smooth height animation */} +
= 2 ? '1fr' : '0fr' }} + > +
+ +
+
- return
+ {/* Terminal panes container */} +
+ {tabs.map((tab) => ( + handlePtyExit(tab.id)} + /> + ))} +
+
+ ) } diff --git a/src/renderer/src/components/TerminalPane.tsx b/src/renderer/src/components/TerminalPane.tsx new file mode 100644 index 000000000..2f358a16b --- /dev/null +++ b/src/renderer/src/components/TerminalPane.tsx @@ -0,0 +1,260 @@ +import { useEffect, useRef } from 'react' +import { Restty, getBuiltinTheme } from 'restty' +import { useAppStore } from '../store' + +type PtyTransport = { + connect: (options: { + url: string + cols?: number + rows?: number + callbacks: { + onConnect?: () => void + onDisconnect?: () => void + onData?: (data: string) => void + onStatus?: (shell: string) => void + onError?: (message: string, errors?: string[]) => void + onExit?: (code: number) => void + } + }) => void | Promise + disconnect: () => void + sendInput: (data: string) => boolean + resize: ( + cols: number, + rows: number, + meta?: { widthPx?: number; heightPx?: number; cellW?: number; cellH?: number } + ) => boolean + isConnected: () => boolean + destroy?: () => void | Promise +} + +const OSC_TITLE_RE = /\x1b\]([012]);([^\x07\x1b]*?)(?:\x07|\x1b\\)/g + +function extractLastOscTitle(data: string): string | null { + let last: string | null = null + let m: RegExpExecArray | null + OSC_TITLE_RE.lastIndex = 0 + while ((m = OSC_TITLE_RE.exec(data)) !== null) { + last = m[2] + } + return last +} + +function createIpcPtyTransport( + cwd?: string, + onPtyExit?: () => void, + onTitleChange?: (title: string) => void, + onPtySpawn?: (ptyId: string) => void +): PtyTransport { + let connected = false + let ptyId: string | null = null + let storedCallbacks: { + onConnect?: () => void + onDisconnect?: () => void + onData?: (data: string) => void + onStatus?: (shell: string) => void + onError?: (message: string, errors?: string[]) => void + onExit?: (code: number) => void + } = {} + let unsubData: (() => void) | null = null + let unsubExit: (() => void) | null = null + + return { + async connect(options) { + storedCallbacks = options.callbacks + + try { + const result = await window.api.pty.spawn({ + cols: options.cols ?? 80, + rows: options.rows ?? 24, + cwd + }) + ptyId = result.id + connected = true + onPtySpawn?.(result.id) + + unsubData = window.api.pty.onData((payload) => { + if (payload.id === ptyId) { + storedCallbacks.onData?.(payload.data) + if (onTitleChange) { + const title = extractLastOscTitle(payload.data) + if (title !== null) onTitleChange(title) + } + } + }) + + unsubExit = window.api.pty.onExit((payload) => { + if (payload.id === ptyId) { + connected = false + storedCallbacks.onExit?.(payload.code) + storedCallbacks.onDisconnect?.() + onPtyExit?.() + } + }) + + storedCallbacks.onConnect?.() + storedCallbacks.onStatus?.('shell') + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + storedCallbacks.onError?.(msg) + } + }, + + disconnect() { + if (ptyId) { + window.api.pty.kill(ptyId) + connected = false + ptyId = null + unsubData?.() + unsubExit?.() + unsubData = null + unsubExit = null + storedCallbacks.onDisconnect?.() + } + }, + + sendInput(data: string): boolean { + if (!connected || !ptyId) return false + window.api.pty.write(ptyId, data) + return true + }, + + resize(cols: number, rows: number): boolean { + if (!connected || !ptyId) return false + window.api.pty.resize(ptyId, cols, rows) + return true + }, + + isConnected() { + return connected + }, + + destroy() { + this.disconnect() + } + } +} + +interface TerminalPaneProps { + tabId: string + cwd?: string + isActive: boolean + onPtyExit: () => void +} + +export default function TerminalPane({ + tabId, + cwd, + isActive, + onPtyExit +}: TerminalPaneProps): React.JSX.Element { + const containerRef = useRef(null) + const resttyRef = useRef(null) + const wasActiveRef = useRef(isActive) + + const updateTabTitle = useAppStore((s) => s.updateTabTitle) + const updateTabPtyId = useAppStore((s) => s.updateTabPtyId) + + // Use a ref so the Restty closure always calls the latest onPtyExit + const onPtyExitRef = useRef(onPtyExit) + onPtyExitRef.current = onPtyExit + + // Initialize Restty instance once + useEffect(() => { + const container = containerRef.current + if (!container) return + + const onTitleChange = (title: string): void => { + updateTabTitle(tabId, title) + } + + const onPtySpawn = (ptyId: string): void => { + updateTabPtyId(tabId, ptyId) + } + + const restty = new Restty({ + root: container, + createInitialPane: false, + autoInit: false, + shortcuts: { enabled: true }, + appOptions: ({ id }) => { + const onExit = (): void => { + // Schedule close via parent + const panes = restty.getPanes() + if (panes.length <= 1) { + onPtyExitRef.current() + return + } + restty.closePane(id) + } + return { + renderer: 'webgpu', + fontSize: 14, + fontSizeMode: 'em', + alphaBlending: 'native', + ptyTransport: createIpcPtyTransport(cwd, onExit, onTitleChange, onPtySpawn) as never, + fontSources: [ + { + type: 'local' as const, + label: 'SF Mono', + matchers: ['sf mono', 'sfmono-regular'], + required: true + }, + { + type: 'local' as const, + label: 'Menlo', + matchers: ['menlo', 'menlo regular'] + } + ] + } + }, + onPaneCreated: async (pane) => { + await pane.app.init() + const theme = getBuiltinTheme('Aizen Dark') + if (theme) pane.app.applyTheme(theme, 'Aizen Dark') + pane.app.updateSize(true) + pane.app.connectPty('') + pane.canvas.focus({ preventScroll: true }) + }, + onPaneClosed: () => {}, + onActivePaneChange: () => {} + }) + + restty.createInitialPane({ focus: isActive }) + resttyRef.current = restty + + return () => { + restty.destroy() + resttyRef.current = null + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tabId, cwd]) + + // Handle focus and resize when tab becomes active + useEffect(() => { + const restty = resttyRef.current + if (!restty) return + + if (isActive && !wasActiveRef.current) { + // Tab just became active - focus and resize + requestAnimationFrame(() => { + const panes = restty.getPanes() + for (const p of panes) { + p.app.updateSize(true) + } + const active = restty.getActivePane() ?? panes[0] + if (active) { + active.canvas.focus({ preventScroll: true }) + } + }) + } + wasActiveRef.current = isActive + }, [isActive]) + + return ( +
+ ) +} diff --git a/src/renderer/src/components/sidebar/AddWorktreeDialog.tsx b/src/renderer/src/components/sidebar/AddWorktreeDialog.tsx new file mode 100644 index 000000000..fde677909 --- /dev/null +++ b/src/renderer/src/components/sidebar/AddWorktreeDialog.tsx @@ -0,0 +1,171 @@ +import React, { useState, useCallback } from 'react' +import { useAppStore } from '@/store' +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter +} from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { + Select, + SelectTrigger, + SelectValue, + SelectContent, + SelectItem +} from '@/components/ui/select' + +const AddWorktreeDialog = React.memo(function AddWorktreeDialog() { + const activeModal = useAppStore((s) => s.activeModal) + const closeModal = useAppStore((s) => s.closeModal) + const repos = useAppStore((s) => s.repos) + const createWorktree = useAppStore((s) => s.createWorktree) + const updateWorktreeMeta = useAppStore((s) => s.updateWorktreeMeta) + + const [repoId, setRepoId] = useState('') + const [name, setName] = useState('') + const [linkedIssue, setLinkedIssue] = useState('') + const [comment, setComment] = useState('') + const [creating, setCreating] = useState(false) + + const isOpen = activeModal === 'create-worktree' + + const handleOpenChange = useCallback( + (open: boolean) => { + if (!open) { + closeModal() + setRepoId('') + setName('') + setLinkedIssue('') + setComment('') + } + }, + [closeModal] + ) + + const handleCreate = useCallback(async () => { + if (!repoId || !name.trim()) return + setCreating(true) + try { + const wt = await createWorktree(repoId, name.trim()) + if (wt) { + const metaUpdates: Record = {} + if (linkedIssue.trim()) { + const num = parseInt(linkedIssue.trim(), 10) + if (!isNaN(num)) (metaUpdates as { linkedIssue: number }).linkedIssue = num + } + if (comment.trim()) { + ;(metaUpdates as { comment: string }).comment = comment.trim() + } + if (Object.keys(metaUpdates).length > 0) { + await updateWorktreeMeta(wt.id, metaUpdates as { linkedIssue?: number; comment?: string }) + } + } + handleOpenChange(false) + } finally { + setCreating(false) + } + }, [repoId, name, linkedIssue, comment, createWorktree, updateWorktreeMeta, handleOpenChange]) + + // Auto-select first repo when opening + React.useEffect(() => { + if (isOpen && repos.length > 0 && !repoId) { + setRepoId(repos[0].id) + } + }, [isOpen, repos, repoId]) + + return ( + + + + New Worktree + + Create a new git worktree. The branch name will inherit from the name you provide. + + + +
+ {/* Repo selector */} +
+ + +
+ + {/* Name */} +
+ + setName(e.target.value)} + placeholder="feature/my-feature" + className="h-8 text-xs" + autoFocus + /> +
+ + {/* Link GH Issue */} +
+ + setLinkedIssue(e.target.value)} + placeholder="Issue number, e.g. 42" + className="h-8 text-xs" + /> +
+ + {/* Comment */} +
+ +