Branch setting, focus new WT

This commit is contained in:
Neil
2026-03-18 20:57:52 -07:00
parent 5a08289df5
commit ce3c3ad6a5
20 changed files with 683 additions and 59 deletions
+119 -18
View File
@@ -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<string> {
return getDefaultBaseRefAsync(path)
}
async function getDefaultBaseRefAsync(path: string): Promise<string> {
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<string[]> {
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<string>()
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<boolean> {
try {
await execFileAsync('git', ['rev-parse', '--verify', ref], {
cwd: path,
encoding: 'utf-8'
})
return true
} catch {
return false
}
}
+2
View File
@@ -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 () {
+25 -2
View File
@@ -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<Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings'>>
updates: Partial<
Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings' | 'worktreeBaseRef'>
>
}
) => {
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 {
+13
View File
@@ -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<PersistedUIState>) => {
store.updateUI(args)
})
}
+2 -2
View File
@@ -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)
+3 -2
View File
@@ -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<Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings'>>
updates: Partial<Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings' | 'worktreeBaseRef'>>
): 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<PersistedState['ui']>): void {
+10 -1
View File
@@ -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<void>
update: (args: {
repoId: string
updates: Partial<Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings'>>
updates: Partial<Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings' | 'worktreeBaseRef'>>
}) => Promise<Repo>
pickFolder: () => Promise<string | null>
getGitUsername: (args: { repoId: string }) => Promise<string>
getBaseRefDefault: (args: { repoId: string }) => Promise<string>
searchBaseRefs: (args: { repoId: string; query: string; limit?: number }) => Promise<string[]>
onChanged: (callback: () => void) => () => void
}
@@ -79,6 +82,11 @@ interface SessionApi {
set: (args: WorkspaceSessionState) => Promise<void>
}
interface UIApi {
get: () => Promise<PersistedUIState>
set: (args: Partial<PersistedUIState>) => Promise<void>
}
interface Api {
repos: ReposApi
worktrees: WorktreesApi
@@ -89,6 +97,7 @@ interface Api {
hooks: HooksApi
cache: CacheApi
session: SessionApi
ui: UIApi
}
declare global {
+11
View File
@@ -18,6 +18,12 @@ const api = {
getGitUsername: (args: { repoId: string }): Promise<string> =>
ipcRenderer.invoke('repos:getGitUsername', args),
getBaseRefDefault: (args: { repoId: string }): Promise<string> =>
ipcRenderer.invoke('repos:getBaseRefDefault', args),
searchBaseRefs: (args: { repoId: string; query: string; limit?: number }): Promise<string[]> =>
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<unknown> => ipcRenderer.invoke('session:get'),
set: (args: unknown): Promise<void> => ipcRenderer.invoke('session:set', args)
},
ui: {
get: (): Promise<unknown> => ipcRenderer.invoke('ui:get'),
set: (args: Record<string, unknown>): Promise<void> => ipcRenderer.invoke('ui:set', args)
}
}
+36 -1
View File
@@ -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
+174 -2
View File
@@ -27,6 +27,10 @@ function Settings(): React.JSX.Element {
const [repoHooksMap, setRepoHooksMap] = useState<
Record<string, { hasHooks: boolean; hooks: OrcaHooks | null }>
>({})
const [defaultBaseRef, setDefaultBaseRef] = useState('origin/main')
const [baseRefQuery, setBaseRefQuery] = useState('')
const [baseRefResults, setBaseRefResults] = useState<string[]>([])
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 {
<button
role="switch"
aria-checked={settings.nestWorkspaces}
onClick={() => updateSettings({ nestWorkspaces: !settings.nestWorkspaces })}
onClick={() =>
updateSettings({
nestWorkspaces: !settings.nestWorkspaces
})
}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors ${
settings.nestWorkspaces ? 'bg-foreground' : 'bg-muted-foreground/30'
}`}
@@ -454,7 +535,11 @@ function Settings(): React.JSX.Element {
<Label className="text-sm">Display Name</Label>
<Input
value={selectedRepo.displayName}
onChange={(e) => updateRepo(selectedRepo.id, { displayName: e.target.value })}
onChange={(e) =>
updateRepo(selectedRepo.id, {
displayName: e.target.value
})
}
className="h-9 text-sm"
/>
</div>
@@ -477,6 +562,93 @@ function Settings(): React.JSX.Element {
))}
</div>
</div>
<div className="space-y-2">
<Label className="text-sm">Default Worktree Base</Label>
<div className="rounded-xl border bg-background/80 p-4 shadow-sm">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<div className="text-sm font-medium text-foreground">
{effectiveBaseRef}
</div>
<p className="text-xs text-muted-foreground">
{selectedRepo.worktreeBaseRef
? 'Pinned for this repo'
: `Following primary branch (${defaultBaseRef})`}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => {
setBaseRefQuery('')
setBaseRefResults([])
updateRepo(selectedRepo.id, {
worktreeBaseRef: undefined
})
}}
disabled={!selectedRepo.worktreeBaseRef}
>
Use Primary
</Button>
</div>
<div className="mt-4 space-y-2">
<Input
value={baseRefQuery}
onChange={(e) => setBaseRefQuery(e.target.value)}
placeholder="Search branches by name..."
className="max-w-md"
/>
<p className="text-xs text-muted-foreground">Type at least 2 characters.</p>
</div>
{isSearchingBaseRefs ? (
<p className="mt-3 text-xs text-muted-foreground">Searching branches...</p>
) : null}
{!isSearchingBaseRefs && baseRefQuery.trim().length >= 2 ? (
baseRefResults.length > 0 ? (
<ScrollArea className="mt-3 h-48 rounded-md border">
<div className="p-1">
{baseRefResults.map((ref) => (
<button
key={ref}
onClick={() => {
setBaseRefQuery(ref)
setBaseRefResults([])
updateRepo(selectedRepo.id, {
worktreeBaseRef: ref
})
}}
className={`flex w-full items-center justify-between rounded-sm px-3 py-2 text-left text-sm transition-colors hover:bg-muted/60 ${
selectedRepo.worktreeBaseRef === ref
? 'bg-accent text-accent-foreground'
: 'text-foreground'
}`}
>
<span className="truncate">{ref}</span>
{selectedRepo.worktreeBaseRef === ref ? (
<span className="text-[10px] uppercase tracking-[0.18em]">
Current
</span>
) : null}
</button>
))}
</div>
</ScrollArea>
) : (
<p className="mt-3 text-xs text-muted-foreground">
No matching branches found.
</p>
)
) : null}
</div>
<p className="text-xs text-muted-foreground">
New worktrees default to the repo primary branch unless you pin a different base
here.
</p>
</div>
</section>
<Separator />
+1
View File
@@ -232,6 +232,7 @@ export default function Terminal(): React.JSX.Element | null {
<TerminalPane
key={tab.id}
tabId={tab.id}
worktreeId={worktree.id}
cwd={worktree.path}
isActive={isVisible && tab.id === activeTabId}
onPtyExit={(ptyId) => handlePtyExit(tab.id, ptyId)}
+64 -2
View File
@@ -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,
@@ -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<string>('')
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(() => {
@@ -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 (
<WorktreeContextMenu worktree={worktree}>
@@ -88,6 +88,17 @@ function getPRGroupKey(
return 'in-review'
}
function getGroupKeyForWorktree(
groupBy: 'none' | 'repo' | 'pr-status',
worktree: Worktree,
repoMap: Map<string, Repo>,
prCache: Record<string, unknown> | 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<string, { label: string; items: Worktree[]; repo?: Repo }>()
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 (
<div ref={scrollRef} className="flex-1 overflow-auto px-1 scrollbar-sleek">
<div ref={scrollRef} className="flex-1 overflow-auto px-1 scrollbar-sleek scroll-smooth">
<div className="relative w-full" style={{ height: `${virtualizer.getTotalSize()}px` }}>
{virtualizer.getVirtualItems().map((vItem) => {
const row = rows[vItem.index]
+1 -1
View File
@@ -10,7 +10,7 @@ export interface RepoSlice {
removeRepo: (repoId: string) => Promise<void>
updateRepo: (
repoId: string,
updates: Partial<Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings'>>
updates: Partial<Pick<Repo, 'displayName' | 'badgeColor' | 'hookSettings' | 'worktreeBaseRef'>>
) => Promise<void>
setActiveRepo: (repoId: string | null) => void
}
+22 -1
View File
@@ -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<AppState, [], [], UISlice> = (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<AppState, [], [], UISlice> = (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
})
})
+97 -8
View File
@@ -21,6 +21,7 @@ export interface WorktreeSlice {
) => Promise<{ ok: true } | { ok: false; error: string }>
clearWorktreeDeleteState: (worktreeId: string) => void
updateWorktreeMeta: (worktreeId: string, updates: Partial<WorktreeMeta>) => Promise<void>
markWorktreeUnreadFromBell: (worktreeId: string) => void
setActiveWorktree: (worktreeId: string | null) => void
allWorktrees: () => Worktree[]
}
@@ -133,21 +134,109 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
},
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<string, Worktree[]>,
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<string, Worktree[]>,
worktreeId: string,
updates: Partial<WorktreeMeta>
): Record<string, Worktree[]> {
let changed = false
const next: Record<string, Worktree[]> = {}
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)
}
+12 -5
View File
@@ -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,
+10 -5
View File
@@ -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<string, WorktreeMeta>
settings: GlobalSettings
ui: {
lastActiveRepoId: string | null
lastActiveWorktreeId: string | null
sidebarWidth: number
}
ui: PersistedUIState
githubCache: {
pr: Record<string, { data: PRInfo | null; fetchedAt: number }>
issue: Record<string, { data: IssueInfo | null; fetchedAt: number }>