diff --git a/src/main/git/repo.ts b/src/main/git/repo.ts index 6b76a4537..b520dd9f4 100644 --- a/src/main/git/repo.ts +++ b/src/main/git/repo.ts @@ -1,6 +1,9 @@ -import { execSync } from 'child_process' +import { execFile, execSync } from 'child_process' import { existsSync, statSync } from 'fs' import { join, basename } from 'path' +import { promisify } from 'util' + +const execFileAsync = promisify(execFile) /** * Check if a path is a valid git repository (regular or bare). @@ -119,28 +122,126 @@ export function getGitUsername(path: string): string { ) } -/** - * Detect the default branch (main or master). - */ -export function getDefaultBranch(path: string): string { +function hasGitRef(path: string, ref: string): boolean { try { - // Check if 'main' branch exists - execSync('git rev-parse --verify refs/heads/main', { + execSync(`git rev-parse --verify ${ref}`, { cwd: path, encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] }) - return 'main' + return true } catch { - try { - execSync('git rev-parse --verify refs/heads/master', { - cwd: path, - encoding: 'utf-8', - stdio: ['pipe', 'pipe', 'pipe'] - }) - return 'master' - } catch { - return 'main' - } + return false + } +} + +/** + * Resolve the default base ref for new worktrees. + * Prefer the remote primary branch over a potentially stale local branch. + */ +export function getDefaultBaseRef(path: string): string { + try { + const ref = execSync('git symbolic-ref --quiet refs/remotes/origin/HEAD', { + cwd: path, + encoding: 'utf-8', + stdio: ['pipe', 'pipe', 'pipe'] + }).trim() + + if (ref) { + return ref.replace(/^refs\/remotes\//, '') + } + } catch { + // Fall through to explicit remote branch probes. + } + + if (hasGitRef(path, 'refs/remotes/origin/main')) return 'origin/main' + if (hasGitRef(path, 'refs/remotes/origin/master')) return 'origin/master' + if (hasGitRef(path, 'refs/heads/main')) return 'main' + if (hasGitRef(path, 'refs/heads/master')) return 'master' + + return 'origin/main' +} + +export async function getBaseRefDefault(path: string): Promise { + return getDefaultBaseRefAsync(path) +} + +async function getDefaultBaseRefAsync(path: string): Promise { + try { + const { stdout } = await execFileAsync( + 'git', + ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], + { + cwd: path, + encoding: 'utf-8' + } + ) + const ref = stdout.trim() + if (ref) { + return ref.replace(/^refs\/remotes\//, '') + } + } catch { + // Fall through to explicit remote branch probes. + } + + if (await hasGitRefAsync(path, 'refs/remotes/origin/main')) return 'origin/main' + if (await hasGitRefAsync(path, 'refs/remotes/origin/master')) return 'origin/master' + if (await hasGitRefAsync(path, 'refs/heads/main')) return 'main' + if (await hasGitRefAsync(path, 'refs/heads/master')) return 'master' + + return 'origin/main' +} + +export async function searchBaseRefs(path: string, query: string, limit = 25): Promise { + const normalizedQuery = normalizeRefSearchQuery(query) + if (!normalizedQuery) return [] + + try { + const { stdout } = await execFileAsync( + 'git', + [ + 'for-each-ref', + '--format=%(refname:short)', + '--sort=-committerdate', + `refs/remotes/origin/*${normalizedQuery}*`, + `refs/heads/*${normalizedQuery}*` + ], + { + cwd: path, + encoding: 'utf-8' + } + ) + + const seen = new Set() + const refs = stdout + .split('\n') + .map((line) => line.trim()) + .filter((line) => line && line !== 'origin/HEAD') + .filter((line) => { + if (seen.has(line)) return false + seen.add(line) + return true + }) + .slice(0, Math.max(1, limit)) + + return refs + } catch { + return [] + } +} + +function normalizeRefSearchQuery(query: string): string { + return query.trim().replace(/[\*\?\[\]\\]/g, '') +} + +async function hasGitRefAsync(path: string, ref: string): Promise { + try { + await execFileAsync('git', ['rev-parse', '--verify', ref], { + cwd: path, + encoding: 'utf-8' + }) + return true + } catch { + return false } } diff --git a/src/main/index.ts b/src/main/index.ts index 98a65ebf3..4fd922fcf 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -12,6 +12,7 @@ import { registerGitHubHandlers } from './ipc/github' import { registerSettingsHandlers } from './ipc/settings' import { registerShellHandlers } from './ipc/shell' import { registerSessionHandlers } from './ipc/session' +import { registerUIHandlers } from './ipc/ui' let mainWindow: BrowserWindow | null = null let store: Store | null = null @@ -141,6 +142,7 @@ app.whenReady().then(() => { registerSettingsHandlers(store) registerShellHandlers() registerSessionHandlers(store) + registerUIHandlers(store) // macOS re-activate app.on('activate', function () { diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index fd0a41919..b502d455c 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -3,7 +3,13 @@ import { randomUUID } from 'crypto' import type { Store } from '../persistence' import type { Repo } from '../../shared/types' import { REPO_COLORS } from '../../shared/constants' -import { isGitRepo, getGitUsername, getRepoName } from '../git/repo' +import { + isGitRepo, + getGitUsername, + getRepoName, + getBaseRefDefault, + searchBaseRefs +} from '../git/repo' export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): void { ipcMain.handle('repos:list', () => { @@ -43,7 +49,9 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v _event, args: { repoId: string - updates: Partial> + updates: Partial< + Pick + > } ) => { const updated = store.updateRepo(args.repoId, args.updates) @@ -65,6 +73,21 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v if (!repo) return '' return getGitUsername(repo.path) }) + + ipcMain.handle('repos:getBaseRefDefault', async (_event, args: { repoId: string }) => { + const repo = store.getRepo(args.repoId) + if (!repo) return 'origin/main' + return getBaseRefDefault(repo.path) + }) + + ipcMain.handle( + 'repos:searchBaseRefs', + async (_event, args: { repoId: string; query: string; limit?: number }) => { + const repo = store.getRepo(args.repoId) + if (!repo) return [] + return searchBaseRefs(repo.path, args.query, args.limit ?? 25) + } + ) } function notifyReposChanged(mainWindow: BrowserWindow): void { diff --git a/src/main/ipc/ui.ts b/src/main/ipc/ui.ts new file mode 100644 index 000000000..7e96be6c8 --- /dev/null +++ b/src/main/ipc/ui.ts @@ -0,0 +1,13 @@ +import { ipcMain } from 'electron' +import type { Store } from '../persistence' +import type { PersistedUIState } from '../../shared/types' + +export function registerUIHandlers(store: Store): void { + ipcMain.handle('ui:get', () => { + return store.getUI() + }) + + ipcMain.handle('ui:set', (_event, args: Partial) => { + store.updateUI(args) + }) +} diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 107160119..d78aa2b4b 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -3,7 +3,7 @@ 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 { getGitUsername, getDefaultBaseRef } from '../git/repo' import { getEffectiveHooks, loadHooks, runHook, hasHooksFile } from '../hooks' export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store): void { @@ -64,7 +64,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store } // Determine base branch - const baseBranch = args.baseBranch || getDefaultBranch(repo.path) + const baseBranch = args.baseBranch || repo.worktreeBaseRef || getDefaultBaseRef(repo.path) addWorktree(repo.path, worktreePath, branchName, baseBranch) diff --git a/src/main/persistence.ts b/src/main/persistence.ts index fcb27d83f..2fab62d80 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -6,6 +6,7 @@ import type { PersistedState, Repo, WorktreeMeta, GlobalSettings } from '../shar import { getGitUsername } from './git/repo' import { getDefaultPersistedState, + getDefaultUIState, getDefaultRepoHookSettings, getDefaultWorkspaceSession } from '../shared/constants' @@ -89,7 +90,7 @@ export class Store { updateRepo( id: string, - updates: Partial> + updates: Partial> ): Repo | null { const repo = this.state.repos.find((r) => r.id === id) if (!repo) return null @@ -159,7 +160,7 @@ export class Store { // ── UI State ─────────────────────────────────────────────────────── getUI(): PersistedState['ui'] { - return this.state.ui + return { ...getDefaultUIState(), ...this.state.ui } } updateUI(updates: Partial): void { diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 16bc5aa35..85c965f2c 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -7,6 +7,7 @@ import type { IssueInfo, GlobalSettings, OrcaHooks, + PersistedUIState, WorkspaceSessionState } from '../../shared/types' @@ -16,10 +17,12 @@ interface ReposApi { remove: (args: { repoId: string }) => Promise update: (args: { repoId: string - updates: Partial> + updates: Partial> }) => Promise pickFolder: () => Promise getGitUsername: (args: { repoId: string }) => Promise + getBaseRefDefault: (args: { repoId: string }) => Promise + searchBaseRefs: (args: { repoId: string; query: string; limit?: number }) => Promise onChanged: (callback: () => void) => () => void } @@ -79,6 +82,11 @@ interface SessionApi { set: (args: WorkspaceSessionState) => Promise } +interface UIApi { + get: () => Promise + set: (args: Partial) => Promise +} + interface Api { repos: ReposApi worktrees: WorktreesApi @@ -89,6 +97,7 @@ interface Api { hooks: HooksApi cache: CacheApi session: SessionApi + ui: UIApi } declare global { diff --git a/src/preload/index.ts b/src/preload/index.ts index f64f26f34..25cc6dff3 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -18,6 +18,12 @@ const api = { getGitUsername: (args: { repoId: string }): Promise => ipcRenderer.invoke('repos:getGitUsername', args), + getBaseRefDefault: (args: { repoId: string }): Promise => + ipcRenderer.invoke('repos:getBaseRefDefault', args), + + searchBaseRefs: (args: { repoId: string; query: string; limit?: number }): Promise => + ipcRenderer.invoke('repos:searchBaseRefs', args), + onChanged: (callback: () => void): (() => void) => { const listener = (_event: Electron.IpcRendererEvent) => callback() ipcRenderer.on('repos:changed', listener) @@ -116,6 +122,11 @@ const api = { session: { get: (): Promise => ipcRenderer.invoke('session:get'), set: (args: unknown): Promise => ipcRenderer.invoke('session:set', args) + }, + + ui: { + get: (): Promise => ipcRenderer.invoke('ui:get'), + set: (args: Record): Promise => ipcRenderer.invoke('ui:set', args) } } diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index c4ff30136..03d15636a 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -24,8 +24,13 @@ function App(): React.JSX.Element { const fetchSettings = useAppStore((s) => s.fetchSettings) const initGitHubCache = useAppStore((s) => s.initGitHubCache) const hydrateWorkspaceSession = useAppStore((s) => s.hydrateWorkspaceSession) + const hydratePersistedUI = useAppStore((s) => s.hydratePersistedUI) const openModal = useAppStore((s) => s.openModal) const repos = useAppStore((s) => s.repos) + const sidebarWidth = useAppStore((s) => s.sidebarWidth) + const groupBy = useAppStore((s) => s.groupBy) + const sortBy = useAppStore((s) => s.sortBy) + const persistedUIReady = useAppStore((s) => s.persistedUIReady) // Subscribe to IPC push events useIpcEvents() @@ -40,13 +45,22 @@ function App(): React.JSX.Element { try { await fetchRepos() await fetchAllWorktrees() + const persistedUI = await window.api.ui.get() const session = await window.api.session.get() if (!cancelled) { + hydratePersistedUI(persistedUI) hydrateWorkspaceSession(session) } } catch (error) { console.error('Failed to hydrate workspace session:', error) if (!cancelled) { + hydratePersistedUI({ + lastActiveRepoId: null, + lastActiveWorktreeId: null, + sidebarWidth: 280, + groupBy: 'none', + sortBy: 'name' + }) hydrateWorkspaceSession({ activeRepoId: null, activeWorktreeId: null, @@ -63,7 +77,14 @@ function App(): React.JSX.Element { return () => { cancelled = true } - }, [fetchRepos, fetchAllWorktrees, fetchSettings, initGitHubCache, hydrateWorkspaceSession]) + }, [ + fetchRepos, + fetchAllWorktrees, + fetchSettings, + initGitHubCache, + hydratePersistedUI, + hydrateWorkspaceSession + ]) useEffect(() => { if (!workspaceSessionReady) return @@ -88,6 +109,20 @@ function App(): React.JSX.Element { terminalLayoutsByTabId ]) + useEffect(() => { + if (!persistedUIReady) return + + const timer = window.setTimeout(() => { + void window.api.ui.set({ + sidebarWidth, + groupBy, + sortBy + }) + }, 150) + + return () => window.clearTimeout(timer) + }, [persistedUIReady, sidebarWidth, groupBy, sortBy]) + // Apply theme to document useEffect(() => { if (!settings) return diff --git a/src/renderer/src/components/Settings.tsx b/src/renderer/src/components/Settings.tsx index c5fb0e549..6f3e1b043 100644 --- a/src/renderer/src/components/Settings.tsx +++ b/src/renderer/src/components/Settings.tsx @@ -27,6 +27,10 @@ function Settings(): React.JSX.Element { const [repoHooksMap, setRepoHooksMap] = useState< Record >({}) + const [defaultBaseRef, setDefaultBaseRef] = useState('origin/main') + const [baseRefQuery, setBaseRefQuery] = useState('') + const [baseRefResults, setBaseRefResults] = useState([]) + const [isSearchingBaseRefs, setIsSearchingBaseRefs] = useState(false) useEffect(() => { fetchSettings() @@ -62,6 +66,78 @@ function Settings(): React.JSX.Element { } }, [repos]) + useEffect(() => { + let stale = false + + const loadDefaultBaseRef = async (repoId: string) => { + try { + const result = await window.api.repos.getBaseRefDefault({ repoId }) + if (stale) return + setDefaultBaseRef(result) + } catch { + if (stale) return + setDefaultBaseRef('origin/main') + } + } + + if (!selectedRepoId) { + setDefaultBaseRef('origin/main') + setBaseRefQuery('') + setBaseRefResults([]) + } else { + setBaseRefQuery('') + setBaseRefResults([]) + void loadDefaultBaseRef(selectedRepoId) + } + + return () => { + stale = true + } + }, [selectedRepoId]) + + useEffect(() => { + if (!selectedRepoId) return + + const trimmedQuery = baseRefQuery.trim() + if (trimmedQuery.length < 2) { + setBaseRefResults([]) + setIsSearchingBaseRefs(false) + return + } + + let stale = false + setIsSearchingBaseRefs(true) + + const timer = window.setTimeout(() => { + void window.api.repos + .searchBaseRefs({ + repoId: selectedRepoId, + query: trimmedQuery, + limit: 20 + }) + .then((results) => { + if (!stale) { + setBaseRefResults(results) + } + }) + .catch(() => { + if (!stale) { + setBaseRefResults([]) + } + }) + .finally(() => { + if (!stale) { + setIsSearchingBaseRefs(false) + } + }) + }, 200) + + return () => { + stale = true + window.clearTimeout(timer) + } + }, [selectedRepoId, baseRefQuery]) + useEffect(() => { if (repos.length === 0) { setSelectedRepoId(null) @@ -111,6 +187,7 @@ function Settings(): React.JSX.Element { const selectedYamlHooks = selectedRepo ? (repoHooksMap[selectedRepo.id]?.hooks ?? null) : null const showGeneralPane = selectedPane === 'general' || !selectedRepo const displayedGitUsername = (selectedRepo ?? repos[0])?.gitUsername ?? '' + const effectiveBaseRef = selectedRepo?.worktreeBaseRef ?? defaultBaseRef const updateSelectedRepoHookSettings = ( repo: Repo, @@ -260,7 +337,11 @@ function Settings(): React.JSX.Element { + + +
+ setBaseRefQuery(e.target.value)} + placeholder="Search branches by name..." + className="max-w-md" + /> +

Type at least 2 characters.

+
+ + {isSearchingBaseRefs ? ( +

Searching branches...

+ ) : null} + + {!isSearchingBaseRefs && baseRefQuery.trim().length >= 2 ? ( + baseRefResults.length > 0 ? ( + +
+ {baseRefResults.map((ref) => ( + + ))} +
+
+ ) : ( +

+ No matching branches found. +

+ ) + ) : null} + +

+ New worktrees default to the repo primary branch unless you pin a different base + here. +

+ diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index fa7bef578..ce5998174 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -232,6 +232,7 @@ export default function Terminal(): React.JSX.Element | null { handlePtyExit(tab.id, ptyId)} diff --git a/src/renderer/src/components/TerminalPane.tsx b/src/renderer/src/components/TerminalPane.tsx index fcd13565f..90c350c60 100644 --- a/src/renderer/src/components/TerminalPane.tsx +++ b/src/renderer/src/components/TerminalPane.tsx @@ -74,10 +74,14 @@ function createIpcPtyTransport( cwd?: string, onPtyExit?: (ptyId: string) => void, onTitleChange?: (title: string) => void, - onPtySpawn?: (ptyId: string) => void + onPtySpawn?: (ptyId: string) => void, + onBell?: () => void ): PtyTransport { let connected = false let ptyId: string | null = null + let pendingEscape = false + let inOsc = false + let pendingOscEscape = false let storedCallbacks: { onConnect?: () => void onDisconnect?: () => void @@ -110,6 +114,9 @@ function createIpcPtyTransport( const title = extractLastOscTitle(payload.data) if (title !== null) onTitleChange(title) } + if (onBell && chunkContainsBell(payload.data)) { + onBell() + } } }) @@ -165,6 +172,51 @@ function createIpcPtyTransport( this.disconnect() } } + + function chunkContainsBell(data: string): boolean { + for (let i = 0; i < data.length; i += 1) { + const char = data[i] + + if (inOsc) { + if (pendingOscEscape) { + pendingOscEscape = char === '\x1b' + if (char === '\\') { + inOsc = false + pendingOscEscape = false + } + continue + } + + if (char === '\x07') { + inOsc = false + continue + } + + pendingOscEscape = char === '\x1b' + continue + } + + if (pendingEscape) { + pendingEscape = false + if (char === ']') { + inOsc = true + pendingOscEscape = false + } else if (char === '\x1b') { + pendingEscape = true + } + continue + } + + if (char === '\x1b') { + pendingEscape = true + continue + } + + if (char === '\x07') return true + } + + return false + } } function paneLeafId(paneId: number): string { @@ -265,6 +317,7 @@ function collectLeafIds( interface TerminalPaneProps { tabId: string + worktreeId: string cwd?: string isActive: boolean onPtyExit: (ptyId: string) => void @@ -272,6 +325,7 @@ interface TerminalPaneProps { export default function TerminalPane({ tabId, + worktreeId, cwd, isActive, onPtyExit @@ -430,6 +484,7 @@ export default function TerminalPane({ const updateTabTitle = useAppStore((s) => s.updateTabTitle) const updateTabPtyId = useAppStore((s) => s.updateTabPtyId) const clearTabPtyId = useAppStore((s) => s.clearTabPtyId) + const markWorktreeUnreadFromBell = useAppStore((s) => s.markWorktreeUnreadFromBell) // Use a ref so the Restty closure always calls the latest onPtyExit const onPtyExitRef = useRef(onPtyExit) @@ -463,6 +518,7 @@ export default function TerminalPane({ } const onPtySpawn = (ptyId: string): void => updateTabPtyId(tabId, ptyId) + const onBell = (): void => markWorktreeUnreadFromBell(worktreeId) let shouldPersistLayout = false @@ -488,7 +544,13 @@ export default function TerminalPane({ fontSize: 14, fontSizeMode: 'em', alphaBlending: 'native', - ptyTransport: createIpcPtyTransport(cwd, onExit, onTitleChange, onPtySpawn) as never, + ptyTransport: createIpcPtyTransport( + cwd, + onExit, + onTitleChange, + onPtySpawn, + onBell + ) as never, fontSources: [ { type: 'local' as const, diff --git a/src/renderer/src/components/sidebar/AddWorktreeDialog.tsx b/src/renderer/src/components/sidebar/AddWorktreeDialog.tsx index 8b89d9bd5..8e1a89c73 100644 --- a/src/renderer/src/components/sidebar/AddWorktreeDialog.tsx +++ b/src/renderer/src/components/sidebar/AddWorktreeDialog.tsx @@ -27,6 +27,14 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() { const repos = useAppStore((s) => s.repos) const createWorktree = useAppStore((s) => s.createWorktree) const updateWorktreeMeta = useAppStore((s) => s.updateWorktreeMeta) + const setActiveRepo = useAppStore((s) => s.setActiveRepo) + const setActiveWorktree = useAppStore((s) => s.setActiveWorktree) + const setActiveView = useAppStore((s) => s.setActiveView) + const setSidebarOpen = useAppStore((s) => s.setSidebarOpen) + const setSearchQuery = useAppStore((s) => s.setSearchQuery) + const setShowActiveOnly = useAppStore((s) => s.setShowActiveOnly) + const setFilterRepoId = useAppStore((s) => s.setFilterRepoId) + const revealWorktreeInSidebar = useAppStore((s) => s.revealWorktreeInSidebar) const [repoId, setRepoId] = useState('') const [name, setName] = useState('') @@ -71,12 +79,37 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() { if (Object.keys(metaUpdates).length > 0) { await updateWorktreeMeta(wt.id, metaUpdates as { linkedIssue?: number; comment?: string }) } + + setActiveRepo(repoId) + setActiveView('terminal') + setSidebarOpen(true) + setSearchQuery('') + setShowActiveOnly(false) + setFilterRepoId(repoId) + setActiveWorktree(wt.id) + revealWorktreeInSidebar(wt.id) } handleOpenChange(false) } finally { setCreating(false) } - }, [repoId, name, linkedIssue, comment, createWorktree, updateWorktreeMeta, handleOpenChange]) + }, [ + repoId, + name, + linkedIssue, + comment, + createWorktree, + updateWorktreeMeta, + setActiveRepo, + setActiveView, + setSidebarOpen, + setSearchQuery, + setShowActiveOnly, + setFilterRepoId, + setActiveWorktree, + revealWorktreeInSidebar, + handleOpenChange + ]) // Auto-select first repo when opening React.useEffect(() => { diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index cbfeafa1d..dbfef41b4 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -159,9 +159,7 @@ const WorktreeCard = React.memo(function WorktreeCard({ [worktree.id, worktree.isUnread, updateWorktreeMeta] ) - const unreadTooltip = worktree.isUnread - ? 'Unread - click to mark read' - : 'Read - hover/click to mark unread' + const unreadTooltip = worktree.isUnread ? 'Mark read' : 'Mark unread' return ( diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index 32421a30e..d82477942 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -88,6 +88,17 @@ function getPRGroupKey( return 'in-review' } +function getGroupKeyForWorktree( + groupBy: 'none' | 'repo' | 'pr-status', + worktree: Worktree, + repoMap: Map, + prCache: Record | null +): string | null { + if (groupBy === 'none') return null + if (groupBy === 'repo') return `repo:${worktree.repoId}` + return `pr:${getPRGroupKey(worktree, repoMap, prCache)}` +} + const WorktreeList = React.memo(function WorktreeList() { // ── Granular selectors (each is a primitive or shallow-stable ref) ── const worktreesByRepo = useAppStore((s) => s.worktreesByRepo) @@ -99,6 +110,8 @@ const WorktreeList = React.memo(function WorktreeList() { const showActiveOnly = useAppStore((s) => s.showActiveOnly) const filterRepoId = useAppStore((s) => s.filterRepoId) const openModal = useAppStore((s) => s.openModal) + const pendingRevealWorktreeId = useAppStore((s) => s.pendingRevealWorktreeId) + const clearPendingRevealWorktreeId = useAppStore((s) => s.clearPendingRevealWorktreeId) // Only read tabsByWorktree when showActiveOnly is on (avoid subscription otherwise) const tabsByWorktree = useAppStore((s) => (showActiveOnly ? s.tabsByWorktree : null)) @@ -138,9 +151,9 @@ const WorktreeList = React.memo(function WorktreeList() { } // Filter active only - if (showActiveOnly && tabsByWorktree) { + if (showActiveOnly) { all = all.filter((w) => { - const tabs = tabsByWorktree[w.id] ?? [] + const tabs = tabsByWorktree?.[w.id] ?? [] return tabs.some((t) => t.ptyId) }) } @@ -189,7 +202,6 @@ const WorktreeList = React.memo(function WorktreeList() { return result } - // Group items const grouped = new Map() for (const w of worktrees) { let key: string @@ -255,7 +267,24 @@ const WorktreeList = React.memo(function WorktreeList() { } return result - }, [groupBy, worktrees, repoMap, prCache, collapsedGroups]) + }, [groupBy, worktrees, repoMap, prCache, collapsedGroups, tabsByWorktree]) + + React.useEffect(() => { + if (!pendingRevealWorktreeId || groupBy === 'none') return + + const targetWorktree = worktrees.find((worktree) => worktree.id === pendingRevealWorktreeId) + if (!targetWorktree) return + + const groupKey = getGroupKeyForWorktree(groupBy, targetWorktree, repoMap, prCache) + if (!groupKey) return + + setCollapsedGroups((prev) => { + if (!prev.has(groupKey)) return prev + const next = new Set(prev) + next.delete(groupKey) + return next + }) + }, [pendingRevealWorktreeId, groupBy, worktrees, repoMap, prCache]) // ── TanStack Virtual ────────────────────────────────────────── const virtualizer = useVirtualizer({ @@ -269,6 +298,18 @@ const WorktreeList = React.memo(function WorktreeList() { } }) + React.useEffect(() => { + if (!pendingRevealWorktreeId) return + + const targetIndex = rows.findIndex( + (row) => row.type === 'item' && row.worktree.id === pendingRevealWorktreeId + ) + if (targetIndex === -1) return + + virtualizer.scrollToIndex(targetIndex, { align: 'center' }) + clearPendingRevealWorktreeId() + }, [pendingRevealWorktreeId, rows, virtualizer, clearPendingRevealWorktreeId]) + const handleCreateForRepo = useCallback( (repoId: string) => { openModal('create-worktree', { preselectedRepoId: repoId }) @@ -285,7 +326,7 @@ const WorktreeList = React.memo(function WorktreeList() { } return ( -
+
{virtualizer.getVirtualItems().map((vItem) => { const row = rows[vItem.index] diff --git a/src/renderer/src/store/slices/repos.ts b/src/renderer/src/store/slices/repos.ts index 27a4475af..6b7ffbaa3 100644 --- a/src/renderer/src/store/slices/repos.ts +++ b/src/renderer/src/store/slices/repos.ts @@ -10,7 +10,7 @@ export interface RepoSlice { removeRepo: (repoId: string) => Promise updateRepo: ( repoId: string, - updates: Partial> + updates: Partial> ) => Promise setActiveRepo: (repoId: string | null) => void } diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 2181d4a59..267faa06a 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -1,10 +1,12 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' +import type { PersistedUIState } from '../../../../shared/types' export interface UISlice { sidebarOpen: boolean sidebarWidth: number toggleSidebar: () => void + setSidebarOpen: (open: boolean) => void setSidebarWidth: (width: number) => void activeView: 'terminal' | 'settings' setActiveView: (view: UISlice['activeView']) => void @@ -22,12 +24,18 @@ export interface UISlice { setShowActiveOnly: (v: boolean) => void filterRepoId: string | null setFilterRepoId: (id: string | null) => void + pendingRevealWorktreeId: string | null + revealWorktreeInSidebar: (worktreeId: string) => void + clearPendingRevealWorktreeId: () => void + persistedUIReady: boolean + hydratePersistedUI: (ui: PersistedUIState) => void } export const createUISlice: StateCreator = (set) => ({ sidebarOpen: true, sidebarWidth: 280, toggleSidebar: () => set((s) => ({ sidebarOpen: !s.sidebarOpen })), + setSidebarOpen: (open) => set({ sidebarOpen: open }), setSidebarWidth: (width) => set({ sidebarWidth: width }), activeView: 'terminal', @@ -51,5 +59,18 @@ export const createUISlice: StateCreator = (set) => ( setShowActiveOnly: (v) => set({ showActiveOnly: v }), filterRepoId: null, - setFilterRepoId: (id) => set({ filterRepoId: id }) + setFilterRepoId: (id) => set({ filterRepoId: id }), + + pendingRevealWorktreeId: null, + revealWorktreeInSidebar: (worktreeId) => set({ pendingRevealWorktreeId: worktreeId }), + clearPendingRevealWorktreeId: () => set({ pendingRevealWorktreeId: null }), + persistedUIReady: false, + + hydratePersistedUI: (ui) => + set({ + sidebarWidth: ui.sidebarWidth, + groupBy: ui.groupBy, + sortBy: ui.sortBy, + persistedUIReady: true + }) }) diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 2945edf10..ff34a04a0 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -21,6 +21,7 @@ export interface WorktreeSlice { ) => Promise<{ ok: true } | { ok: false; error: string }> clearWorktreeDeleteState: (worktreeId: string) => void updateWorktreeMeta: (worktreeId: string, updates: Partial) => Promise + markWorktreeUnreadFromBell: (worktreeId: string) => void setActiveWorktree: (worktreeId: string | null) => void allWorktrees: () => Worktree[] } @@ -133,21 +134,109 @@ export const createWorktreeSlice: StateCreator }, updateWorktreeMeta: async (worktreeId, updates) => { + set((s) => { + const nextWorktrees = applyWorktreeUpdates(s.worktreesByRepo, worktreeId, updates) + return nextWorktrees === s.worktreesByRepo ? {} : { worktreesByRepo: nextWorktrees } + }) + try { await window.api.worktrees.updateMeta({ worktreeId, updates }) - set((s) => { - const next = { ...s.worktreesByRepo } - for (const repoId of Object.keys(next)) { - next[repoId] = next[repoId].map((w) => (w.id === worktreeId ? { ...w, ...updates } : w)) - } - return { worktreesByRepo: next } - }) } catch (err) { console.error('Failed to update worktree meta:', err) + void get().fetchWorktrees(getRepoIdFromWorktreeId(worktreeId)) } }, - setActiveWorktree: (worktreeId) => set({ activeWorktreeId: worktreeId }), + markWorktreeUnreadFromBell: (worktreeId) => { + const activeWorktreeId = get().activeWorktreeId + if (activeWorktreeId === worktreeId) return + + let shouldPersist = false + set((s) => { + const worktree = findWorktreeById(s.worktreesByRepo, worktreeId) + if (!worktree || worktree.isUnread) return {} + shouldPersist = true + return { + worktreesByRepo: applyWorktreeUpdates(s.worktreesByRepo, worktreeId, { isUnread: true }) + } + }) + + if (!shouldPersist) return + + void window.api.worktrees + .updateMeta({ worktreeId, updates: { isUnread: true } }) + .catch((err) => { + console.error('Failed to persist unread worktree bell state:', err) + void get().fetchWorktrees(getRepoIdFromWorktreeId(worktreeId)) + }) + }, + + setActiveWorktree: (worktreeId) => { + let shouldClearUnread = false + set((s) => { + if (!worktreeId) return { activeWorktreeId: null } + + const worktree = findWorktreeById(s.worktreesByRepo, worktreeId) + shouldClearUnread = Boolean(worktree?.isUnread) + return { + activeWorktreeId: worktreeId, + worktreesByRepo: shouldClearUnread + ? applyWorktreeUpdates(s.worktreesByRepo, worktreeId, { isUnread: false }) + : s.worktreesByRepo + } + }) + + if (!worktreeId || !shouldClearUnread) return + + void window.api.worktrees + .updateMeta({ worktreeId, updates: { isUnread: false } }) + .catch((err) => { + console.error('Failed to clear unread state for active worktree:', err) + void get().fetchWorktrees(getRepoIdFromWorktreeId(worktreeId)) + }) + }, allWorktrees: () => Object.values(get().worktreesByRepo).flat() }) + +function findWorktreeById( + worktreesByRepo: Record, + worktreeId: string +): Worktree | undefined { + for (const worktrees of Object.values(worktreesByRepo)) { + const match = worktrees.find((worktree) => worktree.id === worktreeId) + if (match) return match + } + + return undefined +} + +function applyWorktreeUpdates( + worktreesByRepo: Record, + worktreeId: string, + updates: Partial +): Record { + let changed = false + const next: Record = {} + + for (const [repoId, worktrees] of Object.entries(worktreesByRepo)) { + let repoChanged = false + const nextWorktrees = worktrees.map((worktree) => { + if (worktree.id !== worktreeId) return worktree + + const updatedWorktree = { ...worktree, ...updates } + repoChanged = true + changed = true + return updatedWorktree + }) + + next[repoId] = repoChanged ? nextWorktrees : worktrees + } + + return changed ? next : worktreesByRepo +} + +function getRepoIdFromWorktreeId(worktreeId: string): string { + const sepIdx = worktreeId.indexOf('::') + return sepIdx === -1 ? worktreeId : worktreeId.slice(0, sepIdx) +} diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 224b52e7f..5c617bf66 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -1,6 +1,7 @@ import type { GlobalSettings, PersistedState, + PersistedUIState, RepoHookSettings, WorkspaceSessionState } from './types' @@ -46,16 +47,22 @@ export function getDefaultPersistedState(homedir: string): PersistedState { repos: [], worktreeMeta: {}, settings: getDefaultSettings(homedir), - ui: { - lastActiveRepoId: null, - lastActiveWorktreeId: null, - sidebarWidth: 280 - }, + ui: getDefaultUIState(), githubCache: { pr: {}, issue: {} }, workspaceSession: getDefaultWorkspaceSession() } } +export function getDefaultUIState(): PersistedUIState { + return { + lastActiveRepoId: null, + lastActiveWorktreeId: null, + sidebarWidth: 280, + groupBy: 'none', + sortBy: 'name' + } +} + export function getDefaultWorkspaceSession(): WorkspaceSessionState { return { activeRepoId: null, diff --git a/src/shared/types.ts b/src/shared/types.ts index 8bc3eba1c..50c7f966f 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -6,6 +6,7 @@ export interface Repo { badgeColor: string addedAt: number gitUsername?: string + worktreeBaseRef?: string hookSettings?: RepoHookSettings } @@ -130,17 +131,21 @@ export interface GlobalSettings { terminalFontFamily: string } +export interface PersistedUIState { + lastActiveRepoId: string | null + lastActiveWorktreeId: string | null + sidebarWidth: number + groupBy: 'none' | 'repo' | 'pr-status' + sortBy: 'name' | 'recent' | 'repo' +} + // ─── Persistence shape ────────────────────────────────────────────── export interface PersistedState { schemaVersion: number repos: Repo[] worktreeMeta: Record settings: GlobalSettings - ui: { - lastActiveRepoId: string | null - lastActiveWorktreeId: string | null - sidebarWidth: number - } + ui: PersistedUIState githubCache: { pr: Record issue: Record