diff --git a/CHANGELOG.md b/CHANGELOG.md index 45ec051c..47fbaa7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,18 @@ tagged `vX.Y.Z`. ## Unreleased +### Added + +- **Recent projects widget.** Lists the folders you worked in lately — git repositories under the + folders you choose, plus, if you tick them, Claude Code, Codex, VS Code, Cursor, JetBrains IDEs, + zoxide, tmux and Herdr — and opens one with a tap in Finder, a terminal, your editor (a + JetBrains IDE included) or Herdr (the pane already in that folder, else a new one, with Herdr's + terminal brought to the front), or starts Claude Code or Codex in a new Herdr pane or tmux + window on it; a long press offers the other installed applications, and can make one the + project's own for every later tap. Without one, the files at a project's root can suggest the + right IDE (a `.sln` for Rider, a `Cargo.toml` for RustRover…). Only folder paths, dates and + the names at a project's root are read, never a conversation or a file's contents. + ### Fixed - **The clipboard widget masks one-time codes.** A six-digit code copied from a text message or diff --git a/README.md b/README.md index 5fffb256..8ab322af 100644 --- a/README.md +++ b/README.md @@ -570,7 +570,8 @@ limits, and how to report a problem: **[SECURITY.md](SECURITY.md)**. ## Credits and trademarks Fremkit is written by [usul](https://github.com/fdussert), with -[FlorianBruniaux](https://github.com/FlorianBruniaux) and [mcouzinet](https://github.com/mcouzinet). +[FlorianBruniaux](https://github.com/FlorianBruniaux), [mcouzinet](https://github.com/mcouzinet) and +[LivioGama](https://github.com/LivioGama). The widgets and themes on the registry name their own authors on their cards. The admin's **Settings → About** lists the same people, from `ui/src/shared/credits.ts`. diff --git a/server/src/app.ts b/server/src/app.ts index b9ecc4f2..9b4887ef 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -64,6 +64,7 @@ import { createShortcutsProvider } from './providers/shortcuts.js' import { createServiceStatusProvider } from './providers/service-status.js' import { createSystemProvider } from './providers/system.js' import { createDiskMapProvider } from './providers/disk-map.js' +import { createRecentProjectsProvider, MEMORY_FILE as RECENT_PROJECTS_FILE, RECENT_PROJECTS_CHANNEL, RECENT_PROJECTS_WIDGET } from './providers/recent-projects/index.js' import { BrightnessService } from './brightness/service.js' import { createBrightnessProvider, BRIGHTNESS_INTERVAL_MS } from './brightness/provider.js' import { brightnessRoutes } from './brightness/routes.js' @@ -284,6 +285,8 @@ export async function buildApp(opts: AppOptions): Promise { const config = store.get() return instanceInScope(config, commandScope(ctx, screenOfDevice), instanceId) ? findInstance(config, instanceId) : null } + /** Kept for the diagnostics, which report its sources' counts. Null in demo mode. */ + let recentProjects: ReturnType | null = null /** Every real provider: the Mac, the accounts, the helper's reports. Never called in demo mode. */ function registerRealProviders(): void { for (const p of opts.providers ?? []) registry.register(p) @@ -309,6 +312,13 @@ export async function buildApp(opts: AppOptions): Promise { // Registered here, not in providers/index.ts, because that is where the config store lives. registry.register(createShortcutsProvider(undefined, instances)) registry.register(createServiceStatusProvider({}, instances)) + // Reads what every shown tile ticked, so a source no tile asked for is never read. + recentProjects = createRecentProjectsProvider({ + instances: () => findInstances(store.get(), RECENT_PROJECTS_WIDGET), + memoryFile: join(opts.dataDir, RECENT_PROJECTS_FILE), + onChange: () => registry.refresh(RECENT_PROJECTS_CHANNEL), + }) + registry.register(recentProjects) // A paired device may set only its own screen's brightness: see mayCommandBrightness. Read // at command time, so a device moved to another screen (or unpaired) is judged as it is now. registry.register(createBrightnessProvider(brightness, brightnessChanged, (id) => deviceService.deviceScreenOf(id))) @@ -375,7 +385,14 @@ export async function buildApp(opts: AppOptions): Promise { // How each provider's last poll went, for the editor's widget health (providers/health.ts). const stopHealth = publishHealth(registry, (channel, data) => hub.broadcast(channel, data)) let showAccountEmail = store.get().privacy.showAccountEmail + // A tile that ticks a source or adds a git root sees it now, not on the next minute's poll. + let recentProjectsWants = JSON.stringify(findInstances(store.get(), RECENT_PROJECTS_WIDGET)) store.onChange((cfg) => { + const wants = JSON.stringify(findInstances(cfg, RECENT_PROJECTS_WIDGET)) + if (wants !== recentProjectsWants) { + recentProjectsWants = wants + registry.refresh(RECENT_PROJECTS_CHANNEL) + } setServerLocale(cfg.locale) if (cfg.privacy.showAccountEmail !== showAccountEmail) { showAccountEmail = cfg.privacy.showAccountEmail @@ -564,6 +581,7 @@ export async function buildApp(opts: AppOptions): Promise { channelFor: (connection) => connections.channelFor(connection), secretsFor: (connection) => connections.secretsFor(connection), channels: () => registry.status(), + recentProjects: () => recentProjects?.snapshot()?.sources ?? null, devices: () => devices.list(), remoteAccess: () => devices.enabled, accessToken: opts.accessToken, diff --git a/server/src/demo/providers.ts b/server/src/demo/providers.ts index dd4521c3..df225d7f 100644 --- a/server/src/demo/providers.ts +++ b/server/src/demo/providers.ts @@ -63,9 +63,65 @@ export function createDemoProviders(opts: DemoProviderOptions): Provider[] { rtkProvider(now), { channel: 'shortcuts', commands: { open: ACTED } }, serviceStatusProvider(now, opts.instances ?? ((id) => findInstance(opts.config(), id))), + recentProjectsProvider(now), ] } +/** Invented folders under an invented home, touched over the last few days. */ +function recentProjectsProvider(now: () => number): Provider { + const HOUR = 3_600_000 + const rows: { name: string; parent: string; ago: number; sources: string[]; suggested?: string }[] = [ + { name: 'example-api', parent: '~/Dev', ago: 0.3, sources: ['git', 'claude', 'herdr'], suggested: 'jetbrains-rider' }, + { name: 'dashboard-web', parent: '~/Dev', ago: 2, sources: ['git', 'vscode'] }, + { name: 'mobile-app', parent: '~/Dev/clients/acme', ago: 5, sources: ['git', 'claude'], suggested: 'xcode' }, + { name: 'infra', parent: '~/Dev', ago: 26, sources: ['git', 'herdr'], suggested: 'jetbrains-goland' }, + { name: 'design-system', parent: '~/Dev/clients/acme', ago: 50, sources: ['git', 'vscode', 'claude'] }, + { name: 'notes', parent: '~/Documents', ago: 74, sources: ['claude'] }, + { name: 'blog', parent: '~/Dev/personal', ago: 120, sources: ['git'] }, + ] + const pathOf = (r: { parent: string; name: string }) => `${r.parent.replace('~', '/Users/demo')}/${r.name}` + // Openers set during the demo, in memory; the dashboard one starts with one of its own. + const openers = new Map([[pathOf(rows[1]), 'zed']]) + return { + channel: 'recent-projects', + intervalMs: 60_000, + poll: async () => { + const t = now() + const projects = rows.map((r) => { + const path = pathOf(r) + const opener = openers.get(path) + return { + path, + name: r.name, + parent: r.parent, + seenAt: Math.round(t - r.ago * HOUR), + sources: r.sources, + ...(r.sources.includes('git') ? { gitRoots: ['~/Dev'] } : {}), + ...(opener ? { opener } : r.suggested ? { suggested: r.suggested } : {}), + } + }) + const ids = ['git', 'claude', 'codex', 'vscode', 'cursor', 'jetbrains', 'zoxide', 'tmux', 'herdr'] + const on = new Set(['git', 'claude', 'vscode', 'herdr']) + return { + projects, + sources: ids.map((id) => ({ id, enabled: on.has(id), available: on.has(id), count: projects.filter((p) => p.sources.includes(id)).length })), + apps: ['finder', 'terminal', 'vscode', 'zed', 'xcode', 'herdr', 'herdr-claude', 'herdr-codex', 'jetbrains-rider', 'jetbrains-goland'], + updatedAt: t, + } + }, + commands: { + open: ACTED, + setOpener: async (payload: unknown) => { + const { path, app } = (payload ?? {}) as { path?: unknown; app?: unknown } + if (typeof path !== 'string' || !rows.some((r) => pathOf(r) === path)) return { ok: false, error: 'unknown-project' } + if (typeof app === 'string') openers.set(path, app) + else openers.delete(path) + return { ok: true } + }, + }, + } +} + function systemProvider(now: () => number, startedAt: number): Provider { const total = 32 * GB return { diff --git a/server/src/demo/seed.ts b/server/src/demo/seed.ts index e8f7cdca..699421ab 100644 --- a/server/src/demo/seed.ts +++ b/server/src/demo/seed.ts @@ -38,6 +38,7 @@ export const DEMO_SETTINGS: Record> = { { name: 'Backup NAS', kind: 'ping', url: '192.0.2.10' }, ], }, + 'recent-projects': { source_git: true, source_claude: true, source_vscode: true, source_herdr: true, gitRoots: [{ path: '~/Dev' }] }, shortcuts: { buttons: [ { label: 'Mail', kind: 'app', target: 'Mail', icon: '✉️' }, @@ -94,7 +95,8 @@ const PAGES: { id: string; name: string; items: (Placement & { widgetId: string { instanceId: 'processes-1', widgetId: 'processes', x: 24, y: 0, w: 16, h: 8 }, { instanceId: 'clipboard-1', widgetId: 'clipboard', x: 24, y: 8, w: 16, h: 8 }, { instanceId: 'shortcuts-1', widgetId: 'shortcuts', x: 40, y: 0, w: 24, h: 8 }, - { instanceId: 'clock-2', widgetId: 'clock', x: 40, y: 8, w: 24, h: 8 }, + { instanceId: 'clock-2', widgetId: 'clock', x: 40, y: 8, w: 12, h: 8 }, + { instanceId: 'recent-projects-1', widgetId: 'recent-projects', x: 52, y: 8, w: 12, h: 8 }, ], }, ] diff --git a/server/src/diagnostics/report.ts b/server/src/diagnostics/report.ts index d4ae2e82..0d1ce6ef 100644 --- a/server/src/diagnostics/report.ts +++ b/server/src/diagnostics/report.ts @@ -40,6 +40,11 @@ export interface DiagnosticsFacts { /** Channels that are watched or have polled; the rest are only counted. */ providers: { channel: string; watched: boolean; state: string }[] idleProviders: number + /** + * The recent-projects sources a tile ticked: an id, whether it is installed, how many projects + * it named, and its error code. Counts only — never a path. + */ + recentProjects?: { id: string; available: boolean; count: number; error?: string }[] devices: { paired: number; remoteAccess: boolean } log: LogSource | null } @@ -94,6 +99,13 @@ export function renderReport(f: DiagnosticsFacts): string { if (f.idleProviders > 0) out.push('', `${f.idleProviders} other channels idle, never polled.`) out.push('') + if (f.recentProjects?.length) { + out.push('### Recent projects sources', '') + out.push('| Source | Installed | Projects | Error |', '|---|---|---|---|') + for (const r of f.recentProjects) out.push(`| ${r.id} | ${r.available ? 'yes' : 'no'} | ${r.count} | ${r.error ?? '–'} |`) + out.push('') + } + if (f.log) { const where = f.log.kind === 'file' ? 'server.log' : 'since this server started' out.push(`### Server log (last ${f.log.lines.length} lines, ${where}, redacted)`, '') @@ -211,6 +223,8 @@ export interface DiagnosticsDeps { channelFor: (connection: Connection) => string secretsFor: (connection: Connection) => Promise> channels: () => ChannelStatus[] + /** The recent-projects provider's last source statuses, or null before its first poll. */ + recentProjects?: () => { id: string; enabled: boolean; available: boolean; count: number; error?: string }[] | null devices: () => { name: string }[] remoteAccess: () => boolean accessToken: string | null @@ -359,6 +373,8 @@ export async function buildDiagnostics(deps: DiagnosticsDeps): Promise { connections, providers, idleProviders: allChannels.length - active.length, + recentProjects: deps.recentProjects?.()?.filter((r) => r.enabled) + .map((r) => ({ id: r.id, available: r.available, count: r.count, ...(r.error ? { error: r.error } : {}) })), devices: { paired: pairedDevices.length, remoteAccess: deps.remoteAccess() }, log: deps.log ? await deps.log(RAW_LOG_LINES).then(compactLog, () => null) : null, } diff --git a/server/src/providers/exec.ts b/server/src/providers/exec.ts index 6c532330..2accc8ee 100644 --- a/server/src/providers/exec.ts +++ b/server/src/providers/exec.ts @@ -8,11 +8,11 @@ import { execFile } from 'node:child_process' * arguments are passed as an array and never re-parsed, so nothing a caller supplies can be read * as shell syntax. */ -export type Exec = (file: string, args: string[]) => Promise +export type Exec = (file: string, args: string[], opts?: { timeoutMs?: number }) => Promise -export const execCommand: Exec = (file, args) => +export const execCommand: Exec = (file, args, opts) => new Promise((resolve, reject) => { - execFile(file, args, { timeout: 5000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => { + execFile(file, args, { timeout: opts?.timeoutMs ?? 5000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout, stderr) => { if (err) reject(new Error(stderr.trim() || err.message)) else resolve(stdout) }) diff --git a/server/src/providers/recent-projects/apps.ts b/server/src/providers/recent-projects/apps.ts new file mode 100644 index 00000000..5509739d --- /dev/null +++ b/server/src/providers/recent-projects/apps.ts @@ -0,0 +1,161 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' +import type { Exec } from '../exec.js' +import { detectHerdrTerminal, openInHerdr, startAgentInHerdr, type Agent, type HerdrReach, type HerdrTerminal } from './herdr.js' +import type { ResolveBinary } from './sources/cli.js' +import { exists } from './util.js' + +/** What a project can be opened with: a closed list, nothing a widget composes. */ +export const APP_IDS = [ + 'finder', 'terminal', 'iterm', 'ghostty', 'vscode', 'cursor', 'zed', 'xcode', 'herdr', 'tmux', + 'herdr-claude', 'herdr-codex', 'tmux-claude', 'tmux-codex', + 'jetbrains-idea', 'jetbrains-idea-ce', 'jetbrains-webstorm', 'jetbrains-pycharm', 'jetbrains-pycharm-ce', + 'jetbrains-phpstorm', 'jetbrains-goland', 'jetbrains-rider', 'jetbrains-clion', 'jetbrains-rustrover', + 'jetbrains-rubymine', 'jetbrains-datagrip', 'jetbrains-android-studio', +] as const +export type AppId = (typeof APP_IDS)[number] + +/** The multiplexer and the coding agent a `-` choice launches. */ +const AGENT_LAUNCHES: Partial> = { + 'herdr-claude': { mux: 'herdr', agent: 'claude' }, + 'herdr-codex': { mux: 'herdr', agent: 'codex' }, + 'tmux-claude': { mux: 'tmux', agent: 'claude' }, + 'tmux-codex': { mux: 'tmux', agent: 'codex' }, +} + +/** + * tmux runs a lone command through the shell, so an agent is offered under tmux only when its + * path reads the same to a shell: letters, digits and `/._-`, nothing it would split or expand. + */ +const SHELL_INERT = /^\/[\w./-]+$/ + +const OPEN = '/usr/bin/open' + +/** + * The bundle each Mac application is found as, in the places applications are installed. Fixed + * names checked for existence: nothing found on disk ever becomes an id or a label. + */ +const BUNDLES: Partial> = { + finder: ['/System/Library/CoreServices/Finder.app'], + terminal: ['/System/Applications/Utilities/Terminal.app', '/Applications/Utilities/Terminal.app'], + iterm: ['iTerm.app'], + ghostty: ['Ghostty.app'], + vscode: ['Visual Studio Code.app'], + cursor: ['Cursor.app'], + zed: ['Zed.app'], + xcode: ['Xcode.app'], + // JetBrains IDEs under the names their installers and the Toolbox give the bundle. + 'jetbrains-idea': ['IntelliJ IDEA.app', 'IntelliJ IDEA Ultimate.app'], + 'jetbrains-idea-ce': ['IntelliJ IDEA CE.app', 'IntelliJ IDEA Community Edition.app'], + 'jetbrains-webstorm': ['WebStorm.app'], + 'jetbrains-pycharm': ['PyCharm.app', 'PyCharm Professional Edition.app', 'PyCharm Professional.app'], + 'jetbrains-pycharm-ce': ['PyCharm CE.app', 'PyCharm Community Edition.app'], + 'jetbrains-phpstorm': ['PhpStorm.app'], + 'jetbrains-goland': ['GoLand.app'], + 'jetbrains-rider': ['Rider.app', 'JetBrains Rider.app'], + 'jetbrains-clion': ['CLion.app'], + 'jetbrains-rustrover': ['RustRover.app'], + 'jetbrains-rubymine': ['RubyMine.app'], + 'jetbrains-datagrip': ['DataGrip.app'], + 'jetbrains-android-studio': ['Android Studio.app', 'Android Studio Preview.app'], +} + +export interface AppDeps { + exec: Exec + resolveBinary: ResolveBinary + /** Whether a path exists; swapped in tests so they do not depend on what this Mac has. */ + exists?: (path: string) => Promise +} + +/** The bundle path of an application, or null when it is not installed. */ +async function bundleOf(app: AppId, has: (p: string) => Promise): Promise { + for (const name of BUNDLES[app] ?? []) { + const candidates = name.startsWith('/') + ? [name] + // The JetBrains Toolbox installs into ~/Applications, or into a folder of its own there. + : [join('/Applications', name), join(homedir(), 'Applications', name), join(homedir(), 'Applications', 'JetBrains Toolbox', name)] + for (const c of candidates) if (await has(c)) return c + } + return null +} + +/** The multiplexer's and the agent's absolute paths, or null when either is missing (or unusable under tmux). */ +async function agentCommand(mux: 'herdr' | 'tmux', agent: Agent, deps: AppDeps): Promise<{ mux: string; agent: string } | null> { + const [muxBin, agentBin] = await Promise.all([deps.resolveBinary(mux), deps.resolveBinary(agent)]) + if (!muxBin || !agentBin || (mux === 'tmux' && !SHELL_INERT.test(agentBin))) return null + return { mux: muxBin, agent: agentBin } +} + +/** The applications of `APP_IDS` installed on this Mac, in that order. */ +export async function installedApps(deps: AppDeps): Promise { + const has = deps.exists ?? exists + const out: AppId[] = [] + for (const app of APP_IDS) { + const launch = AGENT_LAUNCHES[app] + if (launch) { + if (await agentCommand(launch.mux, launch.agent, deps)) out.push(app) + } else if (app === 'herdr' || app === 'tmux') { + if (await deps.resolveBinary(app)) out.push(app) + } else if (await bundleOf(app, has)) { + out.push(app) + } + } + return out +} + +export type OpenResult = + | { ok: true; herdr?: HerdrReach; agent?: 'started' | 'waiting'; front?: AppId | null } + | { ok: false; error: string } + +/** + * Opens one folder with one application. `path` has been checked against the snapshot by the + * caller; every program is run by its absolute path with an argument list, never a shell. + * Herdr goes to the pane already in the folder, or splits a new one beside the focused pane + * without moving the focus, then brings its terminal forward; tmux opens a new window. A + * `-` choice always opens a new pane (or window) and starts that agent in it. + */ +export async function openWith(app: AppId, path: string, deps: AppDeps, opts: { terminal?: HerdrTerminal } = {}): Promise { + const launch = AGENT_LAUNCHES[app] + if (launch) { + const cmd = await agentCommand(launch.mux, launch.agent, deps) + if (!cmd) return { ok: false, error: 'not-installed' } + if (launch.mux === 'tmux') { + // One argv item, the agent's absolute path: tmux starts it in the new window, at the folder. + await deps.exec(cmd.mux, ['new-window', '-c', path, cmd.agent]) + return { ok: true } + } + const agent = await startAgentInHerdr(deps.exec, cmd.mux, path, launch.agent) + return { ok: true, herdr: 'new-pane', agent, front: await bringTerminalForward(opts.terminal ?? 'auto', deps) } + } + if (app === 'herdr' || app === 'tmux') { + const bin = await deps.resolveBinary(app) + if (!bin) return { ok: false, error: 'not-installed' } + if (app === 'tmux') { + await deps.exec(bin, ['new-window', '-c', path]) + return { ok: true } + } + const herdr = await openInHerdr(deps.exec, bin, path) + return { ok: true, herdr, front: await bringTerminalForward(opts.terminal ?? 'auto', deps) } + } + const bundle = await bundleOf(app, deps.exists ?? exists) + if (!bundle) return { ok: false, error: 'not-installed' } + await deps.exec(OPEN, ['-a', bundle, path]) + return { ok: true } +} + +/** + * Activates the terminal Herdr runs in (`open -a` with no file only brings it forward): the one + * the tile chose, or the one found running Herdr's client. Null when none is known or installed; + * a terminal that will not come forward never fails the open, whose work in Herdr is done. + */ +async function bringTerminalForward(choice: HerdrTerminal, deps: AppDeps): Promise { + try { + const app = choice === 'auto' ? await detectHerdrTerminal(deps.exec) : choice + const bundle = app && (await bundleOf(app, deps.exists ?? exists)) + if (!app || !bundle) return null + await deps.exec(OPEN, ['-a', bundle]) + return app + } catch { + return null + } +} diff --git a/server/src/providers/recent-projects/herdr.ts b/server/src/providers/recent-projects/herdr.ts new file mode 100644 index 00000000..f48ee89f --- /dev/null +++ b/server/src/providers/recent-projects/herdr.ts @@ -0,0 +1,179 @@ +import { realpath } from 'node:fs/promises' +import type { Exec } from '../exec.js' + +/** The terminal Herdr runs in, brought to the front once a pane is focused: a closed list. */ +export const HERDR_TERMINALS = ['auto', 'terminal', 'iterm', 'ghostty'] as const +export type HerdrTerminal = (typeof HERDR_TERMINALS)[number] +export type TerminalApp = Exclude + +/** How far the open went: the pane that was already there, only its tab, or a new pane. */ +export type HerdrReach = 'pane' | 'tab' | 'new-pane' + +const PS = '/bin/ps' +/** `pane neighbor` questions asked to find a way to a pane: a tab holds a handful of panes. */ +const MAX_NEIGHBOR_QUERIES = 32 +const DIRECTIONS = ['left', 'right', 'up', 'down'] as const + +interface Pane { + pane_id: string + tab_id: string + workspace_id: string + cwd?: string + foreground_cwd?: string +} + +function resultOf(stdout: string): Record | null { + try { + const data = JSON.parse(stdout) as { result?: unknown } + return data && typeof data.result === 'object' && data.result ? (data.result as Record) : null + } catch { + return null + } +} + +/** The panes of `herdr pane list` with the ids an open needs; anything malformed is skipped. */ +export function parsePanes(stdout: string): Pane[] { + const panes = resultOf(stdout)?.panes + if (!Array.isArray(panes)) return [] + return panes.filter((p): p is Pane => + !!p && typeof p.pane_id === 'string' && typeof p.tab_id === 'string' && typeof p.workspace_id === 'string') +} + +async function canonical(path: string): Promise { + return realpath(path).catch(() => null) +} + +/** The first pane whose foreground process or shell sits in `path` (a canonical folder). */ +export async function paneAt(panes: Pane[], path: string): Promise { + for (const pane of panes) { + for (const cwd of [pane.foreground_cwd, pane.cwd]) { + if (typeof cwd !== 'string' || !cwd.startsWith('/')) continue + if (cwd === path || (await canonical(cwd)) === path) return pane + } + } + return null +} + +/** + * Moves Herdr's focus to `target` inside its (already focused) tab. Herdr focuses a pane only by + * direction, so the way is found first with `pane neighbor`, which asks the same question + * `pane focus --direction` answers and moves nothing; the steps are then taken, and the focus is + * read back. True only when Herdr says the target is focused. A zoomed tab is left alone. + */ +async function walkTo(exec: Exec, bin: string, target: string): Promise { + const layoutOf = async () => resultOf(await exec(bin, ['pane', 'layout', '--pane', target]))?.layout as + { focused_pane_id?: unknown; zoomed?: unknown; panes?: { pane_id?: unknown }[] } | undefined + const layout = await layoutOf() + if (!layout || layout.zoomed === true || typeof layout.focused_pane_id !== 'string') return false + const start = layout.focused_pane_id + if (start === target) return true + const inTab = new Set((layout.panes ?? []).map((p) => p.pane_id).filter((id): id is string => typeof id === 'string')) + if (!inTab.has(target) || !inTab.has(start)) return false + + const via = new Map() + const queue = [start] + let queries = 0 + search: while (queue.length) { + const from = queue.shift()! + for (const direction of DIRECTIONS) { + if (++queries > MAX_NEIGHBOR_QUERIES) break search + const res = resultOf(await exec(bin, ['pane', 'neighbor', '--direction', direction, '--pane', from])) + const next = (res?.neighbor as { neighbor_pane_id?: unknown } | undefined)?.neighbor_pane_id + if (typeof next !== 'string' || !inTab.has(next) || next === start || via.has(next)) continue + via.set(next, { from, direction }) + if (next === target) break search + queue.push(next) + } + } + if (!via.has(target)) return false + const steps: { from: string; direction: string }[] = [] + for (let at = target; at !== start; at = via.get(at)!.from) steps.unshift(via.get(at)!) + for (const step of steps) await exec(bin, ['pane', 'focus', '--direction', step.direction, '--pane', step.from]) + return (await layoutOf())?.focused_pane_id === target +} + +/** + * Opens a folder in Herdr: the pane already sitting in it when there is one (its workspace, its + * tab, then the pane itself when the way there can be walked), else a new pane split beside the + * focused one without taking the focus. Every call is Herdr's CLI by its absolute path with an + * argument list. + */ +export async function openInHerdr(exec: Exec, bin: string, path: string): Promise { + const pane = await paneAt(parsePanes(await exec(bin, ['pane', 'list'])), path) + if (!pane) { + await exec(bin, ['pane', 'split', '--cwd', path, '--direction', 'right', '--no-focus']) + return 'new-pane' + } + await exec(bin, ['workspace', 'focus', pane.workspace_id]) + await exec(bin, ['tab', 'focus', pane.tab_id]) + try { + return (await walkTo(exec, bin, pane.pane_id)) ? 'pane' : 'tab' + } catch { + return 'tab' + } +} + +/** The coding agents a project can be opened with: a closed list, and Herdr's own kind names. */ +export const AGENTS = ['claude', 'codex'] as const +export type Agent = (typeof AGENTS)[number] + +/** How long `agent start` may wait for the agent to be ready, and the CLI call around it. */ +const AGENT_START_MS = 30_000 + +/** + * Splits a new pane on the folder, focused, and starts a coding agent in it with Herdr's own + * `agent start`, which launches the agent of that kind and waits until it takes input. Never an + * existing pane: one already in the folder may be busy. The folder goes only as `--cwd`; the + * agent's name is generated, never derived from the folder. Herdr's `agent_not_ready` (the agent + * is up but waiting at a startup question, such as trusting the folder) is still a started agent. + */ +export async function startAgentInHerdr(exec: Exec, bin: string, path: string, agent: Agent, now: number = Date.now()): Promise<'started' | 'waiting'> { + const split = resultOf(await exec(bin, ['pane', 'split', '--cwd', path, '--direction', 'right', '--focus'])) + const paneId = (split?.pane as { pane_id?: unknown } | undefined)?.pane_id + if (typeof paneId !== 'string' || !/^[\w:-]{1,64}$/.test(paneId)) throw new Error('no-pane') + const name = `fremkit-${agent}-${now.toString(36)}` + try { + await exec(bin, ['agent', 'start', name, '--kind', agent, '--pane', paneId, '--timeout', String(AGENT_START_MS)], { timeoutMs: AGENT_START_MS + 5000 }) + return 'started' + } catch (err) { + if (/agent_not_ready/.test((err as Error).message)) return 'waiting' + throw err + } +} + +/** The terminal application a process path belongs to, from its bundle in the path. */ +function terminalOf(command: string): TerminalApp | null { + if (command.includes('/iTerm.app/') || command.includes('/iTerm2/iTermServer')) return 'iterm' + if (command.includes('/Terminal.app/')) return 'terminal' + if (command.includes('/Ghostty.app/')) return 'ghostty' + return null +} + +/** + * The terminal Herdr's client runs in, found by walking each `herdr` process's parents in one + * `ps` listing up to a terminal's bundle. Null when none is found or when Herdr runs in two + * different terminals: guessing would bring the wrong one forward. + */ +export async function detectHerdrTerminal(exec: Exec): Promise { + const parent = new Map() + const command = new Map() + for (const line of (await exec(PS, ['-axo', 'pid=,ppid=,comm='])).split('\n')) { + const m = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line) + if (!m) continue + parent.set(Number(m[1]), Number(m[2])) + command.set(Number(m[1]), m[3].trim()) + } + const found = new Set() + for (const [pid, cmd] of command) { + if (cmd !== 'herdr' && !cmd.endsWith('/herdr')) continue + let at: number | undefined = parent.get(pid) + for (let hops = 0; at && at > 1 && hops < 20; hops++, at = parent.get(at)) { + const app = terminalOf(command.get(at) ?? '') + if (app) { + found.add(app) + break + } + } + } + return found.size === 1 ? [...found][0] : null +} diff --git a/server/src/providers/recent-projects/index.ts b/server/src/providers/recent-projects/index.ts new file mode 100644 index 00000000..81d9706f --- /dev/null +++ b/server/src/providers/recent-projects/index.ts @@ -0,0 +1,331 @@ +import { homedir } from 'node:os' +import { z } from 'zod' +import type { InstanceView } from '../../config/instances.js' +import { execCommand, type Exec } from '../exec.js' +import type { CommandContext, Provider } from '../types.js' +import { APP_IDS, installedApps, openWith, type AppId } from './apps.js' +import { HERDR_TERMINALS } from './herdr.js' +import { LIVE_MEMORY, MAX_OPENERS, MEMORY_FILE, loadState, saveMemory, serializeMemory, type LiveMemory, type Openers } from './memory.js' +import { suggestApp } from './suggest.js' +import { canonicalProject, projectName, shortParent } from './paths.js' +import { createClaudeSource } from './sources/claude.js' +import { createCliSources, resolveBinary as defaultResolveBinary, type ResolveBinary } from './sources/cli.js' +import { createCodexSource } from './sources/codex.js' +import { gitSource } from './sources/git.js' +import { createJetbrainsSource } from './sources/jetbrains.js' +import { createVscodeSource } from './sources/vscode.js' +import { SOURCE_IDS, type RecentProject, type Source, type SourceEntry, type SourceId, type SourceStatus } from './types.js' +import { exists, withTimeout } from './util.js' + +export { SOURCE_IDS, APP_IDS, MEMORY_FILE } +export type { RecentProject, SourceId, AppId } + +export const RECENT_PROJECTS_CHANNEL = 'recent-projects' +export const RECENT_PROJECTS_WIDGET = 'recent-projects' +/** Projects published, whatever a tile shows: a tile picks its own top rows from these. */ +export const MAX_PROJECTS = 50 +/** The longest one source may take before its last good answer is used instead. */ +const SOURCE_TIMEOUT_MS = 10_000 +/** How often the list of installed applications is looked at again. */ +const APPS_TTL_MS = 10 * 60_000 + +/** The sources a tile reads when its settings never said: git alone, every other one opt-in. */ +export const DEFAULT_SOURCES: readonly SourceId[] = ['git'] + +/** The settings key of one source's checkbox. */ +export function sourceKey(id: SourceId): string { + return 'source_' + id +} + +/** What one tile asked for: the sources it ticked and the git roots it typed. */ +export function tileWants(settings: Record): { sources: Set; gitRoots: string[]; suggest: boolean } { + const sources = new Set() + for (const id of SOURCE_IDS) { + const v = settings[sourceKey(id)] + if (v === true || (v === undefined && DEFAULT_SOURCES.includes(id))) sources.add(id) + } + const gitRoots: string[] = [] + if (Array.isArray(settings.gitRoots)) { + for (const item of settings.gitRoots) { + const p = typeof item === 'string' ? item : (item as { path?: unknown })?.path + if (typeof p === 'string' && p.trim() && p.length <= 1024) gitRoots.push(p.trim()) + } + } + return { sources, gitRoots, suggest: settings.suggestApp !== false } +} + +/** Every shown tile's wishes merged: a source is read when one tile wants it, never otherwise. */ +export function mergedWants(instances: InstanceView[]): { sources: Set; gitRoots: string[]; suggest: boolean } { + const sources = new Set() + const roots = new Set() + let suggest = false + for (const i of instances) { + const w = tileWants(i.settings) + w.sources.forEach((s) => sources.add(s)) + w.gitRoots.forEach((r) => roots.add(r)) + suggest ||= w.suggest + } + return { sources, gitRoots: [...roots].slice(0, 20), suggest } +} + +interface Tagged extends SourceEntry { + source: SourceId +} + +/** + * The entries of every source as one list: each path made canonical (and dropped when it does + * not exist or sits outside the home folder and the volumes), one row per folder with the newest + * date any source gave it and every source that named it, newest first, at most `MAX_PROJECTS`. + * A source with no date sorts after every dated row, in its own order. + */ +export async function mergeEntries(entries: Tagged[], home: string): Promise { + const canonical = new Map>() + const byPath = new Map() + for (const e of entries) { + if (!canonical.has(e.path)) canonical.set(e.path, canonicalProject(e.path, home)) + const path = await canonical.get(e.path)! + if (!path) continue + let row = byPath.get(path) + if (!row) { + row = { path, name: projectName(path), parent: shortParent(path, home), seenAt: null, sources: [] } + byPath.set(path, row) + } + if (e.seenAt !== null && (row.seenAt === null || e.seenAt > row.seenAt)) row.seenAt = e.seenAt + if (!row.sources.includes(e.source)) row.sources.push(e.source) + if (e.gitRoot) { + row.gitRoots ??= [] + if (!row.gitRoots.includes(e.gitRoot)) row.gitRoots.push(e.gitRoot) + } + } + const rows = [...byPath.values()] + rows.forEach((r) => r.sources.sort((a, b) => SOURCE_IDS.indexOf(a) - SOURCE_IDS.indexOf(b))) + return rows + .map((r, i) => ({ r, i })) + .sort((a, b) => (b.r.seenAt ?? -Infinity) - (a.r.seenAt ?? -Infinity) || a.i - b.i) + .map(({ r }) => r) + .slice(0, MAX_PROJECTS) +} + +export interface RecentProjectsSnapshot { + projects: RecentProject[] + sources: SourceStatus[] + /** The applications a project can be opened with on this Mac. */ + apps: AppId[] + updatedAt: number +} + +export interface RecentProjectsOptions { + /** Every shown tile of the widget, with its saved settings. */ + instances: () => InstanceView[] + home?: string + sources?: Source[] + exec?: Exec + resolveBinary?: ResolveBinary + appExists?: (path: string) => Promise + now?: () => number + /** + * Where what the live sources (tmux, Herdr) showed is kept across restarts, in the data + * folder; without one it lives in memory only. Paths and dates, nothing else. + */ + memoryFile?: string + /** Something a command changed (a project's opener) should be published now, not at the next tick. */ + onChange?: () => void +} + +export const SetOpenerSchema = z.object({ + path: z.string().min(1).max(4096), + /** null clears it: a tap opens the project with the tile's choice (or the suggestion) again. */ + app: z.enum(APP_IDS).nullable(), +}) + +export const OpenSchema = z.object({ + path: z.string().min(1).max(4096), + app: z.enum(APP_IDS), + /** The terminal to bring forward after Herdr has the folder: the tile's setting. */ + terminal: z.enum(HERDR_TERMINALS).optional(), +}) + +export function defaultSources(exec: Exec, resolve: ResolveBinary, now: () => number): Source[] { + return [ + gitSource, + createClaudeSource(), + createCodexSource(), + createVscodeSource('vscode', { fr: 'VS Code', en: 'VS Code' }, 'Code', exec), + createVscodeSource('cursor', { fr: 'Cursor', en: 'Cursor' }, 'Cursor', exec), + createJetbrainsSource(), + ...createCliSources(exec, resolve, now), + ] +} + +/** + * The `recent-projects` channel: the folders worked in lately, gathered from the sources the + * shown tiles ticked (git repositories under chosen roots, Claude Code, Codex, VS Code, Cursor, + * JetBrains IDEs, zoxide, tmux, Herdr), and one command to open one of them. + * + * Only paths and dates are read: folder names, modification times, a recent list, the first + * line of a Codex session — never a transcript, a pane's contents or a file inside a project. + * A source that fails keeps its last good answer and reports its error beside it, so one broken + * tool never empties the list. + */ +export function createRecentProjectsProvider(opts: RecentProjectsOptions): Provider & { snapshot(): RecentProjectsSnapshot | null } { + const home = opts.home ?? homedir() + const now = opts.now ?? Date.now + const exec = opts.exec ?? execCommand + const resolve = opts.resolveBinary ?? defaultResolveBinary + const sources = opts.sources ?? defaultSources(exec, resolve, now) + const appDeps = { exec, resolveBinary: resolve, exists: opts.appExists } + const lastGood = new Map() + let memory: LiveMemory = new Map() + let openers: Openers = new Map() + let loaded: Promise | null = null + let saved = '' + let saving: Promise = Promise.resolve() + let apps: { list: AppId[]; at: number } | null = null + let last: RecentProjectsSnapshot | null = null + + function remember(id: SourceId, entries: SourceEntry[]): SourceEntry[] { + const seen = memory.get(id) ?? new Map() + memory.set(id, seen) + for (const e of entries) { + const before = seen.get(e.path) + seen.delete(e.path) + seen.set(e.path, before != null && e.seenAt != null ? Math.max(before, e.seenAt) : e.seenAt ?? before ?? null) + } + while (seen.size > LIVE_MEMORY) seen.delete(seen.keys().next().value!) + return remembered(id) + } + + function remembered(id: SourceId): SourceEntry[] { + return [...(memory.get(id) ?? [])].map(([path, seenAt]) => ({ path, seenAt })) + } + + /** Loads the saved memory once, before the first poll uses it. */ + function load(): Promise { + loaded ??= opts.memoryFile + ? loadState(opts.memoryFile).then((s) => { memory = s.live; openers = s.openers; saved = serializeMemory(memory, openers) }) + : Promise.resolve() + return loaded + } + + /** Writes the memory when it changed, one write at a time; a failed write is tried at the next poll. */ + function persist(): Promise { + const file = opts.memoryFile + if (!file) return saving + const text = serializeMemory(memory, openers) + if (text === saved) return saving + saving = saving.then(() => saveMemory(file, text)).then(() => { saved = text }, () => undefined) + return saving + } + + async function poll(): Promise { + await load() + const wants = mergedWants(opts.instances()) + const ctx = { home, gitRoots: wants.gitRoots } + const statuses: SourceStatus[] = [] + const tagged: Tagged[] = [] + await Promise.all(sources.map(async (source) => { + const enabled = wants.sources.has(source.id) + const status: SourceStatus = { id: source.id, enabled, available: false, count: 0 } + statuses.push(status) + if (!enabled) return + status.available = await source.available(ctx).catch(() => false) + if (!status.available) { + lastGood.delete(source.id) + return + } + let entries: SourceEntry[] + try { + entries = await withTimeout(source.list(ctx), SOURCE_TIMEOUT_MS) + if (source.live) entries = remember(source.id, entries) + lastGood.set(source.id, entries) + } catch (err) { + status.error = (err as Error).message === 'timeout' ? 'timeout' : 'unreadable' + entries = lastGood.get(source.id) ?? (source.live ? remembered(source.id) : []) + } + for (const e of entries) tagged.push({ ...e, source: source.id }) + })) + // A project's own application is forgotten once its folder is gone. + for (const path of [...openers.keys()]) if (!(await exists(path))) openers.delete(path) + await persist() + statuses.sort((a, b) => SOURCE_IDS.indexOf(a.id) - SOURCE_IDS.indexOf(b.id)) + const projects = await mergeEntries(tagged, home) + for (const s of statuses) s.count = projects.filter((p) => p.sources.includes(s.id)).length + if (!apps || now() - apps.at > APPS_TTL_MS) apps = { list: await installedApps(appDeps), at: now() } + const installed = apps.list + await Promise.all(projects.map(async (p) => { + const opener = openers.get(p.path) + if (opener) p.opener = opener + else if (wants.suggest) { + const suggested = await suggestApp(p.path, installed) + if (suggested) p.suggested = suggested + } + })) + last = { projects, sources: statuses, apps: installed, updatedAt: now() } + return last + } + + return { + channel: RECENT_PROJECTS_CHANNEL, + intervalMs: 60_000, + poll, + snapshot: () => last, + commands: { + /** + * Opens one listed folder with one application. Local only: it starts a program on this + * Mac, and the paths are this Mac's — a paired device is refused like any remote caller. + * The path must be one the last snapshot listed, and still be that folder. One opened in + * Herdr or tmux is remembered as that source's, agent launches included. + */ + async open(payload: unknown, ctx?: CommandContext) { + if (ctx?.loopback !== true || ctx.paired) return { ok: false, error: 'local-only' } + const parsed = OpenSchema.safeParse(payload) + if (!parsed.success) return { ok: false, error: 'invalid-request' } + const { path, app, terminal } = parsed.data + if (!last?.projects.some((p) => p.path === path)) return { ok: false, error: 'unknown-project' } + if ((await canonicalProject(path, home)) !== path) return { ok: false, error: 'unknown-project' } + let result + try { + result = await openWith(app, path, appDeps, { terminal }) + } catch { + return { ok: false, error: 'failed' } + } + // A folder opened in a pane is one that pane's source would have shown: remember it there, + // so it stays listed once the pane (or the agent in it) is closed. + const mux = app === 'herdr' || app.startsWith('herdr-') ? 'herdr' : app === 'tmux' || app.startsWith('tmux-') ? 'tmux' : null + if (result.ok && mux) { + remember(mux, [{ path, seenAt: now() }]) + await persist() + } + return result + }, + + /** + * Gives one listed project an application a tap opens it with, whatever the tile's choice, + * or (`app: null`) takes it back. Kept in the data folder's `recent-projects.json`, never in + * the config: shared by every tile, and no project path ever reaches a backup. Local only, + * like `open`; the application must be one this Mac has. + */ + async setOpener(payload: unknown, ctx?: CommandContext) { + if (ctx?.loopback !== true || ctx.paired) return { ok: false, error: 'local-only' } + const parsed = SetOpenerSchema.safeParse(payload) + if (!parsed.success) return { ok: false, error: 'invalid-request' } + const { path, app } = parsed.data + if (!last?.projects.some((p) => p.path === path)) return { ok: false, error: 'unknown-project' } + if ((await canonicalProject(path, home)) !== path) return { ok: false, error: 'unknown-project' } + if (app !== null && !last.apps.includes(app)) return { ok: false, error: 'not-installed' } + openers.delete(path) + if (app !== null) openers.set(path, app) + while (openers.size > MAX_OPENERS) openers.delete(openers.keys().next().value!) + await persist() + // The next snapshot carries it; until then the one in hand says so too. + for (const p of last.projects) { + if (p.path !== path) continue + if (app) p.opener = app + else delete p.opener + } + opts.onChange?.() + return { ok: true } + }, + }, + } +} diff --git a/server/src/providers/recent-projects/memory.ts b/server/src/providers/recent-projects/memory.ts new file mode 100644 index 00000000..0b79eb22 --- /dev/null +++ b/server/src/providers/recent-projects/memory.ts @@ -0,0 +1,95 @@ +import { readFile, rename, writeFile } from 'node:fs/promises' +import { z } from 'zod' +import { APP_IDS, type AppId } from './apps.js' +import type { SourceId } from './types.js' + +/** + * The file, in the data folder, that keeps what the live sources showed and the application each + * project was told to open with, across restarts. Project paths live here and nowhere in the + * config, so they never reach a backup, the config history, a shared layout or the diagnostics. + */ +export const MEMORY_FILE = 'recent-projects.json' +/** Folders a live source (a terminal pane) is remembered for, per source. */ +export const LIVE_MEMORY = 50 +/** The sources that show only what is open now, and so are remembered. */ +export const LIVE_SOURCES = ['tmux', 'herdr'] as const satisfies readonly SourceId[] + +/** Projects given an application of their own, at most; the least recently set go first. */ +export const MAX_OPENERS = 200 + +/** Folder → the application a tap opens it with, oldest set first. */ +export type Openers = Map + +/** Per live source, folder → last time it was seen (null when the source gave no date), oldest first. */ +export type LiveMemory = Map> + +const Entry = z.object({ path: z.string().startsWith('/').max(4096), seenAt: z.number().nullable() }) +const Opener = z.object({ path: Entry.shape.path, app: z.enum(APP_IDS) }) +const FileSchema = z.object({ + version: z.literal(1), + sources: z.record(z.string(), z.array(z.unknown())), + openers: z.array(z.unknown()).optional(), +}) + +/** The file's two parts, as kept in memory. */ +export interface SavedState { + live: LiveMemory + openers: Openers +} + +/** + * What `saveMemory` wrote, or an empty state when the file is missing, unreadable or not one of + * ours: it is a convenience, never a reason not to start. Entries that do not check are dropped one + * by one; each live source keeps its newest `LIVE_MEMORY`, the openers their newest `MAX_OPENERS`. + */ +export async function loadState(file: string): Promise { + const state: SavedState = { live: new Map(), openers: new Map() } + let parsed + try { + parsed = FileSchema.safeParse(JSON.parse(await readFile(file, 'utf8'))) + } catch { + return state + } + if (!parsed.success) return state + for (const id of LIVE_SOURCES) { + const seen = new Map() + for (const raw of parsed.data.sources[id] ?? []) { + const e = Entry.safeParse(raw) + if (e.success) seen.set(e.data.path, e.data.seenAt) + } + while (seen.size > LIVE_MEMORY) seen.delete(seen.keys().next().value!) + if (seen.size) state.live.set(id, seen) + } + for (const raw of parsed.data.openers ?? []) { + const o = Opener.safeParse(raw) + if (!o.success) continue + state.openers.delete(o.data.path) + state.openers.set(o.data.path, o.data.app) + } + while (state.openers.size > MAX_OPENERS) state.openers.delete(state.openers.keys().next().value!) + return state +} + +/** The live sources' part of the file alone. */ +export async function loadMemory(file: string): Promise { + return (await loadState(file)).live +} + +/** The file's text: paths and dates for the live sources, paths and application ids for the openers. */ +export function serializeMemory(memory: LiveMemory, openers: Openers = new Map()): string { + const sources: Record = {} + for (const id of LIVE_SOURCES) { + const seen = memory.get(id) + if (seen?.size) sources[id] = [...seen].slice(-LIVE_MEMORY).map(([path, seenAt]) => ({ path, seenAt })) + } + const out: Record = { version: 1, sources } + if (openers.size) out.openers = [...openers].slice(-MAX_OPENERS).map(([path, app]) => ({ path, app })) + return JSON.stringify(out) + '\n' +} + +/** Writes the memory beside the config: owner-only, through a temporary file and a rename. */ +export async function saveMemory(file: string, text: string): Promise { + const tmp = `${file}.tmp` + await writeFile(tmp, text, { encoding: 'utf8', mode: 0o600 }) + await rename(tmp, file) +} diff --git a/server/src/providers/recent-projects/paths.ts b/server/src/providers/recent-projects/paths.ts new file mode 100644 index 00000000..910c1c3a --- /dev/null +++ b/server/src/providers/recent-projects/paths.ts @@ -0,0 +1,72 @@ +import { realpath, stat } from 'node:fs/promises' +import { basename, dirname, isAbsolute, join, sep } from 'node:path' + +/** + * Where a project may live: inside the home folder, or on another volume (`/Volumes//…`, + * where many developers keep their code). Everything else — `/`, `/tmp`, `/var/folders` (the + * throwaway worktrees tools create there), `/Applications`, the system — is never listed, so it + * can never be opened either. The home folder itself, its `Library` and a bare volume root are + * not projects. + */ +export function isAllowedProject(path: string, home: string): boolean { + if (!isAbsolute(path)) return false + const parts = path.split(sep) + if (parts.some((p) => p === 'node_modules' || p === '.Trash' || p === '.git')) return false + if (path.startsWith(home + sep)) { + const rest = path.slice(home.length + 1) + return rest !== '' && rest !== 'Library' && !rest.startsWith('Library' + sep) + } + // ['', 'Volumes', '', '', …] + return parts[1] === 'Volumes' && parts.length >= 4 && parts[2] !== '' && parts[3] !== '' +} + +/** + * The canonical form of a folder a source reported: symlinks resolved, required to exist, to be + * a directory and to sit where `isAllowedProject` allows. Null for anything else. + */ +export async function canonicalProject(path: string, home: string): Promise { + if (typeof path !== 'string' || !isAbsolute(path) || path.length > 4096) return null + try { + const real = await realpath(path) + if (!isAllowedProject(real, home)) return null + return (await stat(real)).isDirectory() ? real : null + } catch { + return null + } +} + +/** + * Where a git root may be: the home folder or anything under it, or a volume and anything on it. + * Wider than a project (a root is where the walk starts, not something opened), still never the + * system. + */ +export async function canonicalRoot(path: string, home: string): Promise { + if (typeof path !== 'string' || !isAbsolute(path) || path.length > 4096) return null + try { + const real = await realpath(path) + const parts = real.split(sep) + const allowed = real === home || real.startsWith(home + sep) || (parts[1] === 'Volumes' && parts.length >= 3 && parts[2] !== '') + return allowed && (await stat(real)).isDirectory() ? real : null + } catch { + return null + } +} + +/** `~/Dev/x` → `/Users/me/Dev/x`; anything else unchanged. */ +export function expandHome(path: string, home: string): string { + if (path === '~') return home + if (path.startsWith('~/')) return join(home, path.slice(2)) + return path +} + +/** The parent folder as the widget shows it: `~/Dev`, `/Volumes/Dev/clients`. */ +export function shortParent(path: string, home: string): string { + const parent = dirname(path) + if (parent === home) return '~' + if (parent.startsWith(home + sep)) return '~' + parent.slice(home.length) + return parent +} + +export function projectName(path: string): string { + return basename(path) || path +} diff --git a/server/src/providers/recent-projects/sources/claude.ts b/server/src/providers/recent-projects/sources/claude.ts new file mode 100644 index 00000000..54cbb6db --- /dev/null +++ b/server/src/providers/recent-projects/sources/claude.ts @@ -0,0 +1,98 @@ +import { readdir, stat } from 'node:fs/promises' +import { join, sep } from 'node:path' +import type { Source, SourceEntry } from '../types.js' +import { exists } from '../util.js' + +/** How Claude Code names a project's folder: every character but letters and digits becomes `-`. */ +export function encodeClaudeName(name: string): string { + return name.replace(/[^A-Za-z0-9]/g, '-') +} + +/** Folders read while decoding one name, past which it is given up. */ +const MAX_READS = 200 + +/** + * The path a `~/.claude/projects/` folder stands for. + * + * The encoding is lossy — `/`, `.`, `_`, `-` and spaces all became `-` — so it is decoded against + * the disk: from `/`, each child folder whose encoded name matches the next stretch of the name + * is tried, longest first, until the whole name is used. The first folder that exists wins; a + * project whose folder is gone decodes to null. Only folder names are read. + */ +export async function decodeClaudeName(encoded: string, root: string = sep): Promise { + let reads = 0 + async function walk(dir: string, rest: string): Promise { + if (rest === '') return dir + if (reads++ >= MAX_READS) return null + let names: string[] + try { + const entries = await readdir(dir, { withFileTypes: true }) + names = entries.filter((e) => e.isDirectory() || e.isSymbolicLink()).map((e) => e.name) + } catch { + return null + } + const candidates = names + .map((name) => ({ name, enc: '-' + encodeClaudeName(name) })) + .filter(({ enc }) => rest === enc || (rest.startsWith(enc) && rest[enc.length] === '-')) + .sort((a, b) => b.enc.length - a.enc.length) + for (const c of candidates) { + const found = await walk(join(dir, c.name), rest.slice(c.enc.length)) + if (found) return found + } + return null + } + if (!encoded.startsWith('-')) return null + return walk(root, encoded) +} + +/** The newest modification time among a folder's files: when the project was last talked to. */ +async function newestInside(dir: string): Promise { + let names: string[] + try { + names = await readdir(dir) + } catch { + return null + } + let newest: number | null = null + for (const name of names.slice(0, 500)) { + try { + const t = (await stat(join(dir, name))).mtimeMs + if (newest === null || t > newest) newest = t + } catch { /* removed meanwhile */ } + } + return newest +} + +const RETRY_MS = 10 * 60_000 + +export function createClaudeSource(opts: { projectsDir?: (home: string) => string; root?: string } = {}): Source { + const dirOf = opts.projectsDir ?? ((home: string) => join(home, '.claude', 'projects')) + /** + * Decoding reads folders: a name's answer is kept while the folder it named still exists, and a + * name that decoded to nothing is tried again ten minutes later. + */ + const decoded = new Map() + return { + id: 'claude', + label: { fr: 'Claude Code', en: 'Claude Code' }, + available: async (ctx) => exists(dirOf(ctx.home)), + async list(ctx) { + const base = dirOf(ctx.home) + const names = (await readdir(base, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name) + const out: SourceEntry[] = [] + for (const name of names) { + const known = decoded.get(name) + let path = known?.path ?? null + const stale = !known || (known.path === null ? Date.now() - known.at > RETRY_MS : !(await exists(known.path))) + if (stale) { + path = await decodeClaudeName(name, opts.root) + decoded.set(name, { path, at: Date.now() }) + } + if (!path) continue + // Only modification times: no transcript is ever opened. + out.push({ path, seenAt: await newestInside(join(base, name)) }) + } + return out + }, + } +} diff --git a/server/src/providers/recent-projects/sources/cli.ts b/server/src/providers/recent-projects/sources/cli.ts new file mode 100644 index 00000000..6577b293 --- /dev/null +++ b/server/src/providers/recent-projects/sources/cli.ts @@ -0,0 +1,110 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' +import type { Exec } from '../../exec.js' +import type { Source, SourceEntry } from '../types.js' +import { isExecutableFile } from '../util.js' + +/** + * Where a command-line tool is looked for, by absolute path and never through `PATH`: Homebrew on + * Apple silicon and Intel, cargo, and `~/.local/bin` (where installers like Herdr's put it), plus + * `~/.claude/local` for Claude Code. + */ +export function binaryCandidates(name: string, home: string): string[] { + const dirs = ['/opt/homebrew/bin', '/usr/local/bin', join(home, '.cargo', 'bin'), join(home, '.local', 'bin')].map((d) => join(d, name)) + // Claude Code's own installer puts it here. + if (name === 'claude') dirs.push(join(home, '.claude', 'local', 'claude')) + return dirs +} + +export type ResolveBinary = (name: 'zoxide' | 'tmux' | 'herdr' | 'claude' | 'codex') => Promise + +export const resolveBinary: ResolveBinary = async (name) => { + for (const candidate of binaryCandidates(name, homedir())) { + if (await isExecutableFile(candidate)) return candidate + } + return null +} + +/** `zoxide query --list --score`: ` 12.5 /path` per line, best first. zoxide keeps no date. */ +export function parseZoxide(stdout: string): SourceEntry[] { + const out: SourceEntry[] = [] + for (const line of stdout.split('\n')) { + const m = /^\s*[\d.]+\s+(\/.*)$/.exec(line) + if (m) out.push({ path: m[1], seenAt: null }) + } + return out.slice(0, 50) +} + +/** `tmux list-panes -a -F '#{pane_current_path}\t#{window_activity}'`, activity in seconds. */ +export function parseTmux(stdout: string): SourceEntry[] { + const out: SourceEntry[] = [] + for (const line of stdout.split('\n')) { + const [path, activity] = line.split('\t') + if (!path?.startsWith('/')) continue + const seconds = Number(activity) + out.push({ path, seenAt: Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null }) + } + return out +} + +/** + * `herdr pane list`: a JSON envelope `{ result: { panes: [...] } }`. Each pane's folder is its + * foreground process's (`foreground_cwd`), else the shell's (`cwd`). Nothing else of a pane — + * its title, its scrollback — is read. + */ +export function parseHerdrPanes(stdout: string, now: number): SourceEntry[] { + let data: unknown + try { + data = JSON.parse(stdout) + } catch { + return [] + } + const root = data as { result?: { panes?: unknown }; panes?: unknown } + const panes = root.result?.panes ?? root.panes + if (!Array.isArray(panes)) return [] + const out: SourceEntry[] = [] + for (const pane of panes) { + const p = pane as { cwd?: unknown; foreground_cwd?: unknown } + const path = typeof p.foreground_cwd === 'string' && p.foreground_cwd ? p.foreground_cwd : p.cwd + if (typeof path === 'string' && path.startsWith('/')) out.push({ path, seenAt: now }) + } + return out +} + +/** A source backed by one command-line tool: unavailable, not failing, when it is not installed. */ +function cliSource( + id: 'zoxide' | 'tmux' | 'herdr', + label: { fr: string; en: string }, + args: string[], + parse: (stdout: string) => SourceEntry[], + exec: Exec, + resolve: ResolveBinary, + opts: { live?: boolean; emptyWhen?: RegExp } = {}, +): Source { + return { + id, + label, + live: opts.live, + available: async () => (await resolve(id)) !== null, + async list() { + const bin = await resolve(id) + if (!bin) return [] + try { + return parse(await exec(bin, args)) + } catch (err) { + // tmux with no server running is an empty list, not a failure. + if (opts.emptyWhen && opts.emptyWhen.test((err as Error).message)) return [] + throw err + } + }, + } +} + +export function createCliSources(exec: Exec, resolve: ResolveBinary = resolveBinary, now: () => number = Date.now): Source[] { + return [ + cliSource('zoxide', { fr: 'zoxide', en: 'zoxide' }, ['query', '--list', '--score'], parseZoxide, exec, resolve), + cliSource('tmux', { fr: 'tmux', en: 'tmux' }, ['list-panes', '-a', '-F', '#{pane_current_path}\t#{window_activity}'], parseTmux, exec, resolve, + { live: true, emptyWhen: /no server running|error connecting/i }), + cliSource('herdr', { fr: 'Herdr', en: 'Herdr' }, ['pane', 'list'], (s) => parseHerdrPanes(s, now()), exec, resolve, { live: true }), + ] +} diff --git a/server/src/providers/recent-projects/sources/codex.ts b/server/src/providers/recent-projects/sources/codex.ts new file mode 100644 index 00000000..6e356940 --- /dev/null +++ b/server/src/providers/recent-projects/sources/codex.ts @@ -0,0 +1,76 @@ +import { constants } from 'node:fs' +import { open, readdir, stat } from 'node:fs/promises' +import { join } from 'node:path' +import type { Source, SourceEntry } from '../types.js' +import { exists } from '../util.js' + +/** Session files looked at per poll, newest days first. */ +const MAX_FILES = 150 +/** The first line of a session (its `session_meta`) is read up to this many bytes, never further. */ +const HEAD_BYTES = 128 * 1024 + +/** + * The working folder a Codex session file records on its first line, or null. + * + * Only that line is read: `{"type":"session_meta","payload":{"cwd":…}}` in current versions, + * a bare `{"cwd":…}` in older ones. The conversation that follows is never read. + */ +export async function sessionCwd(file: string): Promise { + let handle: Awaited> | undefined + try { + handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW) + const buffer = Buffer.alloc(HEAD_BYTES) + const { bytesRead } = await handle.read(buffer, 0, HEAD_BYTES, 0) + const end = buffer.subarray(0, bytesRead).indexOf(10) + if (end < 0) return null + const first = JSON.parse(buffer.subarray(0, end).toString('utf8')) as Record + const payload = (first.payload && typeof first.payload === 'object' ? first.payload : first) as Record + return typeof payload.cwd === 'string' ? payload.cwd : null + } catch { + return null + } finally { + await handle?.close() + } +} + +async function childrenDesc(dir: string): Promise { + try { + return (await readdir(dir)).sort().reverse() + } catch { + return [] + } +} + +export function createCodexSource(opts: { sessionsDir?: (home: string) => string } = {}): Source { + const dirOf = opts.sessionsDir ?? ((home: string) => join(process.env.CODEX_HOME || join(home, '.codex'), 'sessions')) + return { + id: 'codex', + label: { fr: 'Codex', en: 'Codex' }, + available: async (ctx) => exists(dirOf(ctx.home)), + async list(ctx) { + // sessions/YYYY/MM/DD/rollout-….jsonl: walked newest first until enough files are found. + const base = dirOf(ctx.home) + const files: string[] = [] + outer: for (const y of await childrenDesc(base)) { + for (const m of await childrenDesc(join(base, y))) { + for (const d of await childrenDesc(join(base, y, m))) { + for (const f of await childrenDesc(join(base, y, m, d))) { + if (!f.endsWith('.jsonl')) continue + files.push(join(base, y, m, d, f)) + if (files.length >= MAX_FILES) break outer + } + } + } + } + const out: SourceEntry[] = [] + for (const file of files) { + const cwd = await sessionCwd(file) + if (!cwd) continue + try { + out.push({ path: cwd, seenAt: (await stat(file)).mtimeMs }) + } catch { /* removed meanwhile */ } + } + return out + }, + } +} diff --git a/server/src/providers/recent-projects/sources/git.ts b/server/src/providers/recent-projects/sources/git.ts new file mode 100644 index 00000000..5b00fa00 --- /dev/null +++ b/server/src/providers/recent-projects/sources/git.ts @@ -0,0 +1,92 @@ +import { readdir, readFile, stat } from 'node:fs/promises' +import { dirname, isAbsolute, join, resolve } from 'node:path' +import type { Source, SourceEntry } from '../types.js' +import { canonicalRoot, expandHome } from '../paths.js' +import { mtimeOf } from '../util.js' + +/** How far below a root a repository is looked for: `~/Dev/client/app` is depth 2. */ +export const GIT_MAX_DEPTH = 3 +/** Folders read per root before the walk gives up: a root set to the home folder stays cheap. */ +const MAX_DIRS_PER_ROOT = 4000 +/** Never walked into: dependencies, build output, caches, and the Mac's own folders. */ +const SKIP = new Set([ + 'node_modules', 'bower_components', 'vendor', 'Pods', 'DerivedData', 'build', 'dist', 'out', + 'target', 'bin', 'obj', 'venv', '__pycache__', 'Library', 'Applications', 'Movies', 'Music', + 'Pictures', 'Photos Library.photoslibrary', +]) + +/** + * When a repository was last touched, without running git: the newest of `HEAD` (a checkout, a + * commit on a branch switch) and `index` (any staging, any commit). A worktree's `.git` is a + * file naming its real git folder, which is followed. + */ +export async function repoTouchedAt(repo: string): Promise { + const dotGit = join(repo, '.git') + let gitDir = dotGit + try { + const info = await stat(dotGit) + if (info.isFile()) { + const m = /^gitdir:\s*(.+)\s*$/m.exec((await readFile(dotGit, 'utf8')).slice(0, 4096)) + if (!m) return info.mtimeMs + gitDir = isAbsolute(m[1]) ? m[1] : resolve(dirname(dotGit), m[1]) + } + } catch { + return null + } + const times = (await Promise.all([mtimeOf(join(gitDir, 'HEAD')), mtimeOf(join(gitDir, 'index'))])) + .filter((t): t is number => t !== null) + return times.length ? Math.max(...times) : null +} + +/** The repositories under one root, breadth first, at most `GIT_MAX_DEPTH` folders down. */ +export async function scanRoot(root: string): Promise { + const out: SourceEntry[] = [] + let queue: string[] = [root] + let read = 0 + for (let depth = 0; depth <= GIT_MAX_DEPTH && queue.length; depth++) { + const next: string[] = [] + for (const dir of queue) { + if (read++ >= MAX_DIRS_PER_ROOT) return out + let entries + try { + entries = await readdir(dir, { withFileTypes: true }) + } catch { + continue + } + if (entries.some((e) => e.name === '.git')) { + const at = await repoTouchedAt(dir) + if (at !== null) out.push({ path: dir, seenAt: at }) + // A repository's own folders are its business: nested checkouts are rare and costly. + continue + } + if (depth === GIT_MAX_DEPTH) continue + for (const e of entries) { + if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue + next.push(join(dir, e.name)) + } + } + queue = next + } + return out +} + +/** The roots as the walk takes them: `~` expanded, canonical, and allowed. */ +export async function resolveRoots(typed: string[], home: string): Promise<{ typed: string; real: string }[]> { + const out: { typed: string; real: string }[] = [] + for (const t of typed) { + const real = await canonicalRoot(expandHome(t.trim(), home), home) + if (real) out.push({ typed: t.trim(), real }) + } + return out +} + +export const gitSource: Source = { + id: 'git', + label: { fr: 'Dépôts git', en: 'Git repositories' }, + available: async () => true, + async list(ctx) { + const roots = await resolveRoots(ctx.gitRoots, ctx.home) + const lists = await Promise.all(roots.map(async (r) => (await scanRoot(r.real)).map((e) => ({ ...e, gitRoot: r.typed })))) + return lists.flat() + }, +} diff --git a/server/src/providers/recent-projects/sources/jetbrains.ts b/server/src/providers/recent-projects/sources/jetbrains.ts new file mode 100644 index 00000000..27205b08 --- /dev/null +++ b/server/src/providers/recent-projects/sources/jetbrains.ts @@ -0,0 +1,54 @@ +import { readdir, readFile, stat } from 'node:fs/promises' +import { dirname, join } from 'node:path' +import type { Source, SourceEntry } from '../types.js' +import { exists } from '../util.js' + +const FILES = ['recentProjects.xml', 'recentSolutions.xml'] + +function unescapeXml(s: string): string { + return s.replace(/"/g, '"').replace(/'/g, "'").replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&') +} + +/** + * The projects of one `recentProjects.xml` (IntelliJ, WebStorm, PyCharm…) or + * `recentSolutions.xml` (Rider), with the time each was last activated. Rider names a solution + * file: its folder is the project. `$USER_HOME$` is the IDEs' own spelling of the home folder. + */ +export function parseRecentProjects(xml: string, home: string): SourceEntry[] { + const out: SourceEntry[] = [] + const entry = /([\s\S]*?)<\/entry>/g + let m: RegExpExecArray | null + while ((m = entry.exec(xml))) { + let path = unescapeXml(m[1]).replace('$USER_HOME$', home) + if (/\.(sln|slnx|csproj|ipr)$/i.test(path)) path = dirname(path) + const ts = /name="activationTimestamp" value="(\d+)"/.exec(m[2]) ?? /name="projectOpenTimestamp" value="(\d+)"/.exec(m[2]) + out.push({ path, seenAt: ts ? Number(ts[1]) : null }) + } + return out +} + +export function createJetbrainsSource(): Source { + const base = (home: string) => join(home, 'Library', 'Application Support', 'JetBrains') + return { + id: 'jetbrains', + label: { fr: 'JetBrains', en: 'JetBrains' }, + available: async (ctx) => exists(base(ctx.home)), + async list(ctx) { + // One folder per product and version (IntelliJIdea2026.2, Rider2026.1…). Only those touched + // in the last year are read: a machine keeps every version it ever ran. + const root = base(ctx.home) + const yearAgo = Date.now() - 365 * 86_400_000 + const out: SourceEntry[] = [] + for (const product of await readdir(root)) { + for (const file of FILES) { + const path = join(root, product, 'options', file) + try { + if ((await stat(path)).mtimeMs < yearAgo) continue + out.push(...parseRecentProjects(await readFile(path, 'utf8'), ctx.home)) + } catch { /* no such file for this product */ } + } + } + return out + }, + } +} diff --git a/server/src/providers/recent-projects/sources/vscode.ts b/server/src/providers/recent-projects/sources/vscode.ts new file mode 100644 index 00000000..476696a0 --- /dev/null +++ b/server/src/providers/recent-projects/sources/vscode.ts @@ -0,0 +1,93 @@ +import { readdir, readFile, stat } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Exec } from '../../exec.js' +import type { Source, SourceEntry } from '../types.js' +import { exists } from '../util.js' + +const SQLITE = '/usr/bin/sqlite3' +const RECENT_KEY = 'history.recentlyOpenedPathsList' + +/** + * The folders of VS Code's "recently opened" list, most recent first. Files and remote + * workspaces (`vscode-remote://…`) are left out: only a local `file://` folder is a project here. + */ +export function parseRecentlyOpened(json: string): string[] { + let data: unknown + try { + data = JSON.parse(json) + } catch { + return [] + } + const entries = (data as { entries?: unknown }).entries + if (!Array.isArray(entries)) return [] + const out: string[] = [] + for (const e of entries) { + const uri = (e as { folderUri?: unknown })?.folderUri + if (typeof uri !== 'string' || !uri.startsWith('file://')) continue + try { + out.push(fileURLToPath(uri)) + } catch { /* not a local path */ } + } + return out +} + +/** + * When each folder was last opened, from `workspaceStorage//workspace.json` and the + * modification time of that folder's own state. The recent list has no dates; this has them for + * the folders the editor still keeps state for. + */ +async function workspaceDates(storage: string): Promise> { + const out = new Map() + let names: string[] + try { + names = await readdir(storage) + } catch { + return out + } + for (const name of names.slice(0, 500)) { + try { + const json = JSON.parse(await readFile(join(storage, name, 'workspace.json'), 'utf8')) as { folder?: unknown } + if (typeof json.folder !== 'string' || !json.folder.startsWith('file://')) continue + const dir = join(storage, name) + const at = Math.max((await stat(dir)).mtimeMs, await stat(join(dir, 'state.vscdb')).then((s) => s.mtimeMs, () => 0)) + out.set(fileURLToPath(json.folder), at) + } catch { /* no workspace.json, or not a folder */ } + } + return out +} + +/** + * VS Code and its forks (Cursor) keep the same files under their own Application Support folder. + * The recent list is read with the system's `sqlite3`, read-only, one key; a folder with no + * workspace date is placed just behind the one before it, which keeps the editor's order. + */ +export function createVscodeSource( + id: 'vscode' | 'cursor', + label: { fr: string; en: string }, + appSupportName: string, + exec: Exec, +): Source { + const userDir = (home: string) => join(home, 'Library', 'Application Support', appSupportName, 'User') + return { + id, + label, + available: async (ctx) => exists(join(userDir(ctx.home), 'globalStorage', 'state.vscdb')), + async list(ctx) { + const db = join(userDir(ctx.home), 'globalStorage', 'state.vscdb') + const [stdout, dates, dbStat] = await Promise.all([ + exec(SQLITE, ['-readonly', '-cmd', '.timeout 1000', db, `SELECT value FROM ItemTable WHERE key = '${RECENT_KEY}'`]), + workspaceDates(join(userDir(ctx.home), 'workspaceStorage')), + stat(db), + ]) + const out: SourceEntry[] = [] + let previous = dbStat.mtimeMs + for (const path of parseRecentlyOpened(stdout.trim())) { + const at = dates.get(path) ?? previous - 60_000 + out.push({ path, seenAt: at }) + previous = Math.min(previous, at) + } + return out + }, + } +} diff --git a/server/src/providers/recent-projects/suggest.ts b/server/src/providers/recent-projects/suggest.ts new file mode 100644 index 00000000..c207d3ff --- /dev/null +++ b/server/src/providers/recent-projects/suggest.ts @@ -0,0 +1,57 @@ +import { readdir } from 'node:fs/promises' +import { join } from 'node:path' +import type { AppId } from './apps.js' +import { exists } from './util.js' + +/** + * Which application a project's root suggests, from the NAMES of the entries at its top level: + * the first rule that matches and has an installed application wins. Never a file's contents, + * never a subfolder's listing. + */ +interface Rule { + matches: (names: Set, exts: Set) => boolean + /** Candidates in order of preference: the first installed one is suggested. */ + apps: AppId[] +} + +const has = (...wanted: string[]) => (names: Set) => wanted.some((n) => names.has(n)) +const GRADLE = ['build.gradle', 'build.gradle.kts', 'settings.gradle', 'settings.gradle.kts'] + +export const SUGGESTION_RULES: Rule[] = [ + { matches: (_n, e) => e.has('.sln') || e.has('.csproj') || e.has('.fsproj'), apps: ['jetbrains-rider'] }, + { matches: (n, e) => e.has('.xcodeproj') || e.has('.xcworkspace') || n.has('Package.swift'), apps: ['xcode'] }, + { matches: has('Cargo.toml'), apps: ['jetbrains-rustrover'] }, + { matches: has('go.mod'), apps: ['jetbrains-goland'] }, + { matches: has('pyproject.toml', 'requirements.txt'), apps: ['jetbrains-pycharm', 'jetbrains-pycharm-ce'] }, + { matches: has('composer.json'), apps: ['jetbrains-phpstorm'] }, + { matches: has('Gemfile'), apps: ['jetbrains-rubymine'] }, + { matches: has(...GRADLE, 'pom.xml'), apps: ['jetbrains-idea', 'jetbrains-idea-ce'] }, + { matches: has('CMakeLists.txt'), apps: ['jetbrains-clion'] }, +] + +/** An Android build, plainly: a manifest at the root, or the usual `app` module's one. */ +async function isAndroid(path: string, names: Set): Promise { + if (names.has('AndroidManifest.xml')) return true + if (!GRADLE.some((n) => names.has(n)) || !names.has('app')) return false + // One fixed path, checked for existence only: still no listing below the root. + return exists(join(path, 'app', 'src', 'main', 'AndroidManifest.xml')) +} + +/** The suggested application for one project, or null when its root names none installed. */ +export async function suggestApp(path: string, installed: readonly AppId[]): Promise { + let entries: string[] + try { + entries = await readdir(path) + } catch { + return null + } + const names = new Set(entries) + const exts = new Set(entries.map((n) => n.slice(n.lastIndexOf('.'))).filter((e) => e.length > 1)) + if (installed.includes('jetbrains-android-studio') && await isAndroid(path, names)) return 'jetbrains-android-studio' + for (const rule of SUGGESTION_RULES) { + if (!rule.matches(names, exts)) continue + const app = rule.apps.find((a) => installed.includes(a)) + if (app) return app + } + return null +} diff --git a/server/src/providers/recent-projects/types.ts b/server/src/providers/recent-projects/types.ts new file mode 100644 index 00000000..a743d173 --- /dev/null +++ b/server/src/providers/recent-projects/types.ts @@ -0,0 +1,63 @@ +import type { AppId } from './apps.js' + +/** Every source the provider knows, in the order the settings list them. */ +export const SOURCE_IDS = ['git', 'claude', 'codex', 'vscode', 'cursor', 'jetbrains', 'zoxide', 'tmux', 'herdr'] as const +export type SourceId = (typeof SOURCE_IDS)[number] + +/** One folder a source says was used, before it is canonicalised. */ +export interface SourceEntry { + path: string + /** Epoch milliseconds, or null when the source keeps an order but no date (zoxide). */ + seenAt: number | null + /** The git source only: the root, as typed, the repository was found under. */ + gitRoot?: string +} + +/** What a source is handed on each poll: the settings every shown instance asked for, merged. */ +export interface SourceContext { + home: string + /** Git roots as typed in the settings (`~/Dev`, `/Volumes/Dev`), one list for every instance. */ + gitRoots: string[] +} + +/** + * A place recent folders can be read from. `available` answers whether the program or file it + * reads is on this Mac at all, so a missing one is shown as such rather than as an error; `list` + * reads it, cheaply, and throws when it could not. + */ +export interface Source { + id: SourceId + label: { fr: string; en: string } + /** + * The source reports what is open now (terminal panes), not a history: the provider remembers + * what it saw, in memory, so a folder stays listed after its pane is closed. + */ + live?: boolean + available(ctx: SourceContext): Promise + list(ctx: SourceContext): Promise +} + +/** One project as the channel publishes it. */ +export interface RecentProject { + path: string + name: string + /** The parent folder, `~/` for the home folder. */ + parent: string + seenAt: number | null + sources: SourceId[] + /** For a repository the git source found: the roots (as typed) it sits under. */ + gitRoots?: string[] + /** The application this project was told to always open with (`setOpener`). */ + opener?: AppId + /** Without an opener: the application the names at the project's root suggest, if installed. */ + suggested?: AppId +} + +export interface SourceStatus { + id: SourceId + /** Asked for by at least one shown instance. Sources nobody asked for are never read. */ + enabled: boolean + available: boolean + count: number + error?: string +} diff --git a/server/src/providers/recent-projects/util.ts b/server/src/providers/recent-projects/util.ts new file mode 100644 index 00000000..e2225d8f --- /dev/null +++ b/server/src/providers/recent-projects/util.ts @@ -0,0 +1,40 @@ +import { access, stat } from 'node:fs/promises' +import { constants } from 'node:fs' +import { isAbsolute } from 'node:path' + +/** Rejects with `timeout` once `ms` have passed; the work itself is left to finish or fail. */ +export function withTimeout(work: Promise, ms: number): Promise { + let timer: NodeJS.Timeout | undefined + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('timeout')), ms) + }) + return Promise.race([work, deadline]).finally(() => clearTimeout(timer)) +} + +export async function exists(path: string): Promise { + try { + await stat(path) + return true + } catch { + return false + } +} + +/** The modification time of a file, or null when it is not there. */ +export async function mtimeOf(path: string): Promise { + try { + return (await stat(path)).mtimeMs + } catch { + return null + } +} + +export async function isExecutableFile(path: string): Promise { + if (!isAbsolute(path)) return false + try { + const [info] = await Promise.all([stat(path), access(path, constants.X_OK)]) + return info.isFile() + } catch { + return false + } +} diff --git a/server/src/widgets/manifest.ts b/server/src/widgets/manifest.ts index 792c4306..a83d9677 100644 --- a/server/src/widgets/manifest.ts +++ b/server/src/widgets/manifest.ts @@ -176,13 +176,14 @@ const ChannelSchema = z.string().min(1).refine((channel) => { * could read those and send them away, and its consent dialog would only have said "controls * disk-map". `clipboard` publishes a preview of every entry copied — secrets are masked, the * rest is whatever the user copied — and `copy` writes the pasteboard: the same reading, of - * something more personal still. `companion` carries what a browser tab is playing — its title, + * something more personal still. `recent-projects` lists the folders worked in lately, by full + * path, and opens them in an application. `companion` carries what a browser tab is playing — its title, * its site — and the offers that would let a widget watch it. These are refused in an installed * manifest — at install and when the catalogue reads `data/widgets` — and stay open to * `widgets/`, which ships with the server and is reviewed with it. Unlike `RESERVED_CHANNELS`, the * schema alone cannot say: it does not know where a manifest came from. */ -export const BUILTIN_ONLY_CHANNELS: ReadonlySet = new Set(['disk-map', 'clipboard', 'companion']) +export const BUILTIN_ONLY_CHANNELS: ReadonlySet = new Set(['disk-map', 'clipboard', 'recent-projects', 'companion']) /** * Channels any widget may read but only a built-in one may command. `brightness` changes the diff --git a/server/src/ws/hub.ts b/server/src/ws/hub.ts index 42aad7f7..75ece675 100644 --- a/server/src/ws/hub.ts +++ b/server/src/ws/hub.ts @@ -42,10 +42,11 @@ export const DEVICE_TERMINATE_MS = 2000 /** * Channels a paired device never reaches, whatever its screen holds. `companion` carries the * pairing code shown on the Edge, what a browser tab here is playing and the WebRTC offers to - * watch it: this Mac's dashboard only, in this first version. Matched by family, so a - * `companion:` is refused too. + * watch it: this Mac's dashboard only, in this first version. `recent-projects` names this Mac's + * folders by full path and opens them here: nothing a device across the room has a use for. + * Matched by family, so a `companion:` is refused too. */ -export const LOCAL_ONLY_CHANNELS: ReadonlySet = new Set(['companion']) +export const LOCAL_ONLY_CHANNELS: ReadonlySet = new Set(['companion', 'recent-projects']) function isLocalOnly(channel: string): boolean { return LOCAL_ONLY_CHANNELS.has(channel.split(':')[0]) diff --git a/server/test/backup.test.ts b/server/test/backup.test.ts index a83a8919..b04e796c 100644 --- a/server/test/backup.test.ts +++ b/server/test/backup.test.ts @@ -58,6 +58,14 @@ describe('GET /api/backup', () => { expect(names).toContain(`backgrounds/${DEFAULT_BACKGROUND}`) }) + it('leaves the runtime files of the data folder home', async () => { + await writeFile(join(dir, 'recent-projects.json'), JSON.stringify({ version: 1, sources: { herdr: [{ path: '/Users/demo/Dev/api', seenAt: 1 }] } })) + const res = await app.inject({ url: '/api/backup' }) + const entries = zipOf(res) + expect(entries.map((e) => e.name)).not.toContain('recent-projects.json') + expect(Buffer.concat(entries.map((e) => e.data)).toString('utf8')).not.toContain('/Users/demo/Dev/api') + }) + it('carries the live config, migrated, and no secret whatsoever', async () => { const res = await app.inject({ url: '/api/backup' }) const entries = zipOf(res) diff --git a/server/test/diagnostics.test.ts b/server/test/diagnostics.test.ts index 80234f67..e8885432 100644 --- a/server/test/diagnostics.test.ts +++ b/server/test/diagnostics.test.ts @@ -114,6 +114,23 @@ describe('buildDiagnostics', () => { expect(text).toContain('read ~/Library/x') }) + it('reports the ticked recent-projects sources by count, never by path', async () => { + const text = await buildDiagnostics(deps({ + recentProjects: () => [ + { id: 'git', enabled: true, available: true, count: 12 }, + { id: 'herdr', enabled: true, available: false, count: 0 }, + { id: 'claude', enabled: true, available: true, count: 3, error: 'timeout' }, + { id: 'zoxide', enabled: false, available: false, count: 0 }, + ], + })) + expect(text).toContain('### Recent projects sources') + expect(text).toContain('| git | yes | 12 | – |') + expect(text).toContain('| herdr | no | 0 | – |') + expect(text).toContain('| claude | yes | 3 | timeout |') + expect(text).not.toContain('| zoxide') + expect(await buildDiagnostics(deps())).not.toContain('Recent projects') + }) + it('says when there is no log', async () => { const text = await buildDiagnostics(deps({ log: undefined })) expect(text).toContain('### Server log\n\nNot available.') diff --git a/server/test/hub.test.ts b/server/test/hub.test.ts index fdcfaa11..77d82aa7 100644 --- a/server/test/hub.test.ts +++ b/server/test/hub.test.ts @@ -304,6 +304,21 @@ describe('a paired socket', () => { registry.stop() }) + it('refuses recent-projects to a paired socket even when its screen holds the widget', async () => { + const { hub, paired, registry, setPolicy } = pairedSetup() + const opened: unknown[] = [] + registry.register({ channel: 'recent-projects', intervalMs: 1000, commands: { open: async (p) => { opened.push(p); return { ok: true } } } }) + hub.broadcast('recent-projects', { projects: [{ path: '/Users/demo/Dev/example-api' }] }) + setPolicy({ 'dev-a': { subscriptions: ['recent-projects'], commands: ['recent-projects'] } }) + const socket = paired('dev-a') + socket.receive({ type: 'subscribe', channel: 'recent-projects' }) + socket.receive({ type: 'command', id: 'c1', channel: 'recent-projects', name: 'open', payload: { path: '/Users/demo/Dev/example-api', app: 'finder' } }) + await new Promise((r) => setTimeout(r, 0)) + expect(socket.sent).toEqual([REFUSED, { ...REFUSED, id: 'c1' }]) + expect(opened).toEqual([]) + registry.stop() + }) + it('is not heard once closed, even before the close handshake ends', async () => { const { hub, count, focused, attach, registry } = pairedSetup() const socket = attach(new LingeringSocket(), 'dev-a') diff --git a/server/test/recent-projects.test.ts b/server/test/recent-projects.test.ts new file mode 100644 index 00000000..9cddd575 --- /dev/null +++ b/server/test/recent-projects.test.ts @@ -0,0 +1,813 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { chmod, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, symlink, utimes, writeFile } from 'node:fs/promises' +import { homedir, tmpdir } from 'node:os' +import { join } from 'node:path' +import { + createRecentProjectsProvider, mergeEntries, mergedWants, tileWants, MAX_PROJECTS, + type RecentProjectsSnapshot, +} from '../src/providers/recent-projects/index.js' +import { canonicalProject, isAllowedProject, shortParent } from '../src/providers/recent-projects/paths.js' +import { repoTouchedAt, scanRoot, gitSource } from '../src/providers/recent-projects/sources/git.js' +import { createClaudeSource, decodeClaudeName, encodeClaudeName } from '../src/providers/recent-projects/sources/claude.js' +import { createCodexSource, sessionCwd } from '../src/providers/recent-projects/sources/codex.js' +import { createVscodeSource, parseRecentlyOpened } from '../src/providers/recent-projects/sources/vscode.js' +import { parseRecentProjects } from '../src/providers/recent-projects/sources/jetbrains.js' +import { binaryCandidates, createCliSources, parseHerdrPanes, parseTmux, parseZoxide } from '../src/providers/recent-projects/sources/cli.js' +import { installedApps, openWith } from '../src/providers/recent-projects/apps.js' +import { detectHerdrTerminal } from '../src/providers/recent-projects/herdr.js' +import { LIVE_MEMORY, MAX_OPENERS, loadMemory, loadState } from '../src/providers/recent-projects/memory.js' +import { suggestApp } from '../src/providers/recent-projects/suggest.js' +import type { AppId } from '../src/providers/recent-projects/apps.js' +import type { Source } from '../src/providers/recent-projects/types.js' +import { BUILTIN_ONLY_CHANNELS } from '../src/widgets/manifest.js' +import { LOCAL_ONLY_CHANNELS } from '../src/ws/hub.js' + +const LOCAL = { loopback: true, paired: false } +const T = (iso: string) => Date.parse(iso) + +/** A throwaway home folder, canonical (macOS puts tmpdir behind /var → /private/var). */ +let home = '' +beforeEach(async () => { home = await realpath(await mkdtemp(join(tmpdir(), 'fremkit-recent-'))) }) +afterEach(async () => { await rm(home, { recursive: true, force: true }) }) + +async function repo(path: string, at: string): Promise { + await mkdir(join(path, '.git'), { recursive: true }) + await writeFile(join(path, '.git', 'HEAD'), 'ref: refs/heads/main\n') + const d = new Date(at) + await utimes(join(path, '.git', 'HEAD'), d, d) +} + +describe('recent projects: paths', () => { + it('allows the home folder and the volumes, never the system, the home itself or its Library', () => { + expect(isAllowedProject('/Users/me/Dev/app', '/Users/me')).toBe(true) + expect(isAllowedProject('/Volumes/Dev/app', '/Users/me')).toBe(true) + expect(isAllowedProject('/Users/me', '/Users/me')).toBe(false) + expect(isAllowedProject('/Users/me/Library/Caches', '/Users/me')).toBe(false) + expect(isAllowedProject('/Volumes/Dev', '/Users/me')).toBe(false) + expect(isAllowedProject('/private/tmp/x', '/Users/me')).toBe(false) + expect(isAllowedProject('/Users/other/app', '/Users/me')).toBe(false) + expect(isAllowedProject('/Users/me/app/node_modules/x', '/Users/me')).toBe(false) + expect(isAllowedProject('relative/path', '/Users/me')).toBe(false) + }) + + it('canonicalises through symlinks and drops what is missing, a file, or escapes home', async () => { + await mkdir(join(home, 'Dev', 'app'), { recursive: true }) + await symlink(join(home, 'Dev', 'app'), join(home, 'link')) + await writeFile(join(home, 'file.txt'), 'x') + await symlink(tmpdir(), join(home, 'out')) + expect(await canonicalProject(join(home, 'link'), home)).toBe(join(home, 'Dev', 'app')) + expect(await canonicalProject(join(home, 'missing'), home)).toBeNull() + expect(await canonicalProject(join(home, 'file.txt'), home)).toBeNull() + expect(await canonicalProject(join(home, 'out'), home)).toBeNull() + }) + + it('shortens the parent folder under home', () => { + expect(shortParent('/Users/me/Dev/app', '/Users/me')).toBe('~/Dev') + expect(shortParent('/Users/me/app', '/Users/me')).toBe('~') + expect(shortParent('/Volumes/Dev/app', '/Users/me')).toBe('/Volumes/Dev') + }) +}) + +describe('recent projects: git source', () => { + it('finds repositories at most three folders down, skipping dependencies and hidden folders', async () => { + const root = join(home, 'Dev') + await repo(join(root, 'one'), '2026-10-01T10:00:00Z') + await repo(join(root, 'client', 'two'), '2026-10-02T10:00:00Z') + await repo(join(root, 'a', 'b', 'three'), '2026-10-03T10:00:00Z') + await repo(join(root, 'a', 'b', 'c', 'four'), '2026-10-04T10:00:00Z') + await repo(join(root, 'node_modules', 'dep'), '2026-10-05T10:00:00Z') + await repo(join(root, '.cache', 'hidden'), '2026-10-05T10:00:00Z') + await repo(join(root, 'one', 'nested'), '2026-10-05T10:00:00Z') + const found = await scanRoot(root) + expect(found.map((e) => e.path.slice(root.length)).sort()).toEqual(['/a/b/three', '/client/two', '/one']) + expect(found.find((e) => e.path.endsWith('/one'))?.seenAt).toBe(T('2026-10-01T10:00:00Z')) + }) + + it('dates a worktree through the git folder its .git file names, newest of HEAD and index', async () => { + const gitDir = join(home, 'main', '.git', 'worktrees', 'wt') + await mkdir(gitDir, { recursive: true }) + await writeFile(join(gitDir, 'HEAD'), 'ref\n') + await writeFile(join(gitDir, 'index'), 'x') + await utimes(join(gitDir, 'HEAD'), new Date('2026-09-01T00:00:00Z'), new Date('2026-09-01T00:00:00Z')) + await utimes(join(gitDir, 'index'), new Date('2026-09-02T00:00:00Z'), new Date('2026-09-02T00:00:00Z')) + await mkdir(join(home, 'wt')) + await writeFile(join(home, 'wt', '.git'), `gitdir: ${gitDir}\n`) + expect(await repoTouchedAt(join(home, 'wt'))).toBe(T('2026-09-02T00:00:00Z')) + }) + + it('walks the roots as typed, `~` included, and tags each repository with its root', async () => { + await repo(join(home, 'Dev', 'app'), '2026-10-01T10:00:00Z') + const entries = await gitSource.list({ home, gitRoots: ['~/Dev', '/nonexistent', '/System'] }) + expect(entries).toEqual([{ path: join(home, 'Dev', 'app'), seenAt: T('2026-10-01T10:00:00Z'), gitRoot: '~/Dev' }]) + }) +}) + +describe('recent projects: claude source', () => { + it('encodes like Claude Code and decodes against the disk, trying the lossy candidates', async () => { + await mkdir(join(home, 'Dev', 'my.site', 'api_v2'), { recursive: true }) + await mkdir(join(home, 'Dev', 'my'), { recursive: true }) // a decoy that leads nowhere + const encoded = encodeClaudeName(join(home, 'Dev', 'my.site', 'api_v2').slice(home.length)) + expect(encoded).toBe('-Dev-my-site-api-v2') + expect(await decodeClaudeName(encoded, home)).toBe(join(home, 'Dev', 'my.site', 'api_v2')) + expect(await decodeClaudeName('-Dev-gone', home)).toBeNull() + }) + + it('dates a project by the newest file inside, and never opens a transcript', async () => { + await mkdir(join(home, 'Dev', 'app'), { recursive: true }) + const projects = join(home, 'claude-projects') + const folder = join(projects, '-Dev-app') + await mkdir(folder, { recursive: true }) + await writeFile(join(folder, 'a.jsonl'), 'secret transcript') + await writeFile(join(folder, 'b.jsonl'), 'secret transcript') + await utimes(join(folder, 'a.jsonl'), new Date('2026-10-01T00:00:00Z'), new Date('2026-10-01T00:00:00Z')) + await utimes(join(folder, 'b.jsonl'), new Date('2026-10-03T00:00:00Z'), new Date('2026-10-03T00:00:00Z')) + const source = createClaudeSource({ projectsDir: () => projects, root: home }) + expect(await source.list({ home, gitRoots: [] })).toEqual([{ path: join(home, 'Dev', 'app'), seenAt: T('2026-10-03T00:00:00Z') }]) + }) +}) + +describe('recent projects: codex source', () => { + it('reads the cwd from the first line only, current and older formats', async () => { + const a = join(home, 'a.jsonl'), b = join(home, 'b.jsonl'), c = join(home, 'c.jsonl') + await writeFile(a, JSON.stringify({ type: 'session_meta', payload: { id: 'x', cwd: '/Users/demo/Dev/api' } }) + '\n{"not json\n') + await writeFile(b, JSON.stringify({ cwd: '/Users/demo/Dev/old' }) + '\n') + await writeFile(c, 'garbage\n' + JSON.stringify({ cwd: '/second/line' }) + '\n') + expect(await sessionCwd(a)).toBe('/Users/demo/Dev/api') + expect(await sessionCwd(b)).toBe('/Users/demo/Dev/old') + expect(await sessionCwd(c)).toBeNull() + }) + + it('walks the dated session folders newest first', async () => { + const sessions = join(home, 'sessions') + await mkdir(join(sessions, '2026', '10', '19'), { recursive: true }) + await mkdir(join(sessions, '2026', '10', '20'), { recursive: true }) + await writeFile(join(sessions, '2026', '10', '19', 'rollout-1.jsonl'), JSON.stringify({ type: 'session_meta', payload: { cwd: '/p/old' } }) + '\n') + await writeFile(join(sessions, '2026', '10', '20', 'rollout-2.jsonl'), JSON.stringify({ type: 'session_meta', payload: { cwd: '/p/new' } }) + '\n') + const entries = await createCodexSource({ sessionsDir: () => sessions }).list({ home, gitRoots: [] }) + expect(entries.map((e) => e.path)).toEqual(['/p/new', '/p/old']) + }) +}) + +describe('recent projects: editors', () => { + it('keeps the local folders of VS Code’s recent list, in order', () => { + const json = JSON.stringify({ entries: [ + { folderUri: 'file:///Users/demo/Dev/my%20app' }, + { fileUri: 'file:///Users/demo/notes.md' }, + { folderUri: 'vscode-remote://ssh-remote%2Bhost/home/demo/app' }, + { workspace: { configPath: 'file:///Users/demo/x.code-workspace' } }, + { folderUri: 'file:///Volumes/Dev/api' }, + ] }) + expect(parseRecentlyOpened(json)).toEqual(['/Users/demo/Dev/my app', '/Volumes/Dev/api']) + expect(parseRecentlyOpened('not json')).toEqual([]) + }) + + it('reads one key through sqlite3, read-only, and dates folders from workspaceStorage', async () => { + const user = join(home, 'Library', 'Application Support', 'Code', 'User') + await mkdir(join(user, 'globalStorage'), { recursive: true }) + await writeFile(join(user, 'globalStorage', 'state.vscdb'), '') + await mkdir(join(user, 'workspaceStorage', 'abc'), { recursive: true }) + await writeFile(join(user, 'workspaceStorage', 'abc', 'workspace.json'), JSON.stringify({ folder: 'file:///Users/demo/Dev/b' })) + const exec = vi.fn(async (_file: string, _args: string[]) => JSON.stringify({ entries: [{ folderUri: 'file:///Users/demo/Dev/a' }, { folderUri: 'file:///Users/demo/Dev/b' }] }) + '\n') + const source = createVscodeSource('vscode', { fr: 'VS Code', en: 'VS Code' }, 'Code', exec) + expect(await source.available({ home, gitRoots: [] })).toBe(true) + const entries = await source.list({ home, gitRoots: [] }) + expect(exec.mock.calls[0][0]).toBe('/usr/bin/sqlite3') + expect(exec.mock.calls[0][1]).toContain('-readonly') + expect(entries.map((e) => e.path)).toEqual(['/Users/demo/Dev/a', '/Users/demo/Dev/b']) + expect(entries.every((e) => typeof e.seenAt === 'number')).toBe(true) + }) + + it('parses JetBrains recent projects, Rider solutions and $USER_HOME$', () => { + const xml = `` + expect(parseRecentProjects(xml, '/Users/demo')).toEqual([ + { path: '/Users/demo/Dev/api', seenAt: 1760000000000 }, + { path: '/Volumes/Dev/Shop', seenAt: 1750000000000 }, + { path: '/Users/demo/R&D', seenAt: null }, + ]) + }) +}) + +describe('recent projects: command-line sources', () => { + it('parses zoxide, tmux and Herdr output', () => { + expect(parseZoxide(' 24.0 /Users/demo/Dev/api\n 3.5 /Users/demo/Dev/web\nnoise\n')).toEqual([ + { path: '/Users/demo/Dev/api', seenAt: null }, { path: '/Users/demo/Dev/web', seenAt: null }, + ]) + expect(parseTmux('/Users/demo/Dev/api\t1760000000\n/Users/demo/x\t\n')).toEqual([ + { path: '/Users/demo/Dev/api', seenAt: 1760000000000 }, { path: '/Users/demo/x', seenAt: null }, + ]) + const herdr = JSON.stringify({ id: 'r', result: { panes: [ + { pane_id: 'p1', cwd: '/Users/demo', foreground_cwd: '/Users/demo/Dev/api', scroll: 'ignored' }, + { pane_id: 'p2', cwd: '/Users/demo/Dev/web', foreground_cwd: '' }, + { pane_id: 'p3', cwd: 'relative' }, + ] } }) + expect(parseHerdrPanes(herdr, 5)).toEqual([ + { path: '/Users/demo/Dev/api', seenAt: 5 }, { path: '/Users/demo/Dev/web', seenAt: 5 }, + ]) + expect(parseHerdrPanes('nope', 5)).toEqual([]) + }) + + it('runs each tool by absolute path with an argument list, and is unavailable when missing', async () => { + const exec = vi.fn(async () => '') + const [zoxide, tmux, herdr] = createCliSources(exec, async (name) => (name === 'tmux' ? null : `/opt/homebrew/bin/${name}`)) + expect(await tmux.available({ home, gitRoots: [] })).toBe(false) + await zoxide.list({ home, gitRoots: [] }) + await herdr.list({ home, gitRoots: [] }) + expect(exec.mock.calls).toEqual([ + ['/opt/homebrew/bin/zoxide', ['query', '--list', '--score']], + ['/opt/homebrew/bin/herdr', ['pane', 'list']], + ]) + }) + + it('treats tmux with no server running as an empty list', async () => { + const exec = vi.fn(async () => { throw new Error('no server running on /private/tmp/tmux-501/default') }) + const [, tmux] = createCliSources(exec, async () => '/opt/homebrew/bin/tmux') + expect(await tmux.list({ home, gitRoots: [] })).toEqual([]) + }) +}) + +describe('recent projects: settings and merge', () => { + it('reads git alone by default, every other source only when ticked', () => { + expect([...tileWants({}).sources]).toEqual(['git']) + expect([...tileWants({ source_git: false, source_claude: true }).sources]).toEqual(['claude']) + expect(tileWants({ gitRoots: [{ path: ' ~/Dev ' }, { path: '' }, 'x', 3] }).gitRoots).toEqual(['~/Dev', 'x']) + const merged = mergedWants([ + { widgetId: 'recent-projects', settings: { source_herdr: true, gitRoots: [{ path: '~/A' }] } }, + { widgetId: 'recent-projects', settings: { source_git: false, gitRoots: [{ path: '~/A' }, { path: '~/B' }] } }, + ]) + expect([...merged.sources].sort()).toEqual(['git', 'herdr']) + expect(merged.gitRoots).toEqual(['~/A', '~/B']) + }) + + it('dedupes by canonical path, keeping the newest date and every source, newest first', async () => { + await mkdir(join(home, 'Dev', 'api'), { recursive: true }) + await mkdir(join(home, 'Dev', 'web'), { recursive: true }) + await mkdir(join(home, 'Dev', 'old'), { recursive: true }) + await symlink(join(home, 'Dev', 'api'), join(home, 'api-link')) + const rows = await mergeEntries([ + { path: join(home, 'Dev', 'api'), seenAt: 10, source: 'git', gitRoot: '~/Dev' }, + { path: join(home, 'api-link'), seenAt: 30, source: 'claude' }, + { path: join(home, 'Dev', 'web'), seenAt: 20, source: 'vscode' }, + { path: join(home, 'Dev', 'old'), seenAt: null, source: 'zoxide' }, + { path: '/private/tmp', seenAt: 99, source: 'tmux' }, + { path: join(home, 'gone'), seenAt: 99, source: 'herdr' }, + ], home) + expect(rows).toEqual([ + { path: join(home, 'Dev', 'api'), name: 'api', parent: '~/Dev', seenAt: 30, sources: ['git', 'claude'], gitRoots: ['~/Dev'] }, + { path: join(home, 'Dev', 'web'), name: 'web', parent: '~/Dev', seenAt: 20, sources: ['vscode'] }, + { path: join(home, 'Dev', 'old'), name: 'old', parent: '~/Dev', seenAt: null, sources: ['zoxide'] }, + ]) + }) + + it('caps the list', async () => { + const entries = [] + for (let i = 0; i < MAX_PROJECTS + 5; i++) { + await mkdir(join(home, `p${i}`)) + entries.push({ path: join(home, `p${i}`), seenAt: i, source: 'git' as const }) + } + const rows = await mergeEntries(entries, home) + expect(rows).toHaveLength(MAX_PROJECTS) + expect(rows[0].name).toBe(`p${MAX_PROJECTS + 4}`) + }) +}) + +function fakeSource(id: Source['id'], list: Source['list'], live = false): Source { + return { id, label: { fr: id, en: id }, live, available: async () => true, list } +} + +describe('recent projects: provider', () => { + async function setup(sources: Source[], settings: Record) { + const exec = vi.fn(async () => '') + const provider = createRecentProjectsProvider({ + instances: () => [{ widgetId: 'recent-projects', settings }], + home, sources, exec, + resolveBinary: async (name) => (name === 'herdr' ? '/Users/demo/.local/bin/herdr' : null), + appExists: async (p) => p === '/Applications/Visual Studio Code.app' || p.endsWith('Finder.app'), + }) + return { provider, exec } + } + + it('never reads a source no tile ticked', async () => { + await mkdir(join(home, 'a')) + const claude = vi.fn(async () => [{ path: join(home, 'a'), seenAt: 1 }]) + const { provider } = await setup([fakeSource('claude', claude)], {}) + const snap = await provider.poll!() as RecentProjectsSnapshot + expect(claude).not.toHaveBeenCalled() + expect(snap.projects).toEqual([]) + expect(snap.sources).toEqual([{ id: 'claude', enabled: false, available: false, count: 0 }]) + }) + + it('keeps a failing source’s last good answer and reports its error', async () => { + await mkdir(join(home, 'a')) + let fail = false + const list = vi.fn(async () => { + if (fail) throw new Error('boom /Users/demo/secret') + return [{ path: join(home, 'a'), seenAt: 1 }] + }) + const { provider } = await setup([fakeSource('claude', list)], { source_claude: true }) + await provider.poll!() + fail = true + const snap = await provider.poll!() as RecentProjectsSnapshot + expect(snap.projects.map((p) => p.name)).toEqual(['a']) + expect(snap.sources[0]).toEqual({ id: 'claude', enabled: true, available: true, count: 1, error: 'unreadable' }) + }) + + it('remembers what a live source showed after it stops showing it', async () => { + await mkdir(join(home, 'a')) + await mkdir(join(home, 'b')) + let panes = [join(home, 'a')] + const { provider } = await setup([fakeSource('herdr', async () => panes.map((path) => ({ path, seenAt: 1 })), true)], { source_herdr: true }) + await provider.poll!() + panes = [join(home, 'b')] + const snap = await provider.poll!() as RecentProjectsSnapshot + expect(snap.projects.map((p) => p.name).sort()).toEqual(['a', 'b']) + }) + + it('lists the installed applications', async () => { + const { provider } = await setup([], {}) + expect((await provider.poll!() as RecentProjectsSnapshot).apps).toEqual(['finder', 'vscode', 'herdr']) + }) + + describe('open', () => { + async function ready() { + await mkdir(join(home, 'Dev', 'api'), { recursive: true }) + const s = await setup([fakeSource('git', async () => [{ path: join(home, 'Dev', 'api'), seenAt: 1 }])], {}) + await s.provider.poll!() + return { ...s, path: join(home, 'Dev', 'api'), open: s.provider.commands!.open } + } + + it('opens a listed folder with /usr/bin/open -a and the bundle path, or Herdr by argv', async () => { + const { exec, path, open } = await ready() + expect(await open({ path, app: 'vscode' }, LOCAL)).toEqual({ ok: true }) + expect(await open({ path, app: 'herdr' }, LOCAL)).toEqual({ ok: true, herdr: 'new-pane', front: null }) + expect(exec.mock.calls).toEqual([ + ['/usr/bin/open', ['-a', '/Applications/Visual Studio Code.app', path]], + ['/Users/demo/.local/bin/herdr', ['pane', 'list']], + ['/Users/demo/.local/bin/herdr', ['pane', 'split', '--cwd', path, '--direction', 'right', '--no-focus']], + ['/bin/ps', ['-axo', 'pid=,ppid=,comm=']], + ]) + }) + + it('refuses a remote or paired caller, an unlisted path, an unknown app, a missing app', async () => { + const { exec, path, open } = await ready() + expect(await open({ path, app: 'finder' })).toMatchObject({ ok: false, error: 'local-only' }) + expect(await open({ path, app: 'finder' }, { loopback: false, paired: false })).toMatchObject({ ok: false, error: 'local-only' }) + expect(await open({ path, app: 'finder' }, { loopback: false, paired: true, deviceId: 'd' })).toMatchObject({ ok: false, error: 'local-only' }) + expect(await open({ path: '/Applications/Calculator.app', app: 'finder' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + expect(await open({ path: join(home, 'Dev'), app: 'finder' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + expect(await open({ path, app: 'sh' }, LOCAL)).toMatchObject({ ok: false, error: 'invalid-request' }) + expect(await open({ path, app: 'herdr', terminal: 'Calculator' }, LOCAL)).toMatchObject({ ok: false, error: 'invalid-request' }) + expect(await open({ path, app: 'finder', command: 'rm -rf ~' }, LOCAL)).toEqual({ ok: true }) + expect(await open({ path, app: 'cursor' }, LOCAL)).toMatchObject({ ok: false, error: 'not-installed' }) + expect(await open({ path, app: 'tmux' }, LOCAL)).toMatchObject({ ok: false, error: 'not-installed' }) + expect(exec.mock.calls).toEqual([['/usr/bin/open', ['-a', '/System/Library/CoreServices/Finder.app', path]]]) + }) + + it('refuses a listed folder that has since been removed', async () => { + const { path, open } = await ready() + await rm(path, { recursive: true }) + expect(await open({ path, app: 'finder' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + }) + }) + + it('opens tmux in a new window at the folder', async () => { + const exec = vi.fn(async () => '') + await openWith('tmux', '/Users/demo/Dev/api', { exec, resolveBinary: async () => '/opt/homebrew/bin/tmux' }) + expect(exec).toHaveBeenCalledWith('/opt/homebrew/bin/tmux', ['new-window', '-c', '/Users/demo/Dev/api']) + }) +}) + +/** + * A Herdr with two workspaces: w1 holds one pane, w2 one tab of three panes side by side + * (p1 | p3 | p2), focused on p1. It answers `pane list`, `pane layout`, `pane neighbor` and + * moves its focus on `pane focus`, as Herdr 0.9.5 does; `stuck` makes focus moves do nothing. + */ +function fakeHerdr(opts: { zoomed?: boolean; stuck?: boolean; ps?: string; agentError?: string; agents?: string[] } = {}) { + const BIN = '/Users/demo/.local/bin/herdr' + const panes = [ + { pane_id: 'w1:p1', tab_id: 'w1:t1', workspace_id: 'w1', cwd: '/Users/demo', foreground_cwd: '/Users/demo' }, + { pane_id: 'w2:p1', tab_id: 'w2:t1', workspace_id: 'w2', cwd: '/Users/demo/Dev/web' }, + { pane_id: 'w2:p3', tab_id: 'w2:t1', workspace_id: 'w2', cwd: '/Users/demo/Dev/web' }, + { pane_id: 'w2:p2', tab_id: 'w2:t1', workspace_id: 'w2', cwd: '/Users/demo', foreground_cwd: '/Users/demo/Dev/api' }, + ] + const row = ['w2:p1', 'w2:p3', 'w2:p2'] + let focused = 'w2:p1' + const neighbor = (from: string, direction: string) => { + const i = row.indexOf(from) + if (direction === 'right') return row[i + 1] + if (direction === 'left') return i > 0 ? row[i - 1] : undefined + return undefined + } + const layout = () => ({ focused_pane_id: focused, zoomed: !!opts.zoomed, panes: row.map((pane_id) => ({ pane_id })), tab_id: 'w2:t1' }) + const exec = vi.fn(async (file: string, args: string[], _opts?: { timeoutMs?: number }) => { + if (file === '/bin/ps') return opts.ps ?? '' + if (file !== BIN) return '' + const [group, verb] = args + const flag = (name: string) => args[args.indexOf(name) + 1] + if (group === 'pane' && verb === 'list') return JSON.stringify({ id: 'cli:pane:list', result: { panes } }) + if (group === 'pane' && verb === 'layout') return JSON.stringify({ result: { layout: layout() } }) + if (group === 'pane' && verb === 'neighbor') { + const id = neighbor(flag('--pane'), flag('--direction')) + return JSON.stringify({ result: { neighbor: { layout: layout(), pane_id: flag('--pane'), ...(id ? { neighbor_pane_id: id } : {}) } } }) + } + if (group === 'pane' && verb === 'split') return JSON.stringify({ id: 'cli:pane:split', result: { pane: { pane_id: 'w2:p9', tab_id: 'w2:t1' } } }) + if (group === 'agent' && verb === 'start' && opts.agentError) throw new Error(opts.agentError) + if (group === 'pane' && verb === 'focus') { + if (!opts.stuck) focused = neighbor(flag('--pane'), flag('--direction')) ?? focused + return '{}' + } + return '{}' + }) + const deps = { + exec, + resolveBinary: async (name: string) => + name === 'herdr' ? BIN : (opts.agents ?? ['claude']).includes(name) ? `/Users/demo/.local/bin/${name}` : null, + exists: async (p: string) => p === '/Applications/iTerm.app' || p === '/Applications/Ghostty.app', + } + const calls = () => exec.mock.calls.map(([f, a]) => (f === BIN ? 'herdr ' : f + ' ') + a.join(' ')) + return { exec, deps, calls } +} + +/** `ps -axo pid=,ppid=,comm=` with Herdr's client in a shell under iTerm, and its server below it. */ +const PS_ITERM = [ + ' 1 0 /sbin/launchd', + ' 300 1 /Applications/iTerm.app/Contents/MacOS/iTerm2', + ' 310 300 /Users/demo/Library/Application Support/iTerm2/iTermServer-3.7.6', + ' 320 310 /usr/bin/login', + ' 330 320 -zsh', + ' 340 330 herdr', + ' 350 340 /Users/demo/.local/bin/herdr', +].join('\n') + +describe('recent projects: Herdr', () => { + it('goes to the pane already in the folder: its workspace, its tab, then the walk to it', async () => { + const h = fakeHerdr() + expect(await openWith('herdr', '/Users/demo/Dev/api', h.deps, { terminal: 'iterm' })).toEqual({ ok: true, herdr: 'pane', front: 'iterm' }) + const calls = h.calls() + expect(calls.slice(0, 3)).toEqual(['herdr pane list', 'herdr workspace focus w2', 'herdr tab focus w2:t1']) + expect(calls.filter((c) => c.startsWith('herdr pane focus'))).toEqual([ + 'herdr pane focus --direction right --pane w2:p1', + 'herdr pane focus --direction right --pane w2:p3', + ]) + expect(calls.at(-1)).toBe('/usr/bin/open -a /Applications/iTerm.app') + expect(calls.some((c) => c.includes('split'))).toBe(false) + }) + + it('matches a pane by its shell’s folder too, and stays put when that pane is already focused', async () => { + const h = fakeHerdr() + expect(await openWith('herdr', '/Users/demo/Dev/web', h.deps, { terminal: 'ghostty' })).toEqual({ ok: true, herdr: 'pane', front: 'ghostty' }) + expect(h.calls().some((c) => c.startsWith('herdr pane focus') || c.startsWith('herdr pane neighbor'))).toBe(false) + }) + + it('stops at the tab and says so when the focus does not reach the pane, or the tab is zoomed', async () => { + const stuck = fakeHerdr({ stuck: true }) + expect(await openWith('herdr', '/Users/demo/Dev/api', stuck.deps, { terminal: 'iterm' })).toMatchObject({ ok: true, herdr: 'tab' }) + const zoomed = fakeHerdr({ zoomed: true }) + expect(await openWith('herdr', '/Users/demo/Dev/api', zoomed.deps, { terminal: 'iterm' })).toMatchObject({ ok: true, herdr: 'tab' }) + expect(zoomed.calls().some((c) => c.startsWith('herdr pane neighbor') || c.startsWith('herdr pane focus'))).toBe(false) + }) + + it('splits a new pane when no pane is in the folder, and finds the terminal Herdr runs in', async () => { + const h = fakeHerdr({ ps: PS_ITERM }) + expect(await openWith('herdr', '/Users/demo/Dev/new', h.deps)).toEqual({ ok: true, herdr: 'new-pane', front: 'iterm' }) + expect(h.calls()).toEqual([ + 'herdr pane list', + 'herdr pane split --cwd /Users/demo/Dev/new --direction right --no-focus', + '/bin/ps -axo pid=,ppid=,comm=', + '/usr/bin/open -a /Applications/iTerm.app', + ]) + }) + + it('brings nothing forward when the terminal is not installed or cannot be told', async () => { + expect(await openWith('herdr', '/Users/demo/Dev/new', fakeHerdr().deps, { terminal: 'terminal' })).toMatchObject({ front: null }) + expect(await openWith('herdr', '/Users/demo/Dev/new', fakeHerdr().deps)).toMatchObject({ ok: true, front: null }) + }) + + it('detects one terminal only: none or two is no answer', async () => { + const ps = async (out: string) => detectHerdrTerminal(async () => out) + expect(await ps(PS_ITERM)).toBe('iterm') + expect(await ps(PS_ITERM + '\n 400 1 /Applications/Ghostty.app/Contents/MacOS/ghostty\n 410 400 herdr')).toBeNull() + expect(await ps(' 340 1 herdr')).toBeNull() + expect(await ps(' 300 1 /Applications/iTerm.app/Contents/MacOS/iTerm2')).toBeNull() + }) +}) + +describe('recent projects: suggested application', () => { + const ALL: AppId[] = ['finder', 'xcode', 'jetbrains-idea', 'jetbrains-pycharm', 'jetbrains-rider', 'jetbrains-rustrover', + 'jetbrains-goland', 'jetbrains-phpstorm', 'jetbrains-rubymine', 'jetbrains-clion', 'jetbrains-android-studio'] + + async function project(entries: Record): Promise { + const dir = await mkdtemp(join(home, 'p-')) + for (const [name, kind] of Object.entries(entries)) { + if (kind === 'dir') await mkdir(join(dir, name), { recursive: true }) + else { + await mkdir(join(dir, name, '..'), { recursive: true }) + await writeFile(join(dir, name), '') + } + } + return dir + } + + it.each([ + [{ 'Shop.sln': 'file' }, 'jetbrains-rider'], + [{ 'Api.csproj': 'file' }, 'jetbrains-rider'], + [{ 'Lib.fsproj': 'file' }, 'jetbrains-rider'], + [{ 'App.xcodeproj': 'dir' }, 'xcode'], + [{ 'App.xcworkspace': 'dir' }, 'xcode'], + [{ 'Package.swift': 'file' }, 'xcode'], + [{ 'Cargo.toml': 'file' }, 'jetbrains-rustrover'], + [{ 'go.mod': 'file' }, 'jetbrains-goland'], + [{ 'pyproject.toml': 'file' }, 'jetbrains-pycharm'], + [{ 'requirements.txt': 'file' }, 'jetbrains-pycharm'], + [{ 'composer.json': 'file' }, 'jetbrains-phpstorm'], + [{ Gemfile: 'file' }, 'jetbrains-rubymine'], + [{ 'build.gradle': 'file' }, 'jetbrains-idea'], + [{ 'build.gradle.kts': 'file' }, 'jetbrains-idea'], + [{ 'pom.xml': 'file' }, 'jetbrains-idea'], + [{ 'build.gradle.kts': 'file', 'app/src/main/AndroidManifest.xml': 'file' }, 'jetbrains-android-studio'], + [{ 'AndroidManifest.xml': 'file', 'build.gradle': 'file' }, 'jetbrains-android-studio'], + [{ 'CMakeLists.txt': 'file' }, 'jetbrains-clion'], + [{ 'package.json': 'file', 'README.md': 'file' }, null], + [{ 'sub/Cargo.toml': 'file' }, null], + ] as [Record, AppId | null][])('%o suggests %s', async (entries, app) => { + expect(await suggestApp(await project(entries), ALL)).toBe(app) + }) + + it('suggests only an installed application, trying the next candidate, else nothing', async () => { + expect(await suggestApp(await project({ 'Cargo.toml': 'file' }), ['finder', 'vscode'])).toBeNull() + expect(await suggestApp(await project({ 'pom.xml': 'file' }), ['jetbrains-idea-ce'])).toBe('jetbrains-idea-ce') + expect(await suggestApp(await project({ 'requirements.txt': 'file' }), ['jetbrains-pycharm-ce'])).toBe('jetbrains-pycharm-ce') + // Android Studio missing: a Gradle build is still IntelliJ's. + expect(await suggestApp(await project({ 'build.gradle': 'file', 'AndroidManifest.xml': 'file' }), ['jetbrains-idea'])).toBe('jetbrains-idea') + // Rider missing, but the same root names another rule's installed IDE. + expect(await suggestApp(await project({ 'Tool.sln': 'file', 'CMakeLists.txt': 'file' }), ['jetbrains-clion'])).toBe('jetbrains-clion') + }) + + it('reads names only, never a file', async () => { + const dir = await project({ 'Cargo.toml': 'file' }) + await chmod(join(dir, 'Cargo.toml'), 0o000) + expect(await suggestApp(dir, ALL)).toBe('jetbrains-rustrover') + expect(await suggestApp(join(home, 'gone'), ALL)).toBeNull() + }) +}) + +describe('recent projects: a project’s own application', () => { + async function setup(opts: { settings?: Record; file?: string } = {}) { + await mkdir(join(home, 'Dev', 'api'), { recursive: true }) + await writeFile(join(home, 'Dev', 'api', 'Api.sln'), '') + const onChange = vi.fn() + const provider = createRecentProjectsProvider({ + instances: () => [{ widgetId: 'recent-projects', settings: opts.settings ?? {} }], + home, sources: [fakeSource('git', async () => [{ path: join(home, 'Dev', 'api'), seenAt: 1 }])], + exec: vi.fn(async () => ''), resolveBinary: async () => null, + appExists: async (p) => p === '/Applications/Rider.app' || p === '/Applications/Zed.app' || p.endsWith('Finder.app'), + memoryFile: opts.file ?? join(home, 'recent-projects.json'), onChange, + }) + const snap = async () => (await provider.poll!()) as RecentProjectsSnapshot + return { provider, snap, onChange, path: join(home, 'Dev', 'api'), set: provider.commands!.setOpener } + } + + it('suggests from the root’s names, unless every tile turned suggestions off', async () => { + expect((await (await setup()).snap()).projects[0]).toMatchObject({ suggested: 'jetbrains-rider' }) + expect((await (await setup({ settings: { suggestApp: false } })).snap()).projects[0].suggested).toBeUndefined() + }) + + it('keeps the chosen application over the suggestion, clears it, and tells the registry', async () => { + const { snap, set, path, onChange } = await setup() + await snap() + expect(await set({ path, app: 'zed' }, LOCAL)).toEqual({ ok: true }) + expect(onChange).toHaveBeenCalledTimes(1) + const chosen = (await snap()).projects[0] + expect(chosen.opener).toBe('zed') + expect(chosen.suggested).toBeUndefined() + expect(await set({ path, app: null }, LOCAL)).toEqual({ ok: true }) + expect((await snap()).projects[0]).toMatchObject({ suggested: 'jetbrains-rider' }) + expect((await snap()).projects[0].opener).toBeUndefined() + }) + + it('refuses a remote or paired caller, a bad payload, an unlisted or non-canonical path, an app not installed', async () => { + const { snap, set, path, onChange } = await setup() + await snap() + expect(await set({ path, app: 'zed' })).toMatchObject({ ok: false, error: 'local-only' }) + expect(await set({ path, app: 'zed' }, { loopback: false, paired: false })).toMatchObject({ ok: false, error: 'local-only' }) + expect(await set({ path, app: 'zed' }, { loopback: false, paired: true, deviceId: 'd' })).toMatchObject({ ok: false, error: 'local-only' }) + expect(await set({ path, app: 'Calculator' }, LOCAL)).toMatchObject({ ok: false, error: 'invalid-request' }) + expect(await set({ path }, LOCAL)).toMatchObject({ ok: false, error: 'invalid-request' }) + expect(await set({ path: 42, app: 'zed' }, LOCAL)).toMatchObject({ ok: false, error: 'invalid-request' }) + expect(await set({ path: join(home, 'Dev'), app: 'zed' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + expect(await set({ path: path + '/', app: 'zed' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + expect(await set({ path: home + '/Dev/../Dev/api', app: 'zed' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + expect(await set({ path, app: 'cursor' }, LOCAL)).toMatchObject({ ok: false, error: 'not-installed' }) + expect(onChange).not.toHaveBeenCalled() + expect((await snap()).projects[0].opener).toBeUndefined() + }) + + it('survives a restart in the 0600 data file, beside the live memory, and is dropped with its folder', async () => { + const file = join(home, 'recent-projects.json') + const first = await setup({ file }) + await first.snap() + await first.set({ path: first.path, app: 'jetbrains-rider' }, LOCAL) + expect((await stat(file)).mode & 0o777).toBe(0o600) + expect(JSON.parse(await readFile(file, 'utf8')).openers).toEqual([{ path: first.path, app: 'jetbrains-rider' }]) + + const again = await setup({ file }) + expect((await again.snap()).projects[0].opener).toBe('jetbrains-rider') + + await rm(first.path, { recursive: true }) + await again.snap() + expect((await loadState(file)).openers.size).toBe(0) + }) + + it('keeps the newest 200 and drops entries that do not check', async () => { + const file = join(home, 'recent-projects.json') + const openers = Array.from({ length: MAX_OPENERS + 50 }, (_, i) => ({ path: `/Users/demo/p${i}`, app: 'zed' })) + await writeFile(file, JSON.stringify({ version: 1, sources: {}, openers: [...openers, { path: '/Users/demo/x', app: 'sh' }, { path: 'rel', app: 'zed' }] })) + const state = await loadState(file) + expect(state.openers.size).toBe(MAX_OPENERS) + expect([...state.openers.keys()][0]).toBe('/Users/demo/p50') + expect(state.openers.has('/Users/demo/x')).toBe(false) + }) +}) + +describe('recent projects: JetBrains IDEs', () => { + const exec = vi.fn(async () => '') + const deps = (bundles: string[]) => ({ exec, resolveBinary: async () => null, exists: async (p: string) => bundles.includes(p) }) + + it('offers one choice per IDE installed, under a fixed id, wherever the Toolbox put it', async () => { + const home = homedir() + const apps = await installedApps(deps([ + '/System/Library/CoreServices/Finder.app', + '/Applications/Rider.app', + join(home, 'Applications', 'IntelliJ IDEA.app'), + join(home, 'Applications', 'JetBrains Toolbox', 'PyCharm Community Edition.app'), + '/Applications/Android Studio.app', + '/Applications/Rider Notes.app', + ])) + expect(apps).toEqual(['finder', 'jetbrains-idea', 'jetbrains-pycharm-ce', 'jetbrains-rider', 'jetbrains-android-studio']) + }) + + it('opens the folder with /usr/bin/open -a and the bundle path, and refuses one not installed', async () => { + exec.mockClear() + const d = deps(['/Applications/Rider.app']) + expect(await openWith('jetbrains-rider', '/Users/demo/Dev/api', d)).toEqual({ ok: true }) + expect(await openWith('jetbrains-goland', '/Users/demo/Dev/api', d)).toEqual({ ok: false, error: 'not-installed' }) + expect(exec.mock.calls).toEqual([['/usr/bin/open', ['-a', '/Applications/Rider.app', '/Users/demo/Dev/api']]]) + }) + + it('takes no IDE name from the request', async () => { + await mkdir(join(home, 'Dev', 'api'), { recursive: true }) + const provider = createRecentProjectsProvider({ + instances: () => [{ widgetId: 'recent-projects', settings: {} }], + home, sources: [fakeSource('git', async () => [{ path: join(home, 'Dev', 'api'), seenAt: 1 }])], + exec, resolveBinary: async () => null, appExists: async () => true, + }) + await provider.poll!() + const open = provider.commands!.open + expect(await open({ path: join(home, 'Dev', 'api'), app: 'jetbrains-Rider Notes' }, LOCAL)).toMatchObject({ ok: false, error: 'invalid-request' }) + expect(await open({ path: join(home, 'Dev', 'api'), app: 'Rider' }, LOCAL)).toMatchObject({ ok: false, error: 'invalid-request' }) + }) +}) + +describe('recent projects: an agent in a new pane', () => { + it('splits a new focused pane on the folder, then starts the agent there with Herdr’s agent start', async () => { + const h = fakeHerdr() + expect(await openWith('herdr-claude', '/Users/demo/Dev/api', h.deps, { terminal: 'iterm' })) + .toEqual({ ok: true, herdr: 'new-pane', agent: 'started', front: 'iterm' }) + const calls = h.calls() + expect(calls[0]).toBe('herdr pane split --cwd /Users/demo/Dev/api --direction right --focus') + expect(calls[1]).toMatch(/^herdr agent start fremkit-claude-[a-z0-9]+ --kind claude --pane w2:p9 --timeout 30000$/) + expect(calls.at(-1)).toBe('/usr/bin/open -a /Applications/iTerm.app') + // Never the pane already in the folder, and the folder on no command line but as --cwd. + expect(calls.some((c) => c.includes('pane list') || c.includes('focus w2'))).toBe(false) + expect(calls.filter((c) => c.includes('/Users/demo/Dev/api'))).toHaveLength(1) + // The agent's start may take Herdr's 30 s: the call around it waits longer than the default. + expect(h.exec.mock.calls[1][2]).toEqual({ timeoutMs: 35_000 }) + expect(calls[1].split(' ')[3]).toMatch(/^[a-z][a-z0-9_-]{0,31}$/) + }) + + it('counts an agent waiting at a startup question as started, and anything else as a failure', async () => { + const waiting = fakeHerdr({ agentError: 'agent_not_ready: blocked at startup' }) + expect(await openWith('herdr-claude', '/Users/demo/Dev/api', waiting.deps)).toMatchObject({ ok: true, agent: 'waiting' }) + await expect(openWith('herdr-claude', '/Users/demo/Dev/api', fakeHerdr({ agentError: 'unknown kind' }).deps)).rejects.toThrow() + }) + + it('offers no agent whose binary is missing, and refuses it', async () => { + const h = fakeHerdr({ agents: ['claude'] }) + const apps = await installedApps(h.deps) + expect(apps).toContain('herdr-claude') + expect(apps).not.toContain('herdr-codex') + expect(apps).not.toContain('tmux-claude') + expect(await openWith('herdr-codex', '/Users/demo/Dev/api', h.deps)).toEqual({ ok: false, error: 'not-installed' }) + expect(h.exec).not.toHaveBeenCalled() + }) + + it('starts the agent by its absolute path in a new tmux window, and only a path a shell reads as is', async () => { + const exec = vi.fn(async () => '') + const bins: Record = { tmux: '/opt/homebrew/bin/tmux', codex: '/opt/homebrew/bin/codex', claude: '/Users/my demo/.local/bin/claude' } + const deps = { exec, resolveBinary: async (n: string) => bins[n] ?? null } + expect(await openWith('tmux-codex', '/Users/demo/Dev/api', deps)).toEqual({ ok: true }) + expect(exec.mock.calls).toEqual([['/opt/homebrew/bin/tmux', ['new-window', '-c', '/Users/demo/Dev/api', '/opt/homebrew/bin/codex']]]) + expect(await installedApps(deps)).toEqual(expect.arrayContaining(['tmux-codex'])) + expect(await installedApps(deps)).not.toContain('tmux-claude') + expect(await openWith('tmux-claude', '/Users/demo/Dev/api', deps)).toEqual({ ok: false, error: 'not-installed' }) + }) + + it('looks for Claude Code in its own installer’s folder too', () => { + expect(binaryCandidates('claude', '/Users/demo')).toContain('/Users/demo/.claude/local/claude') + expect(binaryCandidates('codex', '/Users/demo')).not.toContain('/Users/demo/.claude/local/codex') + }) + + it('refuses an agent launch on a folder the snapshot does not list, and remembers one it opens', async () => { + await mkdir(join(home, 'Dev', 'api'), { recursive: true }) + const file = join(home, 'recent-projects.json') + const h = fakeHerdr() + const provider = createRecentProjectsProvider({ + instances: () => [{ widgetId: 'recent-projects', settings: {} }], + home, sources: [fakeSource('git', async () => [{ path: join(home, 'Dev', 'api'), seenAt: 1 }])], + exec: h.exec, resolveBinary: h.deps.resolveBinary as never, appExists: async () => false, memoryFile: file, + }) + await provider.poll!() + const open = provider.commands!.open + expect(await open({ path: join(home, 'Dev'), app: 'herdr-claude' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + expect(await open({ path: '/Users/demo/elsewhere', app: 'herdr-claude' }, LOCAL)).toMatchObject({ ok: false, error: 'unknown-project' }) + expect(await open({ path: join(home, 'Dev', 'api'), app: 'herdr-claude' }, { loopback: false, paired: true, deviceId: 'd' })).toMatchObject({ ok: false, error: 'local-only' }) + expect(h.exec).not.toHaveBeenCalledWith(expect.anything(), expect.arrayContaining(['split']), expect.anything()) + expect(h.calls().filter((c) => c.startsWith('herdr'))).toEqual([]) + + expect(await open({ path: join(home, 'Dev', 'api'), app: 'herdr-claude' }, LOCAL)).toMatchObject({ ok: true, agent: 'started' }) + expect([...(await loadMemory(file)).get('herdr')!.keys()]).toEqual([join(home, 'Dev', 'api')]) + }) +}) + +describe('recent projects: live sources remembered on disk', () => { + function provider(file: string, list: Source['list']) { + return createRecentProjectsProvider({ + instances: () => [{ widgetId: 'recent-projects', settings: { source_git: false, source_herdr: true } }], + home, sources: [fakeSource('herdr', list, true)], exec: vi.fn(async () => ''), + resolveBinary: async () => null, appExists: async () => false, memoryFile: file, + }) + } + const names = (snap: unknown) => (snap as RecentProjectsSnapshot).projects.map((p) => p.name).sort() + + it('keeps what Herdr showed across a restart, in an owner-only file of paths and dates', async () => { + await mkdir(join(home, 'a')) + await mkdir(join(home, 'b')) + const file = join(home, 'recent-projects.json') + await provider(file, async () => [{ path: join(home, 'a'), seenAt: 1000 }]).poll!() + expect((await stat(file)).mode & 0o777).toBe(0o600) + expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ version: 1, sources: { herdr: [{ path: join(home, 'a'), seenAt: 1000 }] } }) + expect((await readdir(home)).filter((n) => n.endsWith('.tmp'))).toEqual([]) + + // A new server: the pane in `a` is closed, one is open in `b`. + const again = provider(file, async () => [{ path: join(home, 'b'), seenAt: 2000 }]) + expect(names(await again.poll!())).toEqual(['a', 'b']) + }) + + it('shows the remembered folders while the live source fails right after a restart', async () => { + await mkdir(join(home, 'a')) + const file = join(home, 'recent-projects.json') + await provider(file, async () => [{ path: join(home, 'a'), seenAt: 1000 }]).poll!() + const broken = provider(file, async () => { throw new Error('socket') }) + expect(names(await broken.poll!())).toEqual(['a']) + }) + + it('starts empty on a corrupt file, never crashes, and writes a good one over it', async () => { + await mkdir(join(home, 'a')) + const file = join(home, 'recent-projects.json') + for (const junk of ['{not json', '[]', JSON.stringify({ version: 2, sources: {} }), JSON.stringify({ version: 1, sources: 'x' })]) { + await writeFile(file, junk) + expect((await loadMemory(file)).size).toBe(0) + } + await writeFile(file, '{not json') + expect(names(await provider(file, async () => [{ path: join(home, 'a'), seenAt: 5 }]).poll!())).toEqual(['a']) + expect((await loadMemory(file)).get('herdr')?.get(join(home, 'a'))).toBe(5) + }) + + it('drops bad entries and sources that are not live, and keeps the newest 50 per source', async () => { + const file = join(home, 'recent-projects.json') + const many = Array.from({ length: LIVE_MEMORY + 10 }, (_, i) => ({ path: `/Users/demo/p${i}`, seenAt: i })) + await writeFile(file, JSON.stringify({ version: 1, sources: { + herdr: [...many, { path: 'relative', seenAt: 1 }, { path: '/Users/demo/x', seenAt: 'yesterday' }, 42], + tmux: [{ path: '/Users/demo/t', seenAt: null }], + claude: [{ path: '/Users/demo/c', seenAt: 1 }], + } })) + const memory = await loadMemory(file) + expect([...memory.keys()].sort()).toEqual(['herdr', 'tmux']) + const herdr = [...memory.get('herdr')!.keys()] + expect(herdr).toHaveLength(LIVE_MEMORY) + expect(herdr[0]).toBe('/Users/demo/p10') + expect(herdr.at(-1)).toBe(`/Users/demo/p${LIVE_MEMORY + 9}`) + }) +}) + +describe('recent projects: reach', () => { + it('is reserved to built-in widgets and never reaches a paired device', () => { + expect(BUILTIN_ONLY_CHANNELS.has('recent-projects')).toBe(true) + expect(LOCAL_ONLY_CHANNELS.has('recent-projects')).toBe(true) + }) +}) diff --git a/ui/src/shared/credits.ts b/ui/src/shared/credits.ts index 985bc997..569af6ed 100644 --- a/ui/src/shared/credits.ts +++ b/ui/src/shared/credits.ts @@ -18,6 +18,7 @@ export const MAINTAINER: Person = { handle: 'usul', github: 'fdussert' } export const CONTRIBUTORS: readonly Person[] = [ { handle: 'FlorianBruniaux', github: 'FlorianBruniaux' }, { handle: 'mcouzinet', github: 'mcouzinet' }, + { handle: 'LivioGama', github: 'LivioGama' }, ] export const REPOSITORY = 'https://github.com/fdussert/fremkit' diff --git a/ui/src/shared/icons.ts b/ui/src/shared/icons.ts index 6c0c70a2..480ed646 100644 --- a/ui/src/shared/icons.ts +++ b/ui/src/shared/icons.ts @@ -11,6 +11,7 @@ export const ICONS: Record = { 'calendar-days': '', cpu: '', 'chart-pie': '', + 'folder-clock': '', 'hard-drive': '', 'memory-stick': '', network: '', diff --git a/widgets/recent-projects/index.html b/widgets/recent-projects/index.html new file mode 100644 index 00000000..506bc6ee --- /dev/null +++ b/widgets/recent-projects/index.html @@ -0,0 +1,370 @@ + +Recent projects + +
+
+ + +
+ diff --git a/widgets/recent-projects/manifest.json b/widgets/recent-projects/manifest.json new file mode 100644 index 00000000..3f3d7c68 --- /dev/null +++ b/widgets/recent-projects/manifest.json @@ -0,0 +1,80 @@ +{ "id": "recent-projects", + "name": { "fr": "Projets récents", "en": "Recent projects" }, + "version": "0.1.0", "preview": "preview.webp", + "description": { "fr": "Les dossiers sur lesquels vous avez travaillé récemment, à ouvrir d’un geste", + "en": "The folders you worked in lately, one tap away" }, + "category": "dev", + "icon": "folder-clock", "minSize": [8, 4], "defaultSize": [12, 8], + "compact": { "width": 8 }, + "subscriptions": ["recent-projects"], "commands": ["recent-projects"], + "settingsSchema": { + "source_git": { "type": "boolean", "default": true, + "label": { "fr": "Source : dépôts git sous les dossiers ci-dessous", "en": "Source: git repositories under the folders below" } }, + "gitRoots": { "type": "list", "default": [], "max": 20, + "label": { "fr": "Dossiers où chercher des dépôts git (3 niveaux)", "en": "Folders to look for git repositories in (3 levels)" }, + "itemSchema": { + "path": { "type": "string", "default": "", + "label": { "fr": "Dossier (~/Dev, /Volumes/Dev…)", "en": "Folder (~/Dev, /Volumes/Dev…)" } } + } }, + "source_claude": { "type": "boolean", "default": false, + "label": { "fr": "Source : Claude Code", "en": "Source: Claude Code" } }, + "source_codex": { "type": "boolean", "default": false, + "label": { "fr": "Source : Codex", "en": "Source: Codex" } }, + "source_vscode": { "type": "boolean", "default": false, + "label": { "fr": "Source : VS Code (récents)", "en": "Source: VS Code (recent)" } }, + "source_cursor": { "type": "boolean", "default": false, + "label": { "fr": "Source : Cursor (récents)", "en": "Source: Cursor (recent)" } }, + "source_jetbrains": { "type": "boolean", "default": false, + "label": { "fr": "Source : IDE JetBrains (récents)", "en": "Source: JetBrains IDEs (recent)" } }, + "source_zoxide": { "type": "boolean", "default": false, + "label": { "fr": "Source : zoxide", "en": "Source: zoxide" } }, + "source_tmux": { "type": "boolean", "default": false, + "label": { "fr": "Source : panneaux tmux ouverts", "en": "Source: open tmux panes" } }, + "source_herdr": { "type": "boolean", "default": false, + "label": { "fr": "Source : panneaux Herdr ouverts", "en": "Source: open Herdr panes" } }, + "defaultApp": { "type": "enum", "default": "finder", + "label": { "fr": "Ouvrir avec (toucher)", "en": "Open with (tap)" }, + "options": [ + { "value": "finder", "label": { "fr": "Finder", "en": "Finder" } }, + { "value": "terminal", "label": { "fr": "Terminal", "en": "Terminal" } }, + { "value": "iterm", "label": { "fr": "iTerm", "en": "iTerm" } }, + { "value": "ghostty", "label": { "fr": "Ghostty", "en": "Ghostty" } }, + { "value": "vscode", "label": { "fr": "VS Code", "en": "VS Code" } }, + { "value": "cursor", "label": { "fr": "Cursor", "en": "Cursor" } }, + { "value": "zed", "label": { "fr": "Zed", "en": "Zed" } }, + { "value": "xcode", "label": { "fr": "Xcode", "en": "Xcode" } }, + { "value": "jetbrains-idea", "label": { "fr": "IntelliJ IDEA", "en": "IntelliJ IDEA" } }, + { "value": "jetbrains-idea-ce", "label": { "fr": "IntelliJ IDEA CE", "en": "IntelliJ IDEA CE" } }, + { "value": "jetbrains-webstorm", "label": { "fr": "WebStorm", "en": "WebStorm" } }, + { "value": "jetbrains-pycharm", "label": { "fr": "PyCharm", "en": "PyCharm" } }, + { "value": "jetbrains-pycharm-ce", "label": { "fr": "PyCharm CE", "en": "PyCharm CE" } }, + { "value": "jetbrains-phpstorm", "label": { "fr": "PhpStorm", "en": "PhpStorm" } }, + { "value": "jetbrains-goland", "label": { "fr": "GoLand", "en": "GoLand" } }, + { "value": "jetbrains-rider", "label": { "fr": "Rider", "en": "Rider" } }, + { "value": "jetbrains-clion", "label": { "fr": "CLion", "en": "CLion" } }, + { "value": "jetbrains-rustrover", "label": { "fr": "RustRover", "en": "RustRover" } }, + { "value": "jetbrains-rubymine", "label": { "fr": "RubyMine", "en": "RubyMine" } }, + { "value": "jetbrains-datagrip", "label": { "fr": "DataGrip", "en": "DataGrip" } }, + { "value": "jetbrains-android-studio", "label": { "fr": "Android Studio", "en": "Android Studio" } }, + { "value": "herdr", "label": { "fr": "Herdr (panneau existant, sinon nouveau)", "en": "Herdr (existing pane, else a new one)" } }, + { "value": "tmux", "label": { "fr": "tmux (nouvelle fenêtre)", "en": "tmux (new window)" } }, + { "value": "herdr-claude", "label": { "fr": "Herdr + Claude Code (nouveau panneau)", "en": "Herdr + Claude Code (new pane)" } }, + { "value": "herdr-codex", "label": { "fr": "Herdr + Codex (nouveau panneau)", "en": "Herdr + Codex (new pane)" } }, + { "value": "tmux-claude", "label": { "fr": "tmux + Claude Code (nouvelle fenêtre)", "en": "tmux + Claude Code (new window)" } }, + { "value": "tmux-codex", "label": { "fr": "tmux + Codex (nouvelle fenêtre)", "en": "tmux + Codex (new window)" } } + ] }, + "suggestApp": { "type": "boolean", "default": true, + "label": { "fr": "Suggérer une appli d’après les fichiers du projet", "en": "Suggest an app from the project’s files" } }, + "herdrTerminal": { "type": "enum", "default": "auto", + "label": { "fr": "Terminal de Herdr (mis au premier plan)", "en": "Herdr’s terminal (brought to the front)" }, + "options": [ + { "value": "auto", "label": { "fr": "Détecter", "en": "Detect" } }, + { "value": "terminal", "label": { "fr": "Terminal", "en": "Terminal" } }, + { "value": "iterm", "label": { "fr": "iTerm", "en": "iTerm" } }, + { "value": "ghostty", "label": { "fr": "Ghostty", "en": "Ghostty" } } + ] }, + "max": { "type": "number", "default": 8, + "label": { "fr": "Lignes affichées", "en": "Rows shown" } }, + "compactCount": { "type": "number", "default": 3, "scope": "compact", + "label": { "fr": "Projets dans la barre", "en": "Projects in the bar" } } + } } diff --git a/widgets/recent-projects/preview.webp b/widgets/recent-projects/preview.webp new file mode 100644 index 00000000..bd31bfb0 Binary files /dev/null and b/widgets/recent-projects/preview.webp differ