diff --git a/src/main/ipc/worktree-logic.test.ts b/src/main/ipc/worktree-logic.test.ts index 61a485b0a..e72bf636a 100644 --- a/src/main/ipc/worktree-logic.test.ts +++ b/src/main/ipc/worktree-logic.test.ts @@ -150,7 +150,8 @@ describe('mergeWorktree', () => { linkedPR: 10, isArchived: true, isUnread: true, - sortOrder: 5 + sortOrder: 5, + lastActivityAt: 1000 } const result = mergeWorktree('repo1', baseGit, meta) expect(result).toEqual({ @@ -166,7 +167,8 @@ describe('mergeWorktree', () => { linkedPR: 10, isArchived: true, isUnread: true, - sortOrder: 5 + sortOrder: 5, + lastActivityAt: 1000 }) }) @@ -179,6 +181,7 @@ describe('mergeWorktree', () => { expect(result.isArchived).toBe(false) expect(result.isUnread).toBe(false) expect(result.sortOrder).toBe(0) + expect(result.lastActivityAt).toBe(0) }) it('strips refs/heads/ prefix from branch for display name', () => { diff --git a/src/main/ipc/worktree-logic.ts b/src/main/ipc/worktree-logic.ts index 53ebf220d..2830fac93 100644 --- a/src/main/ipc/worktree-logic.ts +++ b/src/main/ipc/worktree-logic.ts @@ -104,7 +104,8 @@ export function mergeWorktree( linkedPR: meta?.linkedPR ?? null, isArchived: meta?.isArchived ?? false, isUnread: meta?.isUnread ?? false, - sortOrder: meta?.sortOrder ?? 0 + sortOrder: meta?.sortOrder ?? 0, + lastActivityAt: meta?.lastActivityAt ?? 0 } } diff --git a/src/main/persistence.ts b/src/main/persistence.ts index e83a521d6..b150f6252 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -227,6 +227,7 @@ function getDefaultWorktreeMeta(): WorktreeMeta { linkedPR: null, isArchived: false, isUnread: false, - sortOrder: Date.now() + sortOrder: Date.now(), + lastActivityAt: 0 } } diff --git a/src/renderer/src/components/sidebar/GroupControls.tsx b/src/renderer/src/components/sidebar/GroupControls.tsx index ff892427e..afda352a8 100644 --- a/src/renderer/src/components/sidebar/GroupControls.tsx +++ b/src/renderer/src/components/sidebar/GroupControls.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { ArrowUpAZ, ArrowUpDown, Check, Clock3, FolderTree } from 'lucide-react' +import { ArrowUpAZ, ArrowUpDown, Check, Clock3, FolderTree, Sparkles } from 'lucide-react' import { useAppStore } from '@/store' import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' import { @@ -20,6 +20,10 @@ const SORT_OPTIONS = { label: 'Recent', icon: Clock3 }, + smart: { + label: 'Smart', + icon: Sparkles + }, repo: { label: 'Repo', icon: FolderTree diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index 8e84792da..f2a0b2da3 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' import { cn } from '@/lib/utils' import type { Worktree, Repo } from '../../../../shared/types' +import { buildWorktreeComparator } from './smart-sort' import { branchName, getPRGroupKey, @@ -32,8 +33,9 @@ const WorktreeList = React.memo(function WorktreeList() { 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)) + // Read tabsByWorktree when needed for filtering or sorting + const needsTabs = showActiveOnly || sortBy === 'recent' || sortBy === 'smart' + const tabsByWorktree = useAppStore((s) => (needsTabs ? s.tabsByWorktree : null)) // PR cache only when grouping by pr-status const prCache = useAppStore((s) => (groupBy === 'pr-status' ? s.prCache : null)) @@ -81,37 +83,7 @@ const WorktreeList = React.memo(function WorktreeList() { } // Sort - all.sort((a, b) => { - switch (sortBy) { - case 'name': - return a.displayName.localeCompare(b.displayName) - case 'recent': { - const aTabs = tabsByWorktree?.[a.id] ?? [] - const bTabs = tabsByWorktree?.[b.id] ?? [] - const aActive = aTabs.some((t) => t.ptyId) - const bActive = bTabs.some((t) => t.ptyId) - // Active worktrees pin to top in stable (name) order - if (aActive && bActive) { - return a.displayName.localeCompare(b.displayName) - } - if (aActive) { - return -1 - } - if (bActive) { - return 1 - } - return b.sortOrder - a.sortOrder - } - case 'repo': { - const ra = repoMap.get(a.repoId)?.displayName ?? '' - const rb = repoMap.get(b.repoId)?.displayName ?? '' - const cmp = ra.localeCompare(rb) - return cmp !== 0 ? cmp : a.displayName.localeCompare(b.displayName) - } - default: - return 0 - } - }) + all.sort(buildWorktreeComparator(sortBy, tabsByWorktree, repoMap)) return all }, [worktreesByRepo, filterRepoIds, searchQuery, showActiveOnly, sortBy, repoMap, tabsByWorktree]) diff --git a/src/renderer/src/components/sidebar/smart-sort.ts b/src/renderer/src/components/sidebar/smart-sort.ts new file mode 100644 index 000000000..184fd95db --- /dev/null +++ b/src/renderer/src/components/sidebar/smart-sort.ts @@ -0,0 +1,108 @@ +import { detectAgentStatusFromTitle } from '@/lib/agent-status' +import type { Worktree, Repo, TerminalTab } from '../../../../shared/types' + +type SortBy = 'name' | 'recent' | 'smart' | 'repo' + +/** + * Build a comparator for sorting worktrees based on the current sort mode. + */ +export function buildWorktreeComparator( + sortBy: SortBy, + tabsByWorktree: Record | null, + repoMap: Map +): (a: Worktree, b: Worktree) => number { + return (a, b) => { + switch (sortBy) { + case 'name': + return a.displayName.localeCompare(b.displayName) + case 'recent': { + // Sort by meaningful activity, NOT by last-viewed timestamp. + // Active worktrees still pin to top in stable (name) order. + const aTabs = tabsByWorktree?.[a.id] ?? [] + const bTabs = tabsByWorktree?.[b.id] ?? [] + const aActive = aTabs.some((t) => t.ptyId) + const bActive = bTabs.some((t) => t.ptyId) + if (aActive && bActive) { + return a.displayName.localeCompare(b.displayName) + } + if (aActive) { + return -1 + } + if (bActive) { + return 1 + } + // Fall back to lastActivityAt, then sortOrder for legacy data + const aActivity = a.lastActivityAt || a.sortOrder + const bActivity = b.lastActivityAt || b.sortOrder + return bActivity - aActivity + } + case 'smart': + return computeSmartScore(b, tabsByWorktree) - computeSmartScore(a, tabsByWorktree) + case 'repo': { + const ra = repoMap.get(a.repoId)?.displayName ?? '' + const rb = repoMap.get(b.repoId)?.displayName ?? '' + const cmp = ra.localeCompare(rb) + return cmp !== 0 ? cmp : a.displayName.localeCompare(b.displayName) + } + default: + return 0 + } + } +} + +/** + * Compute a smart sort score for a worktree. + * Higher score = higher in the list. + * + * Scoring: + * running AI job → +100 + * needs attention → +40 (permission prompt, CI failure) + * unread → +20 + * recent activity → +10 (scaled: 10 for just now, decaying over 1 hour) + * last viewed → +1 (scaled: 1 for just now, decaying over 1 hour) + */ +export function computeSmartScore( + worktree: Worktree, + tabsByWorktree: Record | null +): number { + const tabs = tabsByWorktree?.[worktree.id] ?? [] + const liveTabs = tabs.filter((t) => t.ptyId) + const now = Date.now() + + let score = 0 + + // Running: any live PTY with an AI agent actively working + const isRunning = liveTabs.some((t) => detectAgentStatusFromTitle(t.title) === 'working') + if (isRunning) { + score += 100 + } else if (liveTabs.length > 0) { + // Has live terminals but not actively working — still somewhat relevant + score += 5 + } + + // Needs attention: permission prompt or CI-related unread + const needsAttention = liveTabs.some((t) => detectAgentStatusFromTitle(t.title) === 'permission') + if (needsAttention) { + score += 40 + } + + // Unread + if (worktree.isUnread) { + score += 20 + } + + // Recent meaningful activity (decays over 1 hour) + const activityAge = now - (worktree.lastActivityAt || 0) + const ONE_HOUR = 60 * 60 * 1000 + if (worktree.lastActivityAt > 0) { + score += 10 * Math.max(0, 1 - activityAge / ONE_HOUR) + } + + // Last viewed (minor tiebreaker, decays over 1 hour) + const viewAge = now - (worktree.sortOrder || 0) + if (worktree.sortOrder > 0) { + score += 1 * Math.max(0, 1 - viewAge / ONE_HOUR) + } + + return score +} diff --git a/src/renderer/src/components/sidebar/worktree-list-groups.test.ts b/src/renderer/src/components/sidebar/worktree-list-groups.test.ts index 9f183a708..fc60d8191 100644 --- a/src/renderer/src/components/sidebar/worktree-list-groups.test.ts +++ b/src/renderer/src/components/sidebar/worktree-list-groups.test.ts @@ -23,7 +23,8 @@ const worktree: Worktree = { comment: '', isUnread: false, displayName: 'feature/super-critical', - sortOrder: 0 + sortOrder: 0, + lastActivityAt: 0 } describe('getPRGroupKey', () => { diff --git a/src/renderer/src/store/slices/store-cascades.test.ts b/src/renderer/src/store/slices/store-cascades.test.ts index f709cff4b..769e30d96 100644 --- a/src/renderer/src/store/slices/store-cascades.test.ts +++ b/src/renderer/src/store/slices/store-cascades.test.ts @@ -82,6 +82,7 @@ function makeWorktree(overrides: Partial & { id: string; repoId: strin isArchived: false, isUnread: false, sortOrder: 0, + lastActivityAt: 0, ...overrides } } diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts index 9f9f2c76f..21c92187e 100644 --- a/src/renderer/src/store/slices/store-session-cascades.test.ts +++ b/src/renderer/src/store/slices/store-session-cascades.test.ts @@ -81,6 +81,7 @@ function makeWorktree(overrides: Partial & { id: string; repoId: strin isArchived: false, isUnread: false, sortOrder: 0, + lastActivityAt: 0, ...overrides } } diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 820d82d1f..67efe5d0a 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -179,9 +179,14 @@ export const createTerminalSlice: StateCreator }, updateTabPtyId: (tabId, ptyId) => { + let worktreeId: string | null = null set((s) => { const next = { ...s.tabsByWorktree } for (const wId of Object.keys(next)) { + const found = next[wId].some((t) => t.id === tabId) + if (found) { + worktreeId = wId + } next[wId] = next[wId].map((t) => (t.id === tabId ? { ...t, ptyId } : t)) } const existingPtyIds = s.ptyIdsByTabId[tabId] ?? [] @@ -193,12 +198,21 @@ export const createTerminalSlice: StateCreator } } }) + + // Bump meaningful activity when a PTY spawns + if (worktreeId) { + get().bumpWorktreeActivity(worktreeId) + } }, clearTabPtyId: (tabId, ptyId) => { + let worktreeId: string | null = null set((s) => { const next = { ...s.tabsByWorktree } for (const wId of Object.keys(next)) { + if (next[wId].some((t) => t.id === tabId)) { + worktreeId = wId + } next[wId] = next[wId].map((t) => { if (t.id !== tabId) { return t @@ -215,6 +229,12 @@ export const createTerminalSlice: StateCreator : [] return { tabsByWorktree: next, ptyIdsByTabId: nextPtyIdsByTabId } }) + + // Bump meaningful activity when a PTY exits, but skip if this exit + // was triggered by an intentional shutdown (suppressed exits). + if (worktreeId && !(ptyId && get().suppressedPtyExitIds[ptyId])) { + get().bumpWorktreeActivity(worktreeId) + } }, shutdownWorktreeTerminals: async (worktreeId) => { diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index ef984f37e..f5889206e 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -18,7 +18,7 @@ export type UISlice = { setSearchQuery: (q: string) => void groupBy: 'none' | 'repo' | 'pr-status' setGroupBy: (g: UISlice['groupBy']) => void - sortBy: 'name' | 'recent' | 'repo' + sortBy: 'name' | 'recent' | 'smart' | 'repo' setSortBy: (s: UISlice['sortBy']) => void showActiveOnly: boolean setShowActiveOnly: (v: boolean) => void diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts new file mode 100644 index 000000000..2e07b915e --- /dev/null +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -0,0 +1,72 @@ +import type { Worktree, WorktreeMeta } from '../../../../shared/types' + +export type WorktreeDeleteState = { + isDeleting: boolean + error: string | null + canForceDelete: boolean +} + +export type WorktreeSlice = { + worktreesByRepo: Record + activeWorktreeId: string | null + deleteStateByWorktreeId: Record + fetchWorktrees: (repoId: string) => Promise + fetchAllWorktrees: () => Promise + createWorktree: (repoId: string, name: string, baseBranch?: string) => Promise + removeWorktree: ( + worktreeId: string, + force?: boolean + ) => Promise<{ ok: true } | { ok: false; error: string }> + clearWorktreeDeleteState: (worktreeId: string) => void + updateWorktreeMeta: (worktreeId: string, updates: Partial) => Promise + markWorktreeUnreadFromBell: (worktreeId: string) => void + bumpWorktreeActivity: (worktreeId: string) => void + setActiveWorktree: (worktreeId: string | null) => void + allWorktrees: () => Worktree[] +} + +export 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 +} + +export 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 +} + +export function getRepoIdFromWorktreeId(worktreeId: string): string { + const sepIdx = worktreeId.indexOf('::') + return sepIdx === -1 ? worktreeId : worktreeId.slice(0, sepIdx) +} diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index b92c7adb0..11227d45f 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -1,30 +1,12 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' -import type { Worktree, WorktreeMeta } from '../../../../shared/types' - -export type WorktreeDeleteState = { - isDeleting: boolean - error: string | null - canForceDelete: boolean -} - -export type WorktreeSlice = { - worktreesByRepo: Record - activeWorktreeId: string | null - deleteStateByWorktreeId: Record - fetchWorktrees: (repoId: string) => Promise - fetchAllWorktrees: () => Promise - createWorktree: (repoId: string, name: string, baseBranch?: string) => Promise - removeWorktree: ( - worktreeId: string, - force?: boolean - ) => 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[] -} +import { + findWorktreeById, + applyWorktreeUpdates, + getRepoIdFromWorktreeId, + type WorktreeSlice +} from './worktree-helpers' +export type { WorktreeSlice, WorktreeDeleteState } from './worktree-helpers' export const createWorktreeSlice: StateCreator = (set, get) => ({ worktreesByRepo: {}, @@ -171,6 +153,7 @@ export const createWorktreeSlice: StateCreator } let shouldPersist = false + const now = Date.now() set((s) => { const worktree = findWorktreeById(s.worktreesByRepo, worktreeId) if (!worktree || worktree.isUnread) { @@ -178,7 +161,10 @@ export const createWorktreeSlice: StateCreator } shouldPersist = true return { - worktreesByRepo: applyWorktreeUpdates(s.worktreesByRepo, worktreeId, { isUnread: true }) + worktreesByRepo: applyWorktreeUpdates(s.worktreesByRepo, worktreeId, { + isUnread: true, + lastActivityAt: now + }) } }) @@ -187,13 +173,35 @@ export const createWorktreeSlice: StateCreator } void window.api.worktrees - .updateMeta({ worktreeId, updates: { isUnread: true } }) + .updateMeta({ worktreeId, updates: { isUnread: true, lastActivityAt: now } }) .catch((err) => { console.error('Failed to persist unread worktree bell state:', err) void get().fetchWorktrees(getRepoIdFromWorktreeId(worktreeId)) }) }, + bumpWorktreeActivity: (worktreeId) => { + const now = Date.now() + set((s) => { + const worktree = findWorktreeById(s.worktreesByRepo, worktreeId) + if (!worktree) { + return {} + } + return { + worktreesByRepo: applyWorktreeUpdates(s.worktreesByRepo, worktreeId, { + lastActivityAt: now + }) + } + }) + + void window.api.worktrees + .updateMeta({ worktreeId, updates: { lastActivityAt: now } }) + .catch((err) => { + console.error('Failed to persist worktree activity timestamp:', err) + void get().fetchWorktrees(getRepoIdFromWorktreeId(worktreeId)) + }) + }, + setActiveWorktree: (worktreeId) => { let shouldClearUnread = false const now = Date.now() @@ -279,49 +287,3 @@ export const createWorktreeSlice: StateCreator 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/types.ts b/src/shared/types.ts index 3126ef887..8bc0e783c 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -29,6 +29,7 @@ export type Worktree = { isArchived: boolean isUnread: boolean sortOrder: number + lastActivityAt: number } & GitWorktreeInfo // ─── Worktree metadata (persisted user-authored fields only) ───────── @@ -40,6 +41,7 @@ export type WorktreeMeta = { isArchived: boolean isUnread: boolean sortOrder: number + lastActivityAt: number } // ─── Terminal Tab ──────────────────────────────────────────────────── @@ -178,7 +180,7 @@ export type PersistedUIState = { sidebarWidth: number rightSidebarWidth: number groupBy: 'none' | 'repo' | 'pr-status' - sortBy: 'name' | 'recent' | 'repo' + sortBy: 'name' | 'recent' | 'smart' | 'repo' filterRepoIds: string[] uiZoomLevel: number }