codeburn/app/renderer/components/ProjectScopePicker.tsx
Resham Joshi 8fb478904e
feat: group a deleted sibling clone with its repository by folder name (#1692)
* feat(app): transient project selector in the desktop top bar

Scopes every report to one project path for the current session through
the same narrowing the VS Code workspace scope uses. The saved project
filter is never written; a restart is back on all projects.

* fix(app): let the name pickers ellipsize before the top bar overflows

* fix: key the daily project split per real path, not per label

A project label can span several paths: every Claude session started from the
home folder shares -Users-<name>, while its cwd puts it in a different project.
The day rollup keyed by label kept the first path it saw, so a rooted
--project headline took the whole label bucket on some days and missed it on
others. Key per (label, path), read old label-keyed days unchanged, bump the
daily cache to v68.

* fix(app): list only selectable, non-zero projects in the top bar picker

Rows with no session cwd (the Cursor and Grok Bot imports, provider label
fallbacks) report their label as the path, so the picker offered names the
bridge refuses and dash-to-slash guesses like eywa/lab. Keep only absolute
paths, and drop rows whose lifetime cost rounds to $0.00. The old test that
rooted a slashless Codex path is replaced: Codex now records the absolute cwd,
and a slashless path is always the label fallback.

* fix(app): show a toast when a project pick is refused

The pick was dropped silently. Also pin that an encoded -Users-... label
never reaches the picker list.

* feat: group projects by git repository

Clones and worktrees that share an origin remote are one project in every
project list (report JSON, By Project, the top bar picker, the terminal
dashboard), with the checkouts listed under the row. A --project path inside
a checkout scopes to the whole repository; --exact-project keeps the old
single-folder match. The origin is learned while the folder exists, kept in
git-origins.json and on each day's project entry (daily cache v69), so a
deleted scratch clone stays in its repository. The report JSON project list
now comes from the durable day set, so a row costs what selecting it reports.

* fix: a picked project row selects that row exactly

The top bar pick sends =<path>: a checkout in a repository still selects the
whole repository, and a plain folder selects itself without the folders under
it, which are rows of their own. So the picker row and the headline it opens
are the same set. Typed --project paths keep their prefix match. Days adopted
from an older cache learn the origin of every checkout that still exists, and
lookups outside a parse are saved on exit.

* fix: key the status snapshot on --exact-project

* feat: one Temporary folders row for scratch folders outside a repository

Every project path under a temp root (os.tmpdir(), /tmp, /var/folders and
their /private spellings) that is not a checkout of a known repository folds
into one row, in the report JSON, By Project, the terminal dashboard, the top
bar picker and the Settings Projects pane. Its pattern @temp selects or hides
all of them. The Projects pane leaves out rows that round to $0.00 unless a
saved pattern names them, and a saved pattern naming any checkout of a
repository row now names the whole row in the renderer too.

* feat: group a deleted sibling folder with its repository by folder name

A deleted folder with no recorded origin, named <checkout>-<suffix> or
<checkout>_<suffix> next to exactly one repository's checkout, joins that
repository row. The checkout entry carries matchedByFolderName and the Spend
drill-down labels it. Existing folders and names two repositories could claim
are left alone.

* feat: the longest checkout name wins a folder-name match

A deleted folder that fits several sibling checkouts joins the one with the
longest name; it is skipped only when the longest fits belong to two
repositories. The report project type declares matchedByFolderName.

* fix(claude): attribute each call to the project of its own cwd

* test: fold the temp roots the tests set, compare checkout ids as identities (Windows)

* test: compare folder-name checkout ids as identities (Windows)

* fix(claude): keep subfolder cwds in their project, count and show a split session once

* fix: an exclude path hides that checkout only, repository rows count a session once

* feat: mark folder-name matches in the CLI report and the project picker

* fix(claude): a deleted subfolder stays its own project
2026-10-08 06:54:41 +02:00

110 lines
4.9 KiB
TypeScript

import { useState } from 'react'
import { t } from '../i18n'
import { shortenProjectPath } from '../lib/format'
import { codeburn } from '../lib/ipc'
import { isRooted, projectVisible } from '../lib/projectMatch'
import type { ProjectFilter, ProjectRow } from '../lib/types'
import { Dropdown, type DropdownOption } from './Dropdown'
/** `path` is one checkout; the CLI widens it to its whole repository. */
export type TransientProject = { name: string; path: string; label?: string }
const ALL = ''
const MAX_SHOWN = 100
/** Projects the saved filter shows, costliest first. Only rows with an
* absolute path, and the temporary-folders row: a bucket with no session cwd (an import, a provider's label
* fallback) reports its label as the path, and no rooted filter selects it.
* Rows that round to $0.00 are left out too, they would show nothing. */
export function projectScopeOptions(projects: ProjectRow[], filter: ProjectFilter): Array<DropdownOption & { name: string }> {
const byPath = new Map<string, ProjectRow>()
for (const project of projects) {
if ((!isRooted(project.path) && !project.temporary) || !projectVisible(project, filter)) continue
const path = project.path.trim()
const held = byPath.get(path)
if (!held || (held.cost ?? 0) < (project.cost ?? 0)) byPath.set(path, project)
}
const rows = [...byPath].filter(([, project]) => Math.round((project.cost ?? 0) * 100) > 0).sort((a, b) => (b[1].cost ?? 0) - (a[1].cost ?? 0))
const labels = new Map<string, number>()
for (const [path] of rows) {
const label = shortenProjectPath(path, 2)
labels.set(label, (labels.get(label) ?? 0) + 1)
}
return rows.map(([path, project]) => {
const label = shortenProjectPath(path, 2)
return {
value: path,
label: project.temporary ? t('shell.project.temporary') : project.checkouts ? project.name : labels.get(label)! > 1 ? path : label,
name: project.name,
...(project.checkouts?.some(c => c.matchedByFolderName) ? { title: t('shell.project.matchedByFolderName') } : {}),
}
})
}
export function matchProjectOptions<T extends DropdownOption>(options: T[], query: string): T[] {
const needle = query.trim().toLowerCase()
if (!needle) return options
return options.filter(option => option.label.toLowerCase().includes(needle) || option.value.toLowerCase().includes(needle))
}
// The lifetime list is the heaviest read the app makes, so it runs on the first
// open only and is kept for the session, like the Projects pane's.
let catalog: Promise<ProjectRow[]> | null = null
function loadCatalog(): Promise<ProjectRow[]> {
catalog ??= codeburn.getUnfilteredProjects().then(report => report.projects).catch(err => {
catalog = null
throw err
})
return catalog
}
/** Scopes every report to one project until cleared or the app restarts. */
export function ProjectScopePicker({ value, onSelect }: { value: TransientProject | null; onSelect: (project: TransientProject | null) => void }) {
const [options, setOptions] = useState<Array<DropdownOption & { name: string }> | null>(null)
const [failed, setFailed] = useState(false)
const [query, setQuery] = useState('')
const load = () => {
setFailed(false)
void Promise.all([loadCatalog(), codeburn.getProjectFilter()])
.then(([projects, filter]) => setOptions(projectScopeOptions(projects, filter)))
.catch(() => setFailed(true))
}
const matches = matchProjectOptions(options ?? [], query)
const shown = matches.slice(0, MAX_SHOWN)
const selected = value ? { value: value.path, label: value.label ?? shortenProjectPath(value.path, 2), name: value.name } : null
const list: DropdownOption[] = query.trim()
? shown
: [
{ value: ALL, label: t('shell.project.all') },
...(selected && !shown.some(option => option.value === selected.value) ? [selected] : []),
...shown,
]
const footer = failed ? t('shell.project.error')
: options === null ? t('shell.project.loading')
: matches.length === 0 ? t('shell.project.noMatch')
: matches.length > shown.length ? t('shell.project.more', { shown: shown.length.toLocaleString(), total: matches.length.toLocaleString() })
: undefined
return (
<Dropdown
id="project-scope"
ariaLabel={t('shell.project.ariaLabel')}
value={value?.path ?? ALL}
options={list}
onChange={path => {
if (path === ALL) { onSelect(null); return }
const option = options?.find(entry => entry.value === path) ?? selected
if (!option) return
// Only a repository row is named apart from its path.
const named = option.label !== option.value && option.label !== shortenProjectPath(option.value, 2)
onSelect({ name: option.name, path: option.value, ...(named ? { label: option.label } : {}) })
}}
footer={footer}
search={{ value: query, onChange: setQuery, placeholder: t('shell.project.search'), ariaLabel: t('shell.project.search') }}
onOpen={load}
/>
)
}