Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(ui): projects panel keeps indexing, ADR editing and server views in the browser
Martin Vogelc8661d7fb1cd
diff --git a/graph-ui/index.html b/graph-ui/index.htmlindex d8222578b..cd3517a37 100644--- a/graph-ui/index.html+++ b/graph-ui/index.html@@ -4,6 +4,7 @@<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="color-scheme" content="dark" />+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%27http://www.w3.org/2000/svg%27 viewBox=%270 0 16 16%27%3E%3Crect width=%2716%27 height=%2716%27 fill=%27%230a0e0d%27/%3E%3Ccircle cx=%278%27 cy=%278%27 r=%274%27 fill=%27%2333ff99%27/%3E%3C/svg%3E" /><title>CodeAtlas</title></head><body>diff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsxindex bf7f9e932..33a2ce9e5 100644--- a/graph-ui/src/App.tsx+++ b/graph-ui/src/App.tsx@@ -296,6 +296,9 @@ import { readLlmPreference, recordLlmPreference } from './llm/preference';import { llmChipValue, llmMenuLabel, llmMenuTitle } from './llm/strings';import SettingsPanel from './settings/SettingsPanel';import type { SettingsMeasurement } from './settings/SettingsPanel';+import ProjectsPanel from './projects/ProjectsPanel';+import type { ProjectsSource } from './projects/ProjectsPanel';+import { projectHref } from './projects/projects-model';import { MODEL_SUGGESTIONS, fetchCommand } from './settings/model-catalog';import { modelKey, readModelPreference, recordModelPreference } from './settings/model-preference';import {@@ -734,6 +737,32 @@ export default function App(): JSX.Element {const client = useMemo(() => new RpcIntelligenceClient({}), []);const api = useMemo(() => new AtlasApi({}), []);+ /*+ * What the projects panel asks the server. The list comes over /rpc like+ * every other read of this window; the rest are the /api routes the panel+ * names in its own text. Opening a project reloads the page with the+ * query the start-up code reads, because every panel of this window is+ * keyed to the project it started with.+ */+ const projectsSource = useMemo<ProjectsSource>(+ () => ({+ listProjects: () => client.listProjects().then((result) => result.projects),+ projectHealth: (name) => api.projectHealth(name),+ deleteProject: (name) => api.deleteProject(name),+ browse: (path) => api.browse(path),+ startIndex: (rootPath, projectName) => api.startIndex(rootPath, projectName),+ indexJobs: () => api.indexJobs(),+ adr: (name) => api.adr(name),+ saveAdr: (name, content) => api.saveAdr(name, content),+ logs: (lines) => api.logs(lines),+ processes: () => api.processes(),+ }),+ [client, api],+ );+ const openProject = useCallback((name: string) => {+ window.location.assign(projectHref(name));+ }, []);+const [project, setProject] = useState('');const [projectDetail, setProjectDetail] = useState('resolving project ...');const [serverOk, setServerOk] = useState<boolean | undefined>(undefined);@@ -854,6 +883,7 @@ export default function App(): JSX.Element {* die Hilfe: eine Flaeche ueber dem Editor geht nicht ungefragt auf.*/const [settingsOpen, setSettingsOpen] = useState(false);+ const [projectsOpen, setProjectsOpen] = useState(false);/** Die Anzeige-Einstellungen des Lesers.*@@ -2579,7 +2609,7 @@ export default function App(): JSX.Element {* eigenes Eingabefeld. Ohne diesen Eintrag fielen Buchstaben, die* jemand vor dem offenen Panel tippt, in die Kommandozeile dahinter.*/- overlayOpen: helpOpen || entryOpen || settingsOpen,+ overlayOpen: helpOpen || entryOpen || settingsOpen || projectsOpen,walkRunning: tour !== undefined,};@@ -3860,6 +3890,22 @@ export default function App(): JSX.Element {return () => window.removeEventListener('keydown', onKeyDown);}, [settingsOpen]);+ // And for the projects panel, which has input fields of its own as well.+ useEffect(() => {+ if (!projectsOpen) {+ return;+ }+ const onKeyDown = (event: globalThis.KeyboardEvent): void => {+ if (event.key !== 'Escape' || event.defaultPrevented) {+ return;+ }+ event.preventDefault();+ setProjectsOpen(false);+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [projectsOpen]);+/*** Die vier Tasten einer laufenden Fuehrung.*@@ -4428,6 +4474,18 @@ export default function App(): JSX.Element {title: messages.menu.settings,onSelect: () => setSettingsOpen((open) => !open),},+ /*+ * The projects panel, as an entry of the atlas row. It toggles like+ * [s]ettings next to it: the letter stands for the surface, and a+ * second press closes it again.+ */+ {+ key: 'projects',+ shortcut: 'p',+ label: messages.projects.menuLabel,+ title: messages.menu.projects,+ onSelect: () => setProjectsOpen((open) => !open),+ },/** Der Live-Modus der Agenten (W11a), als Eintrag der Atlas-Zeile.*@@ -4587,7 +4645,7 @@ export default function App(): JSX.Element {* braucht. Dieselbe Reihenfolge wie ueberall in dieser Datei: was* ueber dem Panel liegt, hat den Vortritt.*/- escapeTaken={helpOpen || entryOpen || overlayOpen || settingsOpen}+ escapeTaken={helpOpen || entryOpen || overlayOpen || settingsOpen || projectsOpen}fullscreenToggle={fullscreenToggle}/>);@@ -4989,6 +5047,20 @@ export default function App(): JSX.Element {onClose={() => setSettingsOpen(false)}/>)}+ {/*+ * The projects panel sits on the same level as the settings and+ * for the same reason: a reader opens it BECAUSE something is+ * missing (no project, a stale index), and it must not sit+ * behind what sent them there.+ */}+ {projectsOpen && (+ <ProjectsPanel+ project={project}+ source={projectsSource}+ onOpenProject={openProject}+ onClose={() => setProjectsOpen(false)}+ />+ )}</AtlasChrome>);}diff --git a/graph-ui/src/app/atlas-api.test.ts b/graph-ui/src/app/atlas-api.test.tsnew file mode 100644index 000000000..cd22c5af0--- /dev/null+++ b/graph-ui/src/app/atlas-api.test.ts@@ -0,0 +1,102 @@+/*+ * The /api client of the projects panel: which route, which method, which+ * body each call sends, and what it makes of the answer. A recording fetch+ * stands in for the server; nothing here touches the network.+ */++import { describe, expect, it } from 'vitest';++import { AtlasApi, AtlasApiError } from './atlas-api';++interface FetchCall {+ url: string;+ init: RequestInit | undefined;+}++function recordingFetch(+ reply: { ok?: boolean; status?: number; body: string },+ calls: FetchCall[],+): typeof globalThis.fetch {+ return ((url: string, init?: RequestInit) => {+ calls.push({ url, init });+ return Promise.resolve({+ ok: reply.ok ?? true,+ status: reply.status ?? 200,+ statusText: '',+ text: () => Promise.resolve(reply.body),+ });+ }) as unknown as typeof globalThis.fetch;+}++function api(reply: { ok?: boolean; status?: number; body: string }): { api: AtlasApi; calls: FetchCall[] } {+ const calls: FetchCall[] = [];+ return { api: new AtlasApi({ base: 'http://127.0.0.1:9749', fetch: recordingFetch(reply, calls) }), calls };+}++describe('AtlasApi, the projects routes', () => {+ it('starts an index job with a JSON body over POST', async () => {+ const { api: client, calls } = api({ status: 202, body: '{"status":"indexing","slot":1,"path":"/repo"}' });+ const started = await client.startIndex('/repo', 'repo');+ expect(started).toEqual({ slot: 1, path: '/repo' });+ expect(calls[0]?.url).toBe('http://127.0.0.1:9749/api/index');+ expect(calls[0]?.init?.method).toBe('POST');+ expect(calls[0]?.init?.body).toBe('{"root_path":"/repo","project_name":"repo"}');+ expect((calls[0]?.init?.headers as Record<string, string>)['Content-Type']).toBe('application/json');+ });++ it('reads the job table', async () => {+ const { api: client, calls } = api({ body: '[{"slot":0,"status":"done","path":"/a","error":""}]' });+ const jobs = await client.indexJobs();+ expect(jobs).toEqual([{ slot: 0, status: 'done', path: '/a', error: '' }]);+ expect(calls[0]?.url).toBe('http://127.0.0.1:9749/api/index-status');+ expect(calls[0]?.init?.method).toBe('GET');+ expect(calls[0]?.init?.body).toBeUndefined();+ });++ it('browses with the path in the query, and without one for the server root', async () => {+ const { api: client, calls } = api({ body: '{"path":"/Users/x","dirs":["a"],"parent":"/Users"}' });+ const level = await client.browse('/Users/x');+ expect(level.dirs).toEqual(['a']);+ expect(calls[0]?.url).toBe('http://127.0.0.1:9749/api/browse?path=%2FUsers%2Fx');+ await client.browse('');+ expect(calls[1]?.url).toBe('http://127.0.0.1:9749/api/browse');+ });++ it('deletes over DELETE with the name in the query', async () => {+ const { api: client, calls } = api({ body: '{"deleted":true}' });+ await client.deleteProject('my project');+ expect(calls[0]?.url).toBe('http://127.0.0.1:9749/api/project?name=my+project');+ expect(calls[0]?.init?.method).toBe('DELETE');+ });++ it('reads the health verdict', async () => {+ const { api: client, calls } = api({ body: '{"status":"healthy","nodes":1,"edges":2,"size_bytes":3}' });+ expect(await client.projectHealth('p')).toEqual({ status: 'healthy', nodes: 1, edges: 2, sizeBytes: 3, reason: '' });+ expect(calls[0]?.url).toBe('http://127.0.0.1:9749/api/project-health?name=p');+ });++ it('reads and stores the decision record', async () => {+ const { api: client, calls } = api({ body: '{"has_adr":true,"content":"# x","updated_at":"now"}' });+ expect(await client.adr('p')).toEqual({ hasAdr: true, content: '# x', updatedAt: 'now' });+ expect(calls[0]?.url).toBe('http://127.0.0.1:9749/api/adr?project=p');+ await client.saveAdr('p', '# y');+ expect(calls[1]?.url).toBe('http://127.0.0.1:9749/api/adr');+ expect(calls[1]?.init?.method).toBe('POST');+ expect(calls[1]?.init?.body).toBe('{"project":"p","content":"# y"}');+ });++ it('reads the log tail and the process report', async () => {+ const { api: client, calls } = api({ body: '{"lines":["a"],"total":9}' });+ expect(await client.logs(200)).toEqual({ lines: ['a'], total: 9 });+ expect(calls[0]?.url).toBe('http://127.0.0.1:9749/api/logs?lines=200');+ const processes = api({ body: '{"self_pid":7,"self_rss_mb":1.5,"processes":[]}' });+ expect(await processes.api.processes()).toEqual({ selfPid: 7, selfRssMb: 1.5, processes: [] });+ expect(processes.calls[0]?.url).toBe('http://127.0.0.1:9749/api/processes');+ });++ it('carries the status of a refusal, so busy can be told from forbidden', async () => {+ const { api: client } = api({ ok: false, status: 423, body: '{"error":"project is busy; retry after indexing"}' });+ await expect(client.saveAdr('p', 'x')).rejects.toSatisfy((error: unknown) =>+ error instanceof AtlasApiError && error.status === 423 && error.route === '/api/adr');+ });+});diff --git a/graph-ui/src/app/atlas-api.ts b/graph-ui/src/app/atlas-api.tsindex 473cf2cf3..8bd39986e 100644--- a/graph-ui/src/app/atlas-api.ts+++ b/graph-ui/src/app/atlas-api.ts@@ -21,6 +21,24 @@ import {readTraceAnswer,} from '../traces/trace-schemas';import type { FlowDetail, FlowSummary, TraceAnswer } from '../traces/trace-schemas';+import {+ readAdr,+ readBrowse,+ readHealth,+ readIndexJobs,+ readIndexStarted,+ readLogs,+ readProcesses,+} from '../projects/projects-model';+import type {+ AdrRecord,+ BrowseLevel,+ IndexJob,+ IndexStarted,+ LogTail,+ ProcessReport,+ ProjectHealth,+} from '../projects/projects-model';export interface AtlasApiOptions {/** Ursprung des Servers, ohne Schraegstrich am Ende. Leer heisst same-origin. */@@ -58,12 +76,27 @@ export class AtlasApi {constructor(private readonly options: AtlasApiOptions = {}) { }- private async getJson(route: string): Promise<unknown> {+ private getJson(route: string): Promise<unknown> {+ return this.request('GET', route);+ }++ /**+ * One request, any method. The writing routes of the projects panel+ * (POST /api/index, POST /api/adr, DELETE /api/project) go through here+ * with a JSON body; the error carries the status so a caller can tell+ * "busy, try later" (423) from "refused" (403) from "not there" (404).+ */+ private async request(method: 'GET' | 'POST' | 'DELETE', route: string, payload?: unknown): Promise<unknown> {const url = `${this.options.base ?? ''}${route}`;const doFetch = this.options.fetch ?? globalThis.fetch;let response: Response;try {- response = await doFetch(url, { headers: { Accept: 'application/json' } });+ const init: RequestInit = { method, headers: { Accept: 'application/json' } };+ if (payload !== undefined) {+ init.headers = { Accept: 'application/json', 'Content-Type': 'application/json' };+ init.body = JSON.stringify(payload);+ }+ response = await doFetch(url, init);} catch (error) {const message = error instanceof Error ? error.message : String(error);throw new AtlasApiError(route, 0, `${route} war nicht erreichbar: ${message}`);@@ -119,6 +152,60 @@ export class AtlasApi {return readFlowDetail(await this.getJson(`${FLOW_ROUTE}?${query.toString()}`));}+ // ------------------------------------------------ the projects panel --++ /** The folders under `path`; the server's own roots when `path` is empty. */+ async browse(path = ''): Promise<BrowseLevel> {+ const query = new URLSearchParams();+ if (path.length > 0) {+ query.set('path', path);+ }+ const suffix = path.length > 0 ? `?${query.toString()}` : '';+ return readBrowse(await this.getJson(`/api/browse${suffix}`));+ }++ /** Ask the server to index `rootPath` under `projectName`, in the background. */+ async startIndex(rootPath: string, projectName: string): Promise<IndexStarted> {+ return readIndexStarted(+ await this.request('POST', '/api/index', { root_path: rootPath, project_name: projectName }),+ );+ }++ /** Every index job the server has run since it started, with its state. */+ async indexJobs(): Promise<IndexJob[]> {+ return readIndexJobs(await this.getJson('/api/index-status'));+ }++ /** Remove the index file of a project. The repository itself is not touched. */+ async deleteProject(name: string): Promise<void> {+ await this.request('DELETE', `/api/project?${new URLSearchParams({ name }).toString()}`);+ }++ /** Does the index file open, and what does it hold. */+ async projectHealth(name: string): Promise<ProjectHealth> {+ return readHealth(await this.getJson(`/api/project-health?${new URLSearchParams({ name }).toString()}`));+ }++ /** The decision record the server keeps for a project. */+ async adr(project: string): Promise<AdrRecord> {+ return readAdr(await this.getJson(`/api/adr?${new URLSearchParams({ project }).toString()}`));+ }++ /** Store the decision record of a project. */+ async saveAdr(project: string, content: string): Promise<void> {+ await this.request('POST', '/api/adr', { project, content });+ }++ /** The last `lines` lines of the server log. */+ async logs(lines: number): Promise<LogTail> {+ return readLogs(await this.getJson(`/api/logs?${new URLSearchParams({ lines: String(lines) }).toString()}`));+ }++ /** The codebase-memory-mcp processes on this machine, as the server sees them. */+ async processes(): Promise<ProcessReport> {+ return readProcesses(await this.getJson('/api/processes'));+ }+/** Wurzelpfad, Branch und Remote eines Projekts. Leere Felder bleiben leer. */async repoInfo(project: string): Promise<RepoInfo> {const raw = await this.getJson(`/api/repo-info?${new URLSearchParams({ project }).toString()}`);diff --git a/graph-ui/src/app/shortcuts.ts b/graph-ui/src/app/shortcuts.tsindex f72945c42..02ede074b 100644--- a/graph-ui/src/app/shortcuts.ts+++ b/graph-ui/src/app/shortcuts.ts@@ -52,8 +52,9 @@ export interface AtlasShortcut {* dem 2026-08-29 ihre eigenen: `w` die Frage nach dem Warum, `b` den* BUG-Assistenten, `c` die Aenderungsansicht, `l` den Schalter des lokalen* Modells, `r` seit W8 den Weg zurueck zum Vorgabe-Layout, `s` seit W10 das- * Einstellungen-Panel, `g` seit W11a den Live-Modus der Agenten. `?` schlaegt- * seit W7a die Hilfe auf und wieder zu.+ * Einstellungen-Panel, `g` seit W11a den Live-Modus der Agenten, `p` das+ * Projekte-Panel (Index anlegen, entfernen, Entscheidungsakte, Serverzustand).+ * `?` schlaegt seit W7a die Hilfe auf und wieder zu.** Warum das vorher nicht so war und warum es jetzt so ist: die Zeile war ein* Menue, dessen Eintraege nur mit der Maus erreichbar waren, in einer@@ -67,7 +68,7 @@ export interface AtlasShortcut {* gepflegte Liste, denn eine gepflegte Liste ist genau die Stelle, an der ein* Punkt ohne Verdrahtung wieder hereinrutscht.*/-export const WIRED_MENU_SHORTCUTS: readonly string[] = ['a', 'w', 'b', 'c', 'l', 'r', 's', 'g', '?'];+export const WIRED_MENU_SHORTCUTS: readonly string[] = ['a', 'w', 'b', 'c', 'l', 'r', 's', 'g', 'p', '?'];/*** Das Alphabet, gegen das die beiden Absichtsfunktionen befragt werden.diff --git a/graph-ui/src/i18n/messages.ts b/graph-ui/src/i18n/messages.tsindex b359d12b5..8eb624aad 100644--- a/graph-ui/src/i18n/messages.ts+++ b/graph-ui/src/i18n/messages.ts@@ -116,6 +116,7 @@ export const messages = {impact: 'atlas: what a change would reach, and what covers it (alt+c)',helpOpen: 'help: what this reads, what it cannot do, and every key it listens to (?)',helpClose: 'help: close this page (?)',+ projects: 'atlas: what this server has indexed, index more, and what the server is doing (alt+p)',},/**@@ -155,15 +156,18 @@ export const messages = {limitsTitle: 'What it cannot do',limits: ['The reader is read-only: you cannot edit a file here, and what you type into it changes nothing.',- 'It cannot run code, and there is no terminal: no build, no test run, no shell, '- + 'no process started from this window.',+ 'It cannot run code, and there is no terminal: no build, no test run, no shell. '+ + 'The one job it can ask for is an index run, and the analysis server does that in its '+ + 'own process, from the [p]rojects panel.','It reaches no cloud. The only model it can use is a sidecar on this machine, '+ 'started by hand, and it stays off until it answers.',],limitsWhy:'That is the shape of the product and not a missing release: this surface has no backend of '- + 'its own, and the analysis server offers a read-only surface. Everything that writes, builds '- + 'or executes happens where the repository lives, on the command line.',+ + 'its own. Apart from the three requests the [p]rojects panel makes (index a repository, '+ + 'remove an index, store a decision record), the analysis server offers it a read-only '+ + 'surface, and everything that writes, builds or executes happens where the repository '+ + 'lives, on the command line.',panelsTitle: 'The panels, and what each one answers',panels: [@@ -181,6 +185,12 @@ export const messages = {'which model in your cache answers, how to get another one, and what the drawing '+ 'of the graph costs on this machine',},+ {+ name: '[p]rojects',+ answers:+ 'what this server has indexed, how to index or remove a repository, the decision '+ + 'record of the open project, and what the server is doing',+ },{name: 'command line',answers:@@ -278,6 +288,7 @@ export const messages = {'mnemonic:r': 'put every zone back to the width and height it starts with','mnemonic:s': 'open or close the settings: the model, and what the drawing costs','mnemonic:g': 'turn the live agent mode on or off. Off asks the bridge nothing at all',+ 'mnemonic:p': 'open or close the projects: what is indexed, index more, and what the server is doing','bare:?': 'open or close this page','line:/': 'put the cursor in the command line, without typing the slash itself','walk:Enter': 'go to the next step of the walk, and finish it on the last one',@@ -292,8 +303,9 @@ export const messages = {operationsTitle: 'Running it',operations: [- 'Index a project with the CLI of the analysis server, then open this page with the project '- + 'name in the address (?project=<name>). This window indexes nothing itself.',+ 'Index a project from the [p]rojects panel (alt+p) or with the CLI of the analysis server, '+ + 'then open it from that panel or with the project name in the address (?project=<name>). '+ + 'The server indexes; this window asks.','Start the local model with llm/start.sh class-a. It listens on the loopback address of this '+ 'machine; the [l]lm card turns green as soon as it answers, and says why when it does not.','Bring recorded runs in with ingest_traces on the command line. There is no importer on this '@@ -350,7 +362,7 @@ export const messages = {serverReady: 'ready',serverUnreachable: 'unreachable',noFileLoaded: 'no file loaded',- noProjectIndexed: 'no project: this server has nothing indexed',+ noProjectIndexed: 'no project: this server has nothing indexed. alt+p opens the projects panel to index one',noProjectError: (detail: string): string => `no project: ${detail}`,},@@ -954,6 +966,124 @@ export const messages = {+ 'not to build a menu that everything disappears into.',},+ /**+ * The projects panel: the one surface that asks the server to write.+ *+ * Its text lives here, like the settings panel's, because it speaks about+ * the product as a whole (what is indexed, what the server is doing) and+ * not about one subject area.+ */+ projects: {+ title: 'CODEATLAS PROJECTS',+ subtitle: 'what this server has indexed, and how to give it more',+ panelLabel: 'projects',+ close: '[esc] close',+ closeLabel: CLOSE,+ /** The entry in the atlas row. The letter sits in brackets. */+ menuLabel: '[p]rojects',++ /* ------------------------------------------------------- the list */++ listTitle: 'Projects on this server',+ listSource: 'read from list_projects over /rpc',+ listLoading: 'asking the server ...',+ listEmpty:+ 'nothing is indexed yet. Index a repository below, or on the command line: '+ + 'codebase-memory-mcp cli index_repository',+ listError: (detail: string): string => `the list did not arrive: ${detail}`,+ refresh: 'refresh',+ openNow: 'open now',+ open: 'open',+ openTitle: (name: string): string => `open ${name}: the page reloads with ?project=${name}`,+ counts: (nodes: number, edges: number): string => `${nodes} sym, ${edges} edg`,+ countsUnknown: 'counts not sent',+ check: 'check',+ checkTitle: 'GET /api/project-health: does the index file open, and what does it hold',+ healthHealthy: (nodes: number, edges: number, mb: string): string =>+ `healthy: ${nodes} symbols, ${edges} edges, ${mb} MB on disk`,+ healthMissing: 'missing: the server has no index file under this name',+ healthCorrupt: (reason: string): string => `corrupt: ${reason}`,+ healthUnknown: 'the server answered with a verdict this panel does not know',+ reindex: 'reindex',+ reindexTitle: (root: string): string => `POST /api/index for ${root}: rebuilds the index in the background`,+ noRoot: 'root path not sent by the server; reindex from the form below',+ remove: 'delete',+ removeTitle: 'DELETE /api/project: removes the index file, never the repository',+ removeArmed: (name: string): string =>+ `delete the index of ${name}? The repository on disk stays as it is.`,+ removeConfirm: 'yes, delete the index',+ cancel: 'cancel',+ removed: (name: string): string => `${name}: index deleted`,+ removeError: (detail: string): string => `not deleted: ${detail}`,++ /* ------------------------------------------------------- the form */++ indexTitle: 'Index a repository',+ indexIntro:+ 'The server does the indexing; this window only asks. The path has to be a folder the '+ + 'server may read (its workspace boundary applies), and the job runs in the background '+ + 'while you keep reading.',+ pathLabel: 'repository path',+ pathPlaceholder: '/absolute/path/to/repository',+ browse: 'browse',+ browseTitle: 'GET /api/browse: list the folders under this path',+ browseClose: 'close browser',+ browseAt: (path: string): string => `folders in ${path}`,+ browseUp: 'up one level',+ browseUse: 'use this folder',+ browseEmpty: 'no folders here',+ browseError: (detail: string): string => `browsing failed: ${detail}`,+ nameLabel: 'project name',+ nameHint: 'suggested from the last path segment; change it if you like',+ start: 'index',+ startTitle: 'POST /api/index: start a background job for this path',+ started: (path: string): string => `job accepted for ${path}; its state appears below`,+ startError: (detail: string): string => `the server refused: ${detail}`,+ jobsTitle: 'Index jobs since the server started',+ jobsSource: (seconds: string): string =>+ `read from GET /api/index-status, asked again every ${seconds} s while a job runs`,+ jobsNone: 'no job has run yet',+ jobIndexing: 'indexing',+ jobDone: 'done',+ jobError: (error: string): string => `failed: ${error}`,+ jobUnknown: 'state not known to this panel',++ /* -------------------------------------------------------- the adr */++ adrTitle: 'Decision record',+ adrIntro: (project: string): string =>+ `The architecture decision record the server keeps for ${project}, as markdown. Saving `+ + 'stores it in the project index; a reindex keeps it.',+ adrNoProject: 'open a project to read or write its decision record',+ adrLoading: 'reading ...',+ adrNone: 'no record yet; what you save here becomes the first one',+ adrUpdated: (at: string): string => `last saved ${at}`,+ adrLabel: 'decision record, markdown',+ adrSave: 'save',+ adrSaveTitle: 'POST /api/adr: store this text for the open project',+ adrSaved: 'saved',+ adrBusy: 'the project is being indexed right now; save again when the job is done',+ adrError: (detail: string): string => `not saved: ${detail}`,+ adrReadError: (detail: string): string => `the record did not arrive: ${detail}`,++ /* ----------------------------------------------------- the server */++ serverTitle: 'This server',+ processesSource: 'read from GET /api/processes',+ processesSelf: (pid: number, mb: string): string => `serving this page: pid ${pid}, ${mb} MB resident`,+ processesOthers: (count: number): string =>+ count === 1 ? 'one other codebase-memory-mcp process' : `${count} other codebase-memory-mcp processes`,+ processesNone: 'no other codebase-memory-mcp process is running',+ processRow: (pid: number, cpu: string, mb: string, elapsed: string): string =>+ `pid ${pid}: ${cpu}% cpu, ${mb} MB, up ${elapsed}`,+ processesError: (detail: string): string => `the process list did not arrive: ${detail}`,+ logsTitle: 'Log tail',+ logsSource: (shown: number, total: number): string => `read from GET /api/logs: ${shown} of ${total} lines`,+ logsEmpty: 'the log ring is empty',+ logsError: (detail: string): string => `the log did not arrive: ${detail}`,+ reload: 'reload',+ },+/** Der Rahmen des Twins. Seine Fakten-Saetze stehen in twin/strings.ts. */twin: {/** Das Etikett des Leseprofils, mit dem dieses Produkt startet. */diff --git a/graph-ui/src/projects/ProjectsPanel.test.tsx b/graph-ui/src/projects/ProjectsPanel.test.tsxnew file mode 100644index 000000000..889c42fd5--- /dev/null+++ b/graph-ui/src/projects/ProjectsPanel.test.tsx@@ -0,0 +1,341 @@+// @vitest-environment jsdom+/*+ * The projects panel in jsdom: what it shows from the server's answers, what+ * it asks the server when a control is used, and what it withholds.+ *+ * The three cases where the panel leaves something OUT are the ones a+ * screenshot cannot show:+ *+ * 1. The index button is absent until a path and a name are there.+ * 2. A project whose root the server did not send has no reindex button.+ * 3. Deleting asks in place first; the request goes out only on the answer.+ *+ * The server is a set of recorded functions. Nothing here touches a network,+ * and the poll interval is one millisecond so a finished job is seen without+ * waiting for the product's second and a half.+ */++import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import ProjectsPanel from './ProjectsPanel';+import type { ProjectsPanelProps, ProjectsSource } from './ProjectsPanel';+import type { IndexJob } from './projects-model';+import { AtlasApiError } from '../app/atlas-api';+import { messages } from '../i18n/messages';+import type { ProjectEntry } from '../provider/rpc-schemas';++let container: HTMLDivElement;+let root: Root;++const PROJECTS: ProjectEntry[] = [+ { name: 'atlas-sample', root_path: '/repos/atlas-sample', nodes: 76, edges: 179 },+ { name: 'rootless' },+];++function fakeSource(jobs: () => IndexJob[] = () => []): ProjectsSource & { calls: Record<string, unknown[][]> } {+ const calls: Record<string, unknown[][]> = {};+ const record = <T,>(name: string, impl: (...args: never[]) => T) => (...args: never[]): T => {+ (calls[name] ??= []).push(args);+ return impl(...args);+ };+ return {+ calls,+ listProjects: record('listProjects', async () => PROJECTS),+ projectHealth: record('projectHealth', async () => ({+ status: 'healthy' as const,+ nodes: 76,+ edges: 179,+ sizeBytes: 1572864,+ reason: '',+ })),+ deleteProject: record('deleteProject', async () => undefined),+ browse: record('browse', async (path: string) => ({+ path: path.length > 0 ? path : '/home',+ dirs: ['repo-a', 'repo-b'],+ parent: '/',+ roots: [],+ })),+ startIndex: record('startIndex', async (path: string) => ({ slot: 0, path })),+ indexJobs: record('indexJobs', async () => jobs()),+ adr: record('adr', async () => ({ hasAdr: true, content: '# old record', updatedAt: '2026-09-05 10:00' })),+ saveAdr: record('saveAdr', async () => undefined),+ logs: record('logs', async () => ({ lines: ['line one', 'line two'], total: 40 })),+ processes: record('processes', async () => ({+ selfPid: 42,+ selfRssMb: 120.5,+ processes: [+ { pid: 42, cpu: 0.2, rssMb: 120.5, elapsed: '00:10', command: 'codebase-memory-mcp', isSelf: true },+ { pid: 43, cpu: 12.5, rssMb: 900, elapsed: '01:00', command: 'codebase-memory-mcp', isSelf: false },+ ],+ })),+ };+}++beforeEach(() => {+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => {+ root.unmount();+ });+ container.remove();+});++/** Let every pending fetch answer and every effect after it run. */+async function settle(): Promise<void> {+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 5));+ });+}++async function render(overrides: Partial<ProjectsPanelProps> = {}): Promise<ProjectsPanelProps> {+ const props: ProjectsPanelProps = {+ project: 'atlas-sample',+ source: fakeSource(),+ onOpenProject: vi.fn(),+ onClose: vi.fn(),+ pollMs: 1,+ ...overrides,+ };+ await act(async () => {+ root.render(<ProjectsPanel {...props} />);+ });+ await settle();+ return props;+}++const byTestId = (id: string): HTMLElement | null => container.querySelector(`[data-testid="${id}"]`);+const allByTestId = (id: string): HTMLElement[] => [...container.querySelectorAll<HTMLElement>(`[data-testid="${id}"]`)];++async function click(element: HTMLElement | null): Promise<void> {+ expect(element, 'the control must exist').not.toBeNull();+ await act(async () => {+ element?.click();+ });+ await settle();+}++async function type(element: HTMLElement | null, value: string): Promise<void> {+ expect(element, 'the field must exist').not.toBeNull();+ const field = element as HTMLInputElement | HTMLTextAreaElement;+ const proto = field instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;+ Object.getOwnPropertyDescriptor(proto, 'value')?.set?.call(field, value);+ await act(async () => {+ field.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await settle();+}++describe('the list', () => {+ it('shows every project with its counts, marks the open one, and names its source', async () => {+ await render();+ const rows = allByTestId('atlas-projects-row');+ expect(rows.map((row) => row.dataset['project'])).toEqual(['atlas-sample', 'rootless']);+ expect(rows[0]?.dataset['open']).toBe('true');+ expect(rows[0]?.textContent).toContain(messages.projects.counts(76, 179));+ expect(rows[1]?.textContent).toContain(messages.projects.countsUnknown);+ expect(container.textContent).toContain(messages.projects.listSource);+ });++ it('offers open only for a project that is not open, and reindex only with a root', async () => {+ await render();+ const [open, rootless] = allByTestId('atlas-projects-row');+ expect(open?.querySelector('[data-testid="atlas-projects-open"]')).toBeNull();+ expect(rootless?.querySelector('[data-testid="atlas-projects-open"]')).not.toBeNull();+ expect(open?.querySelector('[data-testid="atlas-projects-reindex"]')).not.toBeNull();+ expect(rootless?.querySelector('[data-testid="atlas-projects-reindex"]')).toBeNull();+ expect(rootless?.textContent).toContain(messages.projects.noRoot);+ });++ it('says when nothing is indexed, and points at the form', async () => {+ const source = fakeSource();+ source.listProjects = async () => [];+ await render({ source, project: '' });+ expect(byTestId('atlas-projects-empty')?.textContent).toBe(messages.projects.listEmpty);+ expect(byTestId('atlas-projects-adr-none')?.textContent).toBe(messages.projects.adrNoProject);+ });++ it('hands the name to the window when open is pressed', async () => {+ const props = await render();+ await click(byTestId('atlas-projects-open'));+ expect(props.onOpenProject).toHaveBeenCalledWith('rootless');+ });++ it('asks for the health verdict on check and prints it as a sentence', async () => {+ const props = await render();+ await click(allByTestId('atlas-projects-check')[0] ?? null);+ expect((props.source as ReturnType<typeof fakeSource>).calls['projectHealth']).toEqual([['atlas-sample']]);+ expect(byTestId('atlas-projects-health')?.textContent).toBe(messages.projects.healthHealthy(76, 179, '1.5'));+ });++ it('reindexes with the root the server sent', async () => {+ const props = await render();+ await click(byTestId('atlas-projects-reindex'));+ expect((props.source as ReturnType<typeof fakeSource>).calls['startIndex']).toEqual([['/repos/atlas-sample', 'atlas-sample']]);+ });++ it('deletes only after the question in place is answered, then reloads the list', async () => {+ const props = await render();+ const source = props.source as ReturnType<typeof fakeSource>;+ await click(allByTestId('atlas-projects-remove')[1] ?? null);+ expect(byTestId('atlas-projects-armed')?.textContent).toContain(messages.projects.removeArmed('rootless'));+ expect(source.calls['deleteProject']).toBeUndefined();++ await click(byTestId('atlas-projects-remove-cancel'));+ expect(byTestId('atlas-projects-armed')).toBeNull();+ expect(source.calls['deleteProject']).toBeUndefined();++ await click(allByTestId('atlas-projects-remove')[1] ?? null);+ const listReads = source.calls['listProjects']?.length ?? 0;+ await click(byTestId('atlas-projects-remove-confirm'));+ expect(source.calls['deleteProject']).toEqual([['rootless']]);+ expect(source.calls['listProjects']?.length).toBe(listReads + 1);+ expect(byTestId('atlas-projects-list-notice')?.textContent).toBe(messages.projects.removed('rootless'));+ });+});++describe('the form', () => {+ it('suggests the name from the path and shows the index button only once both are there', async () => {+ await render();+ expect(byTestId('atlas-projects-start')).toBeNull();+ await type(byTestId('atlas-projects-path'), '/repos/new-thing/');+ expect((byTestId('atlas-projects-name') as HTMLInputElement).value).toBe('new-thing');+ expect(byTestId('atlas-projects-start')).not.toBeNull();+ await type(byTestId('atlas-projects-name'), '');+ expect(byTestId('atlas-projects-start')).toBeNull();+ });++ it('keeps a name the reader typed when the path changes again', async () => {+ await render();+ await type(byTestId('atlas-projects-path'), '/repos/one');+ await type(byTestId('atlas-projects-name'), 'chosen');+ await type(byTestId('atlas-projects-path'), '/repos/two');+ expect((byTestId('atlas-projects-name') as HTMLInputElement).value).toBe('chosen');+ });++ it('starts the job, shows the acknowledgement, polls while it runs, and reloads the list when it is done', async () => {+ let status: IndexJob['status'] = 'indexing';+ const source = fakeSource(() => [{ slot: 0, status, path: '/repos/new-thing', error: '' }]);+ const props = await render({ source });+ await type(byTestId('atlas-projects-path'), '/repos/new-thing');+ await click(byTestId('atlas-projects-start'));+ expect(source.calls['startIndex']).toEqual([['/repos/new-thing', 'new-thing']]);+ expect(byTestId('atlas-projects-start-notice')?.textContent).toBe(messages.projects.started('/repos/new-thing'));+ expect(allByTestId('atlas-projects-job')[0]?.dataset['status']).toBe('indexing');++ const polled = source.calls['indexJobs']?.length ?? 0;+ const listReads = source.calls['listProjects']?.length ?? 0;+ status = 'done';+ await settle();+ await settle();+ expect(source.calls['indexJobs']?.length).toBeGreaterThan(polled);+ expect(allByTestId('atlas-projects-job')[0]?.dataset['status']).toBe('done');+ expect(source.calls['listProjects']?.length).toBe(listReads + 1);+ void props;+ });++ it('shows the server refusal as it came', async () => {+ const source = fakeSource();+ source.startIndex = async () => {+ throw new AtlasApiError('/api/index', 403, 'root outside the workspace');+ };+ await render({ source });+ await type(byTestId('atlas-projects-path'), '/elsewhere');+ await click(byTestId('atlas-projects-start'));+ expect(byTestId('atlas-projects-start-notice')?.textContent).toBe(+ messages.projects.startError('root outside the workspace'),+ );+ });++ it('browses folders and puts the chosen one into the path', async () => {+ const props = await render();+ await click(byTestId('atlas-projects-browse'));+ expect(byTestId('atlas-projects-browse-level')?.textContent).toContain(messages.projects.browseAt('/home'));+ expect(allByTestId('atlas-projects-browse-dir').map((entry) => entry.textContent)).toEqual(['repo-a', 'repo-b']);+ await click(allByTestId('atlas-projects-browse-dir')[1] ?? null);+ expect((props.source as ReturnType<typeof fakeSource>).calls['browse']).toEqual([[''], ['/home/repo-b']]);+ await click(byTestId('atlas-projects-browse-use'));+ expect((byTestId('atlas-projects-path') as HTMLInputElement).value).toBe('/home/repo-b');+ expect((byTestId('atlas-projects-name') as HTMLInputElement).value).toBe('repo-b');+ expect(byTestId('atlas-projects-browse-level')).toBeNull();+ });+});++describe('the decision record', () => {+ it('loads the record of the open project into the editor and saves what was typed', async () => {+ const props = await render();+ const source = props.source as ReturnType<typeof fakeSource>;+ expect(byTestId('atlas-projects-adr-state')?.textContent).toBe(messages.projects.adrUpdated('2026-09-05 10:00'));+ expect((byTestId('atlas-projects-adr-text') as HTMLTextAreaElement).value).toBe('# old record');+ await type(byTestId('atlas-projects-adr-text'), '# new record');+ await click(byTestId('atlas-projects-adr-save'));+ expect(source.calls['saveAdr']).toEqual([['atlas-sample', '# new record']]);+ expect(byTestId('atlas-projects-adr-notice')?.textContent).toBe(messages.projects.adrSaved);+ });++ it('says busy when the server is indexing, and refused otherwise', async () => {+ const source = fakeSource();+ source.saveAdr = async () => {+ throw new AtlasApiError('/api/adr', 423, 'project is busy');+ };+ await render({ source });+ await click(byTestId('atlas-projects-adr-save'));+ expect(byTestId('atlas-projects-adr-notice')?.textContent).toBe(messages.projects.adrBusy);+ });++ it('names the absence of a record instead of showing an empty timestamp', async () => {+ const source = fakeSource();+ source.adr = async () => ({ hasAdr: false, content: '', updatedAt: '' });+ await render({ source });+ expect(byTestId('atlas-projects-adr-state')?.textContent).toBe(messages.projects.adrNone);+ });+});++describe('the server block', () => {+ it('shows the serving process, the others, and the log tail with its source', async () => {+ await render();+ expect(byTestId('atlas-projects-processes')?.textContent).toContain(messages.projects.processesSelf(42, '120.5'));+ expect(allByTestId('atlas-projects-process').map((entry) => entry.textContent)).toEqual([+ messages.projects.processRow(43, '12.5', '900.0', '01:00'),+ ]);+ expect(byTestId('atlas-projects-logs')?.textContent).toBe('line one\nline two');+ expect(container.textContent).toContain(messages.projects.logsSource(2, 40));+ });++ it('asks again on reload', async () => {+ const props = await render();+ const source = props.source as ReturnType<typeof fakeSource>;+ const before = source.calls['logs']?.length ?? 0;+ await click(byTestId('atlas-projects-server-reload'));+ expect(source.calls['logs']?.length).toBe(before + 1);+ expect(source.calls['processes']?.length).toBe(before + 1);+ });+});++describe('the frame', () => {+ it('closes on escape and on the close button', async () => {+ const props = await render();+ await act(async () => {+ byTestId('atlas-projects')?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));+ });+ expect(props.onClose).toHaveBeenCalledTimes(1);+ await click(byTestId('atlas-projects-close'));+ expect(props.onClose).toHaveBeenCalledTimes(2);+ });++ it('carries every section a reader can look for', async () => {+ await render();+ expect(allByTestId('atlas-projects-section').map((section) => section.dataset['section'])).toEqual([+ 'list',+ 'index',+ 'adr',+ 'server',+ ]);+ });+});diff --git a/graph-ui/src/projects/ProjectsPanel.tsx b/graph-ui/src/projects/ProjectsPanel.tsxnew file mode 100644index 000000000..e45d95d8b--- /dev/null+++ b/graph-ui/src/projects/ProjectsPanel.tsx@@ -0,0 +1,817 @@+/**+ * The projects panel: what this server has indexed, how to give it more, and+ * what the server is doing.+ *+ * It is the one surface of this frontend that asks the server to write, and+ * it says so in every place where it does: index a repository (POST+ * /api/index), remove an index (DELETE /api/project), store a decision record+ * (POST /api/adr). The server does the work in its own process; this window+ * only asks, then reads the answer back through the same routes it would read+ * anyway.+ *+ * Three rules shape it, and they are the rules of the rest of this surface:+ *+ * 1. **Every block names its source.** The list says it comes from+ * list_projects, the jobs say they come from /api/index-status, and a+ * number the server did not send is shown as not sent, never as zero.+ * 2. **A control that cannot act is not on the screen.** The index button+ * appears once a path and a name are there; a project whose root the+ * server did not report has no reindex button and a sentence instead.+ * 3. **Deleting takes two steps, in place.** No browser dialog: the row turns+ * into the question, with the answer and the way back next to it.+ *+ * Why this panel exists at all, given that the help page describes a+ * read-only product: the previous frontend of this repository let a reader+ * index a project from the browser, and the first thing a new install shows is+ * a server with nothing indexed. Sending that reader to the command line would+ * be a capability the replacement took away. The panel keeps it, and keeps the+ * writing confined to these three requests.+ */++import { useCallback, useEffect, useRef, useState } from 'react';+import type { JSX, ReactNode } from 'react';++import { AtlasApiError } from '../app/atlas-api';+import { messages } from '../i18n/messages';+import type { ProjectEntry } from '../provider/rpc-schemas';+import { anyIndexing, childPath, finishedSince, megabytes, projectNameFor } from './projects-model';+import type {+ AdrRecord,+ BrowseLevel,+ IndexJob,+ IndexStarted,+ LogTail,+ ProcessReport,+ ProjectHealth,+} from './projects-model';++const text = messages.projects;++/** How often the job table is read while a job runs. */+export const POLL_MS = 1500;++/** How much of the log the panel asks for. */+export const LOG_LINES = 200;++/**+ * Everything the panel asks the server, as functions and not as a client, so+ * a test can hand in answers without a network and App can bind the list to+ * /rpc and the rest to /api.+ */+export interface ProjectsSource {+ listProjects(): Promise<ProjectEntry[]>;+ projectHealth(name: string): Promise<ProjectHealth>;+ deleteProject(name: string): Promise<void>;+ browse(path: string): Promise<BrowseLevel>;+ startIndex(rootPath: string, projectName: string): Promise<IndexStarted>;+ indexJobs(): Promise<IndexJob[]>;+ adr(project: string): Promise<AdrRecord>;+ saveAdr(project: string, content: string): Promise<void>;+ logs(lines: number): Promise<LogTail>;+ processes(): Promise<ProcessReport>;+}++export interface ProjectsPanelProps {+ /** The project this window has open; empty when none is. */+ project: string;+ source: ProjectsSource;+ /** Called with a project name when the reader wants to open it here. */+ onOpenProject: (name: string) => void;+ onClose: () => void;+ /** The polling interval, so a test does not have to wait a second and a half. */+ pollMs?: number;+}++function describeError(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++function Section(props: { name: string; title: string; source?: string; children: ReactNode }): JSX.Element {+ return (+ <section+ className="atlas-projects-section"+ data-testid="atlas-projects-section"+ data-section={props.name}+ >+ <h3 className="atlas-projects-section-title">{props.title}</h3>+ {props.source !== undefined && (+ <p className="atlas-projects-source" data-testid="atlas-projects-source">{props.source}</p>+ )}+ {props.children}+ </section>+ );+}++type HealthState = ProjectHealth | 'asking';++function healthSentence(health: ProjectHealth): string {+ switch (health.status) {+ case 'healthy':+ return text.healthHealthy(+ health.nodes ?? 0,+ health.edges ?? 0,+ megabytes(health.sizeBytes ?? 0),+ );+ case 'missing':+ return text.healthMissing;+ case 'corrupt':+ return text.healthCorrupt(health.reason);+ default:+ return text.healthUnknown;+ }+}++function jobSentence(job: IndexJob): string {+ switch (job.status) {+ case 'indexing':+ return text.jobIndexing;+ case 'done':+ return text.jobDone;+ case 'error':+ return text.jobError(job.error);+ default:+ return text.jobUnknown;+ }+}++export default function ProjectsPanel(props: ProjectsPanelProps): JSX.Element {+ const { source, project } = props;+ const pollMs = props.pollMs ?? POLL_MS;+ const root = useRef<HTMLDivElement | null>(null);+ const mounted = useRef(true);++ // ------------------------------------------------------------ the list --+ const [projects, setProjects] = useState<ProjectEntry[] | undefined>(undefined);+ const [listError, setListError] = useState('');+ const [listNotice, setListNotice] = useState('');+ const [health, setHealth] = useState<Record<string, HealthState>>({});+ const [armed, setArmed] = useState('');++ // ------------------------------------------------------------ the form --+ const [path, setPath] = useState('');+ const [name, setName] = useState('');+ const [nameTouched, setNameTouched] = useState(false);+ const [browseLevel, setBrowseLevel] = useState<BrowseLevel | undefined>(undefined);+ const [browseError, setBrowseError] = useState('');+ const [startNotice, setStartNotice] = useState('');+ const [jobs, setJobs] = useState<IndexJob[]>([]);+ const jobsRef = useRef<IndexJob[]>([]);++ // ------------------------------------------------------------- the adr --+ const [adr, setAdr] = useState<{ state: 'idle' | 'loading' | 'ready' | 'error'; record?: AdrRecord; detail: string }>({+ state: 'idle',+ detail: '',+ });+ const [adrDraft, setAdrDraft] = useState('');+ const [adrNotice, setAdrNotice] = useState('');++ // ---------------------------------------------------------- the server --+ const [processes, setProcesses] = useState<ProcessReport | undefined>(undefined);+ const [processesError, setProcessesError] = useState('');+ const [logs, setLogs] = useState<LogTail | undefined>(undefined);+ const [logsError, setLogsError] = useState('');++ useEffect(() => {+ mounted.current = true;+ root.current?.focus();+ return () => {+ mounted.current = false;+ };+ }, []);++ const loadProjects = useCallback(async () => {+ try {+ const list = await source.listProjects();+ if (!mounted.current) {+ return;+ }+ setProjects(list);+ setListError('');+ } catch (error) {+ if (mounted.current) {+ setListError(text.listError(describeError(error)));+ }+ }+ }, [source]);++ const loadJobs = useCallback(async () => {+ try {+ const next = await source.indexJobs();+ if (!mounted.current) {+ return;+ }+ const finished = finishedSince(jobsRef.current, next);+ jobsRef.current = next;+ setJobs(next);+ if (finished.length > 0) {+ void loadProjects();+ }+ } catch {+ /* The job table is a courtesy while something runs; its absence is+ * visible as an unchanged list, and the next poll asks again. */+ }+ }, [source, loadProjects]);++ const loadAdr = useCallback(async () => {+ if (project.length === 0) {+ setAdr({ state: 'idle', detail: '' });+ setAdrDraft('');+ return;+ }+ setAdr({ state: 'loading', detail: '' });+ try {+ const record = await source.adr(project);+ if (!mounted.current) {+ return;+ }+ setAdr({ state: 'ready', record, detail: '' });+ setAdrDraft(record.content);+ } catch (error) {+ if (mounted.current) {+ setAdr({ state: 'error', detail: text.adrReadError(describeError(error)) });+ }+ }+ }, [source, project]);++ const loadServer = useCallback(async () => {+ try {+ const report = await source.processes();+ if (mounted.current) {+ setProcesses(report);+ setProcessesError('');+ }+ } catch (error) {+ if (mounted.current) {+ setProcessesError(text.processesError(describeError(error)));+ }+ }+ try {+ const tail = await source.logs(LOG_LINES);+ if (mounted.current) {+ setLogs(tail);+ setLogsError('');+ }+ } catch (error) {+ if (mounted.current) {+ setLogsError(text.logsError(describeError(error)));+ }+ }+ }, [source]);++ useEffect(() => {+ void loadProjects();+ void loadJobs();+ void loadServer();+ }, [loadProjects, loadJobs, loadServer]);++ useEffect(() => {+ void loadAdr();+ }, [loadAdr]);++ // The poll runs only while a job runs: an idle panel sends nothing.+ useEffect(() => {+ if (!anyIndexing(jobs)) {+ return undefined;+ }+ const timer = window.setTimeout(() => {+ void loadJobs();+ }, pollMs);+ return () => window.clearTimeout(timer);+ }, [jobs, pollMs, loadJobs]);++ // ------------------------------------------------------------ actions --++ const check = async (entry: ProjectEntry): Promise<void> => {+ setHealth((current) => ({ ...current, [entry.name]: 'asking' }));+ try {+ const verdict = await source.projectHealth(entry.name);+ if (mounted.current) {+ setHealth((current) => ({ ...current, [entry.name]: verdict }));+ }+ } catch (error) {+ if (mounted.current) {+ setHealth((current) => ({+ ...current,+ [entry.name]: { status: 'unknown', reason: describeError(error) },+ }));+ }+ }+ };++ const remove = async (entry: ProjectEntry): Promise<void> => {+ setArmed('');+ try {+ await source.deleteProject(entry.name);+ if (!mounted.current) {+ return;+ }+ setListNotice(text.removed(entry.name));+ setHealth((current) => {+ const next = { ...current };+ delete next[entry.name];+ return next;+ });+ void loadProjects();+ } catch (error) {+ if (mounted.current) {+ setListNotice(text.removeError(describeError(error)));+ }+ }+ };++ const start = async (rootPath: string, projectName: string): Promise<void> => {+ try {+ const started = await source.startIndex(rootPath, projectName);+ if (!mounted.current) {+ return;+ }+ setStartNotice(text.started(started.path.length > 0 ? started.path : rootPath));+ void loadJobs();+ } catch (error) {+ if (mounted.current) {+ setStartNotice(text.startError(describeError(error)));+ }+ }+ };++ const browse = async (at: string): Promise<void> => {+ try {+ const level = await source.browse(at);+ if (mounted.current) {+ setBrowseLevel(level);+ setBrowseError('');+ }+ } catch (error) {+ if (mounted.current) {+ setBrowseError(text.browseError(describeError(error)));+ }+ }+ };++ const changePath = (value: string): void => {+ setPath(value);+ if (!nameTouched) {+ setName(projectNameFor(value));+ }+ };++ const useFolder = (folder: string): void => {+ changePath(folder);+ setBrowseLevel(undefined);+ };++ const saveAdr = async (): Promise<void> => {+ try {+ await source.saveAdr(project, adrDraft);+ if (!mounted.current) {+ return;+ }+ setAdrNotice(text.adrSaved);+ void loadAdr();+ } catch (error) {+ if (!mounted.current) {+ return;+ }+ if (error instanceof AtlasApiError && error.status === 423) {+ setAdrNotice(text.adrBusy);+ } else {+ setAdrNotice(text.adrError(describeError(error)));+ }+ }+ };++ const canStart = path.trim().length > 0 && name.trim().length > 0;+ const others = processes?.processes.filter((entry) => !entry.isSelf) ?? [];++ return (+ <div+ className="atlas-projects"+ data-testid="atlas-projects"+ role="dialog"+ aria-label={text.panelLabel}+ aria-modal="false"+ tabIndex={-1}+ ref={root}+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ props.onClose();+ }+ }}+ >+ <header className="atlas-projects-head">+ <span className="atlas-projects-title" data-testid="atlas-projects-title">+ {text.title}+ </span>+ <span className="atlas-projects-subtitle">{text.subtitle}</span>+ <button+ type="button"+ className="atlas-projects-close"+ data-testid="atlas-projects-close"+ aria-label={text.closeLabel}+ onClick={props.onClose}+ >+ {text.close}+ </button>+ </header>++ {/* ------------------------------------------------- the list */}+ <Section name="list" title={text.listTitle} source={text.listSource}>+ {listError.length > 0 && (+ <p className="atlas-projects-notice" data-testid="atlas-projects-list-error">{listError}</p>+ )}+ {projects === undefined && listError.length === 0 && (+ <p className="atlas-projects-text">{text.listLoading}</p>+ )}+ {projects !== undefined && projects.length === 0 && (+ <p className="atlas-projects-text" data-testid="atlas-projects-empty">{text.listEmpty}</p>+ )}+ {projects !== undefined && projects.length > 0 && (+ <ul className="atlas-projects-list" data-testid="atlas-projects-list">+ {projects.map((entry) => {+ const verdict = health[entry.name];+ const isOpen = entry.name === project;+ const isArmed = armed === entry.name;+ return (+ <li+ key={entry.name}+ className="atlas-projects-row"+ data-testid="atlas-projects-row"+ data-project={entry.name}+ data-open={isOpen}+ >+ <div className="atlas-projects-row-line">+ <span className="atlas-projects-row-name">{entry.name}</span>+ <span className="atlas-projects-row-meta">+ {entry.nodes !== undefined && entry.edges !== undefined+ ? text.counts(entry.nodes, entry.edges)+ : text.countsUnknown}+ </span>+ {isOpen && <span className="atlas-projects-row-open">{text.openNow}</span>}+ </div>+ {entry.root_path !== undefined && entry.root_path.length > 0 && (+ <div className="atlas-projects-row-path">{entry.root_path}</div>+ )}+ {!isArmed && (+ <div className="atlas-projects-row-actions">+ {!isOpen && (+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-open"+ title={text.openTitle(entry.name)}+ onClick={() => props.onOpenProject(entry.name)}+ >+ {text.open}+ </button>+ )}+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-check"+ title={text.checkTitle}+ onClick={() => {+ void check(entry);+ }}+ >+ {text.check}+ </button>+ {entry.root_path !== undefined && entry.root_path.length > 0 ? (+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-reindex"+ title={text.reindexTitle(entry.root_path)}+ onClick={() => {+ void start(entry.root_path ?? '', entry.name);+ }}+ >+ {text.reindex}+ </button>+ ) : (+ <span className="atlas-projects-row-note">{text.noRoot}</span>+ )}+ <button+ type="button"+ className="atlas-projects-action"+ data-danger="true"+ data-testid="atlas-projects-remove"+ title={text.removeTitle}+ onClick={() => setArmed(entry.name)}+ >+ {text.remove}+ </button>+ </div>+ )}+ {isArmed && (+ <div className="atlas-projects-armed" data-testid="atlas-projects-armed">+ <span>{text.removeArmed(entry.name)}</span>+ <button+ type="button"+ className="atlas-projects-action"+ data-danger="true"+ data-testid="atlas-projects-remove-confirm"+ onClick={() => {+ void remove(entry);+ }}+ >+ {text.removeConfirm}+ </button>+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-remove-cancel"+ onClick={() => setArmed('')}+ >+ {text.cancel}+ </button>+ </div>+ )}+ {verdict !== undefined && (+ <div className="atlas-projects-row-health" data-testid="atlas-projects-health">+ {verdict === 'asking' ? text.listLoading : healthSentence(verdict)}+ </div>+ )}+ </li>+ );+ })}+ </ul>+ )}+ {listNotice.length > 0 && (+ <p className="atlas-projects-notice" data-testid="atlas-projects-list-notice">{listNotice}</p>+ )}+ <div className="atlas-projects-row-actions">+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-refresh"+ onClick={() => {+ void loadProjects();+ }}+ >+ {text.refresh}+ </button>+ </div>+ </Section>++ {/* ------------------------------------------------- the form */}+ <Section name="index" title={text.indexTitle}>+ <p className="atlas-projects-text">{text.indexIntro}</p>+ <div className="atlas-projects-form">+ <label className="atlas-projects-field">+ <span className="atlas-projects-label">{text.pathLabel}</span>+ <input+ className="atlas-projects-input"+ data-testid="atlas-projects-path"+ value={path}+ placeholder={text.pathPlaceholder}+ spellCheck={false}+ onChange={(event) => changePath(event.target.value)}+ />+ </label>+ <label className="atlas-projects-field">+ <span className="atlas-projects-label">{text.nameLabel}</span>+ <input+ className="atlas-projects-input"+ data-testid="atlas-projects-name"+ value={name}+ spellCheck={false}+ onChange={(event) => {+ setName(event.target.value);+ setNameTouched(true);+ }}+ />+ <span className="atlas-projects-note">{text.nameHint}</span>+ </label>+ <div className="atlas-projects-row-actions">+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-browse"+ title={text.browseTitle}+ onClick={() => {+ void browse(path.trim());+ }}+ >+ {text.browse}+ </button>+ {canStart && (+ <button+ type="button"+ className="atlas-projects-action"+ data-primary="true"+ data-testid="atlas-projects-start"+ title={text.startTitle}+ onClick={() => {+ void start(path.trim(), name.trim());+ }}+ >+ {text.start}+ </button>+ )}+ </div>+ {startNotice.length > 0 && (+ <p className="atlas-projects-notice" data-testid="atlas-projects-start-notice">{startNotice}</p>+ )}+ {browseError.length > 0 && (+ <p className="atlas-projects-notice" data-testid="atlas-projects-browse-error">{browseError}</p>+ )}+ {browseLevel !== undefined && (+ <div className="atlas-projects-browse" data-testid="atlas-projects-browse-level">+ <div className="atlas-projects-browse-head">+ <span>{text.browseAt(browseLevel.path)}</span>+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-browse-up"+ onClick={() => {+ void browse(browseLevel.parent);+ }}+ >+ {text.browseUp}+ </button>+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-browse-use"+ onClick={() => useFolder(browseLevel.path)}+ >+ {text.browseUse}+ </button>+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-browse-close"+ onClick={() => setBrowseLevel(undefined)}+ >+ {text.browseClose}+ </button>+ </div>+ {browseLevel.roots.length > 0 && (+ <ul className="atlas-projects-browse-list">+ {browseLevel.roots.map((entry) => (+ <li key={entry}>+ <button+ type="button"+ className="atlas-projects-browse-dir"+ onClick={() => {+ void browse(entry);+ }}+ >+ {entry}+ </button>+ </li>+ ))}+ </ul>+ )}+ {browseLevel.dirs.length === 0 ? (+ <p className="atlas-projects-note">{text.browseEmpty}</p>+ ) : (+ <ul className="atlas-projects-browse-list" data-testid="atlas-projects-browse-dirs">+ {browseLevel.dirs.map((entry) => (+ <li key={entry}>+ <button+ type="button"+ className="atlas-projects-browse-dir"+ data-testid="atlas-projects-browse-dir"+ onClick={() => {+ void browse(childPath(browseLevel, entry));+ }}+ >+ {entry}+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ </div>+ <h4 className="atlas-projects-subtitle-inline">{text.jobsTitle}</h4>+ <p className="atlas-projects-source">{text.jobsSource((pollMs / 1000).toFixed(1))}</p>+ {jobs.length === 0 ? (+ <p className="atlas-projects-note" data-testid="atlas-projects-jobs-none">{text.jobsNone}</p>+ ) : (+ <ul className="atlas-projects-jobs" data-testid="atlas-projects-jobs">+ {jobs.map((job) => (+ <li+ key={job.slot}+ className="atlas-projects-job"+ data-testid="atlas-projects-job"+ data-status={job.status}+ >+ <span className="atlas-projects-job-path">{job.path}</span>+ <span className="atlas-projects-job-state">{jobSentence(job)}</span>+ </li>+ ))}+ </ul>+ )}+ </Section>++ {/* -------------------------------------------------- the adr */}+ <Section name="adr" title={text.adrTitle}>+ {project.length === 0 && (+ <p className="atlas-projects-text" data-testid="atlas-projects-adr-none">{text.adrNoProject}</p>+ )}+ {project.length > 0 && (+ <>+ <p className="atlas-projects-text">{text.adrIntro(project)}</p>+ {adr.state === 'loading' && <p className="atlas-projects-note">{text.adrLoading}</p>}+ {adr.state === 'error' && (+ <p className="atlas-projects-notice" data-testid="atlas-projects-adr-error">{adr.detail}</p>+ )}+ {adr.state === 'ready' && (+ <>+ <p className="atlas-projects-note" data-testid="atlas-projects-adr-state">+ {adr.record?.hasAdr === true+ ? text.adrUpdated(adr.record.updatedAt)+ : text.adrNone}+ </p>+ <textarea+ className="atlas-projects-adr-text"+ data-testid="atlas-projects-adr-text"+ aria-label={text.adrLabel}+ value={adrDraft}+ spellCheck={false}+ onChange={(event) => {+ setAdrDraft(event.target.value);+ setAdrNotice('');+ }}+ />+ <div className="atlas-projects-row-actions">+ <button+ type="button"+ className="atlas-projects-action"+ data-primary="true"+ data-testid="atlas-projects-adr-save"+ title={text.adrSaveTitle}+ onClick={() => {+ void saveAdr();+ }}+ >+ {text.adrSave}+ </button>+ {adrNotice.length > 0 && (+ <span className="atlas-projects-note" data-testid="atlas-projects-adr-notice">+ {adrNotice}+ </span>+ )}+ </div>+ </>+ )}+ </>+ )}+ </Section>++ {/* ------------------------------------------------ the server */}+ <Section name="server" title={text.serverTitle} source={text.processesSource}>+ {processesError.length > 0 && <p className="atlas-projects-notice">{processesError}</p>}+ {processes !== undefined && (+ <div className="atlas-projects-procs" data-testid="atlas-projects-processes">+ <p className="atlas-projects-text">+ {text.processesSelf(processes.selfPid, processes.selfRssMb.toFixed(1))}+ </p>+ <p className="atlas-projects-note">+ {others.length === 0 ? text.processesNone : text.processesOthers(others.length)}+ </p>+ {others.length > 0 && (+ <ul className="atlas-projects-proc-list">+ {others.map((entry) => (+ <li key={entry.pid} data-testid="atlas-projects-process">+ {text.processRow(entry.pid, entry.cpu.toFixed(1), entry.rssMb.toFixed(1), entry.elapsed)}+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ <h4 className="atlas-projects-subtitle-inline">{text.logsTitle}</h4>+ {logsError.length > 0 && <p className="atlas-projects-notice">{logsError}</p>}+ {logs !== undefined && (+ <>+ <p className="atlas-projects-source">{text.logsSource(logs.lines.length, logs.total)}</p>+ {logs.lines.length === 0 ? (+ <p className="atlas-projects-note">{text.logsEmpty}</p>+ ) : (+ <pre className="atlas-projects-logs" data-testid="atlas-projects-logs">+ {logs.lines.join('\n')}+ </pre>+ )}+ </>+ )}+ <div className="atlas-projects-row-actions">+ <button+ type="button"+ className="atlas-projects-action"+ data-testid="atlas-projects-server-reload"+ onClick={() => {+ void loadServer();+ }}+ >+ {text.reload}+ </button>+ </div>+ </Section>+ </div>+ );+}diff --git a/graph-ui/src/projects/projects-model.test.ts b/graph-ui/src/projects/projects-model.test.tsnew file mode 100644index 000000000..888b26afa--- /dev/null+++ b/graph-ui/src/projects/projects-model.test.ts@@ -0,0 +1,190 @@+/*+ * The readers of the projects panel: what they keep, what they refuse, and+ * the two decisions the panel makes on top of them (when a job has finished,+ * which name a path suggests).+ */++import { describe, expect, it } from 'vitest';++import {+ anyIndexing,+ childPath,+ finishedSince,+ megabytes,+ projectHref,+ projectNameFor,+ readAdr,+ readBrowse,+ readHealth,+ readIndexJobs,+ readIndexStarted,+ readLogs,+ readProcesses,+} from './projects-model';++describe('readIndexJobs', () => {+ it('reads the job table as the server writes it', () => {+ const jobs = readIndexJobs([+ { slot: 0, status: 'indexing', path: '/repo/a', error: '' },+ { slot: 1, status: 'done', path: '/repo/b', error: '' },+ { slot: 2, status: 'error', path: '/repo/c', error: 'parse failed' },+ ]);+ expect(jobs).toEqual([+ { slot: 0, status: 'indexing', path: '/repo/a', error: '' },+ { slot: 1, status: 'done', path: '/repo/b', error: '' },+ { slot: 2, status: 'error', path: '/repo/c', error: 'parse failed' },+ ]);+ });++ it('names a status it does not know instead of guessing one', () => {+ expect(readIndexJobs([{ slot: 0, status: 'queued', path: '/x', error: '' }])[0]?.status).toBe('unknown');+ });++ it('reads anything that is not a list as no jobs', () => {+ expect(readIndexJobs({ jobs: [] })).toEqual([]);+ expect(readIndexJobs('nope')).toEqual([]);+ expect(readIndexJobs([1, 'two', null])).toEqual([]);+ });++ it('knows whether anything is still running', () => {+ expect(anyIndexing([])).toBe(false);+ expect(anyIndexing(readIndexJobs([{ slot: 0, status: 'done', path: '/a', error: '' }]))).toBe(false);+ expect(anyIndexing(readIndexJobs([{ slot: 0, status: 'indexing', path: '/a', error: '' }]))).toBe(true);+ });++ it('reports the paths that finished between two readings, and only those', () => {+ const before = readIndexJobs([+ { slot: 0, status: 'indexing', path: '/a', error: '' },+ { slot: 1, status: 'indexing', path: '/b', error: '' },+ { slot: 2, status: 'done', path: '/old', error: '' },+ ]);+ const after = readIndexJobs([+ { slot: 0, status: 'done', path: '/a', error: '' },+ { slot: 1, status: 'indexing', path: '/b', error: '' },+ { slot: 2, status: 'done', path: '/old', error: '' },+ ]);+ expect(finishedSince(before, after)).toEqual(['/a']);+ expect(finishedSince(after, after)).toEqual([]);+ });++ it('reads the acknowledgement of a started job', () => {+ expect(readIndexStarted({ status: 'indexing', slot: 2, path: '/repo' })).toEqual({ slot: 2, path: '/repo' });+ expect(readIndexStarted(null)).toEqual({ slot: -1, path: '' });+ });+});++describe('readBrowse', () => {+ it('reads a level with its parent and the optional drive roots', () => {+ expect(readBrowse({ path: '/Users/x', dirs: ['a', 'b'], parent: '/Users' })).toEqual({+ path: '/Users/x',+ dirs: ['a', 'b'],+ parent: '/Users',+ roots: [],+ });+ expect(readBrowse({ path: 'C:/', dirs: [], parent: 'C:/', roots: ['C:/', 'D:/'] }).roots).toEqual(['C:/', 'D:/']);+ });++ it('drops entries that are not strings', () => {+ expect(readBrowse({ path: '/', dirs: ['ok', 3, null] }).dirs).toEqual(['ok']);+ });++ it('joins a folder onto the level without doubling the separator', () => {+ expect(childPath(readBrowse({ path: '/Users/x', dirs: [] }), 'repo')).toBe('/Users/x/repo');+ expect(childPath(readBrowse({ path: '/', dirs: [] }), 'Users')).toBe('/Users');+ expect(childPath(readBrowse({ path: '', dirs: [] }), 'repo')).toBe('repo');+ });+});++describe('readHealth', () => {+ it('reads the three verdicts and their numbers', () => {+ expect(readHealth({ status: 'healthy', nodes: 76, edges: 178, size_bytes: 1048576 })).toEqual({+ status: 'healthy',+ nodes: 76,+ edges: 178,+ sizeBytes: 1048576,+ reason: '',+ });+ expect(readHealth({ status: 'missing' }).status).toBe('missing');+ expect(readHealth({ status: 'corrupt', reason: 'cannot open' })).toMatchObject({ status: 'corrupt', reason: 'cannot open' });+ });++ it('leaves a number the server did not send undefined', () => {+ const health = readHealth({ status: 'healthy' });+ expect(health.nodes).toBeUndefined();+ expect(health.sizeBytes).toBeUndefined();+ });++ it('names an unknown verdict as unknown', () => {+ expect(readHealth({ status: 'fine' }).status).toBe('unknown');+ expect(readHealth(undefined).status).toBe('unknown');+ });++ it('prints megabytes with one decimal', () => {+ expect(megabytes(1048576)).toBe('1.0');+ expect(megabytes(1572864)).toBe('1.5');+ expect(megabytes(0)).toBe('0.0');+ });+});++describe('readAdr', () => {+ it('reads a record with its content and timestamp', () => {+ expect(readAdr({ has_adr: true, content: '# ADR\n', updated_at: '2026-09-05 12:00' })).toEqual({+ hasAdr: true,+ content: '# ADR\n',+ updatedAt: '2026-09-05 12:00',+ });+ });++ it('reads the absence of a record as empty, not as an error', () => {+ expect(readAdr({ has_adr: false })).toEqual({ hasAdr: false, content: '', updatedAt: '' });+ });+});++describe('readLogs and readProcesses', () => {+ it('reads the log tail and its total', () => {+ expect(readLogs({ lines: ['a', 'b'], total: 400 })).toEqual({ lines: ['a', 'b'], total: 400 });+ });++ it('falls back to the shown count when the total is missing', () => {+ expect(readLogs({ lines: ['a'] }).total).toBe(1);+ expect(readLogs(null)).toEqual({ lines: [], total: 0 });+ });++ it('reads the process report with the flag for the serving process', () => {+ const report = readProcesses({+ self_pid: 42,+ self_rss_mb: 120.5,+ self_user_cpu_s: 1.2,+ self_sys_cpu_s: 0.3,+ processes: [+ { pid: 42, cpu: 0.5, rss_mb: 120.5, elapsed: '01:02:03', command: 'codebase-memory-mcp', is_self: true },+ { pid: 43, cpu: 12.0, rss_mb: 900.0, elapsed: '00:00:10', command: 'codebase-memory-mcp', is_self: false },+ ],+ });+ expect(report.selfPid).toBe(42);+ expect(report.selfRssMb).toBe(120.5);+ expect(report.processes.map((entry) => [entry.pid, entry.isSelf])).toEqual([[42, true], [43, false]]);+ });++ it('reads an empty or malformed report as no processes', () => {+ expect(readProcesses({}).processes).toEqual([]);+ expect(readProcesses('x').selfPid).toBe(-1);+ });+});++describe('projectNameFor and projectHref', () => {+ it('suggests the last path segment as the project name', () => {+ expect(projectNameFor('/Users/x/repo')).toBe('repo');+ expect(projectNameFor('/Users/x/repo/')).toBe('repo');+ expect(projectNameFor('C:\\code\\thing\\')).toBe('thing');+ });++ it('suggests nothing for an empty path or a bare root', () => {+ expect(projectNameFor('')).toBe('');+ expect(projectNameFor('/')).toBe('');+ });++ it('addresses a project through the query the page reads at start', () => {+ expect(projectHref('atlas sample')).toBe('?project=atlas%20sample');+ });+});diff --git a/graph-ui/src/projects/projects-model.ts b/graph-ui/src/projects/projects-model.tsnew file mode 100644index 000000000..b50615598--- /dev/null+++ b/graph-ui/src/projects/projects-model.ts@@ -0,0 +1,239 @@+/**+ * What the server says about its projects, read strictly, and the small+ * decisions the projects panel makes on top of it.+ *+ * The panel (src/projects/ProjectsPanel.tsx) is the one surface of this+ * frontend that asks the server to WRITE: index a repository, delete an index,+ * store a decision record. Everything it shows before and after such a request+ * comes from the routes below, and every reader here refuses to invent a+ * field: a number the server did not send stays `undefined`, a status it did+ * not name becomes `'unknown'`, and the panel says so.+ *+ * The routes and their shapes, as src/ui/http_server.c writes them:+ *+ * GET /api/index-status [{slot, status, path, error}]+ * POST /api/index {status: 'indexing', slot, path} (202)+ * GET /api/browse?path= {path, dirs[], parent, roots?[]}+ * GET /api/project-health?name= {status, nodes?, edges?, size_bytes?, reason?}+ * DELETE /api/project?name= {deleted: true}+ * GET /api/adr?project= {has_adr, content?, updated_at?}+ * POST /api/adr {saved: true}+ * GET /api/logs?lines= {lines[], total}+ * GET /api/processes {self_pid, self_rss_mb, ..., processes[]}+ */++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++const text = (value: unknown): string => (typeof value === 'string' ? value : '');++function optionalNumber(value: unknown): number | undefined {+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;+}++function strings(value: unknown): string[] {+ return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];+}++// ------------------------------------------------------------ index jobs --++export type IndexJobStatus = 'indexing' | 'done' | 'error' | 'unknown';++export interface IndexJob {+ slot: number;+ status: IndexJobStatus;+ path: string;+ /** Only set when `status` is `'error'`; the server sends an empty string otherwise. */+ error: string;+}++function readJobStatus(value: unknown): IndexJobStatus {+ return value === 'indexing' || value === 'done' || value === 'error' ? value : 'unknown';+}++/** The job table. Anything that is not an array of records reads as no jobs. */+export function readIndexJobs(raw: unknown): IndexJob[] {+ if (!Array.isArray(raw)) {+ return [];+ }+ return raw.filter(isRecord).map((job) => ({+ slot: optionalNumber(job['slot']) ?? -1,+ status: readJobStatus(job['status']),+ path: text(job['path']),+ error: text(job['error']),+ }));+}++export interface IndexStarted {+ slot: number;+ path: string;+}++/** The acknowledgement of POST /api/index. */+export function readIndexStarted(raw: unknown): IndexStarted {+ const record = isRecord(raw) ? raw : {};+ return { slot: optionalNumber(record['slot']) ?? -1, path: text(record['path']) };+}++/** True while at least one job is still running, which is when the panel keeps asking. */+export function anyIndexing(jobs: readonly IndexJob[]): boolean {+ return jobs.some((job) => job.status === 'indexing');+}++/**+ * The paths whose job went from running to finished between two readings.+ *+ * The panel reloads the project list exactly then: a list refreshed on every+ * poll would flicker, and one never refreshed would show the new project only+ * after a reload of the page.+ */+export function finishedSince(before: readonly IndexJob[], after: readonly IndexJob[]): string[] {+ const wasRunning = new Set(before.filter((job) => job.status === 'indexing').map((job) => job.slot));+ return after+ .filter((job) => wasRunning.has(job.slot) && job.status !== 'indexing')+ .map((job) => job.path);+}++// ---------------------------------------------------------------- browse --++export interface BrowseLevel {+ path: string;+ dirs: string[];+ parent: string;+ /** Drive letters on Windows; empty elsewhere. */+ roots: string[];+}++export function readBrowse(raw: unknown): BrowseLevel {+ const record = isRecord(raw) ? raw : {};+ return {+ path: text(record['path']),+ dirs: strings(record['dirs']),+ parent: text(record['parent']),+ roots: strings(record['roots']),+ };+}++/** `path` joined with one of its listed folders, without doubling the separator. */+export function childPath(level: BrowseLevel, dir: string): string {+ const base = level.path;+ if (base.length === 0) {+ return dir;+ }+ return base.endsWith('/') ? `${base}${dir}` : `${base}/${dir}`;+}++// ---------------------------------------------------------------- health --++export type HealthStatus = 'healthy' | 'missing' | 'corrupt' | 'unknown';++export interface ProjectHealth {+ status: HealthStatus;+ nodes?: number;+ edges?: number;+ sizeBytes?: number;+ reason: string;+}++export function readHealth(raw: unknown): ProjectHealth {+ const record = isRecord(raw) ? raw : {};+ const status = record['status'];+ return {+ status: status === 'healthy' || status === 'missing' || status === 'corrupt' ? status : 'unknown',+ nodes: optionalNumber(record['nodes']),+ edges: optionalNumber(record['edges']),+ sizeBytes: optionalNumber(record['size_bytes']),+ reason: text(record['reason']),+ };+}++/** Megabytes with one decimal, for a size the server gave in bytes. */+export function megabytes(bytes: number): string {+ return (bytes / (1024 * 1024)).toFixed(1);+}++// ------------------------------------------------------------------- adr --++export interface AdrRecord {+ hasAdr: boolean;+ content: string;+ updatedAt: string;+}++export function readAdr(raw: unknown): AdrRecord {+ const record = isRecord(raw) ? raw : {};+ return {+ hasAdr: record['has_adr'] === true,+ content: text(record['content']),+ updatedAt: text(record['updated_at']),+ };+}++// ------------------------------------------------------------------ logs --++export interface LogTail {+ lines: string[];+ total: number;+}++export function readLogs(raw: unknown): LogTail {+ const record = isRecord(raw) ? raw : {};+ const lines = strings(record['lines']);+ return { lines, total: optionalNumber(record['total']) ?? lines.length };+}++// ------------------------------------------------------------- processes --++export interface ServerProcess {+ pid: number;+ cpu: number;+ rssMb: number;+ elapsed: string;+ command: string;+ isSelf: boolean;+}++export interface ProcessReport {+ selfPid: number;+ selfRssMb: number;+ processes: ServerProcess[];+}++export function readProcesses(raw: unknown): ProcessReport {+ const record = isRecord(raw) ? raw : {};+ const list = Array.isArray(record['processes']) ? record['processes'].filter(isRecord) : [];+ return {+ selfPid: optionalNumber(record['self_pid']) ?? -1,+ selfRssMb: optionalNumber(record['self_rss_mb']) ?? 0,+ processes: list.map((entry) => ({+ pid: optionalNumber(entry['pid']) ?? -1,+ cpu: optionalNumber(entry['cpu']) ?? 0,+ rssMb: optionalNumber(entry['rss_mb']) ?? 0,+ elapsed: text(entry['elapsed']),+ command: text(entry['command']),+ isSelf: entry['is_self'] === true,+ })),+ };+}++// ------------------------------------------------------------ the form ----++/**+ * The project name a path suggests: its last segment.+ *+ * The server accepts the name it is given and stores the index under it, so+ * the suggestion only has to be something a reader recognises. Trailing+ * separators are dropped first, because `/repo/` names `repo` and not an empty+ * string. A path that is only separators, or empty, suggests nothing.+ */+export function projectNameFor(path: string): string {+ const trimmed = path.replace(/[\\/]+$/, '');+ const segment = trimmed.split(/[\\/]/).pop() ?? '';+ return segment;+}++/** The address of a project in this window: the page reloads with it. */+export function projectHref(name: string): string {+ return `?project=${encodeURIComponent(name)}`;+}diff --git a/graph-ui/src/styles/terminal.css b/graph-ui/src/styles/terminal.cssindex 1fcf2b7dc..4d7546eeb 100644--- a/graph-ui/src/styles/terminal.css+++ b/graph-ui/src/styles/terminal.css@@ -6580,3 +6580,313 @@ button.atlas-settings-model-pick:focus-visible {outline: 1px solid var(--atlas-alarm);outline-offset: -1px;}+++/* ----------------------------------------------------------------------- */+/* The projects panel. Same frame as the settings panel; its own blocks for */+/* the list rows, the index form, the folder browser and the log tail. */+/* ----------------------------------------------------------------------- */++.atlas-projects {+ position: absolute;+ inset: 0;+ z-index: 14;+ padding: 14px 20px 20px;+ background-color: var(--atlas-bg);+ overflow-y: auto;+}++.atlas-projects:focus {+ outline: none;+}++.atlas-projects > * {+ max-width: 108ch;+}++.atlas-projects-head {+ display: flex;+ align-items: baseline;+ gap: 14px;+ padding-bottom: 6px;+ border-bottom: 1px solid var(--atlas-line);+}++.atlas-projects-title {+ color: var(--atlas-phosphor);+ font-size: 14px;+ letter-spacing: 0.08em;+}++.atlas-projects-subtitle {+ color: var(--atlas-dim);+ font-size: 11px;+}++.atlas-projects-close {+ margin-left: auto;+ appearance: none;+ border: 1px solid var(--atlas-line);+ background: transparent;+ color: var(--atlas-dim);+ font: inherit;+ font-size: 11px;+ padding: 0 8px;+ cursor: pointer;+}++.atlas-projects-close:hover,+.atlas-projects-close:focus-visible {+ border-color: var(--atlas-phosphor-mute);+ color: var(--atlas-phosphor);+}++.atlas-projects-section {+ margin-top: 18px;+}++.atlas-projects-section-title {+ margin: 0 0 6px;+ color: var(--atlas-fg);+ font-size: 12px;+ font-weight: normal;+ letter-spacing: 0.06em;+ text-transform: uppercase;+}++.atlas-projects-subtitle-inline {+ margin: 14px 0 4px;+ color: var(--atlas-fg);+ font-size: 12px;+ font-weight: normal;+}++.atlas-projects-source,+.atlas-projects-note {+ margin: 0 0 6px;+ color: var(--atlas-dim);+ font-size: 11px;+}++.atlas-projects-text {+ margin: 0 0 6px;+ color: var(--atlas-fg);+ line-height: 1.5;+}++.atlas-projects-notice {+ margin: 6px 0;+ color: var(--atlas-cyan);+ font-size: 12px;+}++.atlas-projects-list,+.atlas-projects-jobs,+.atlas-projects-browse-list,+.atlas-projects-proc-list {+ margin: 0 0 8px;+ padding: 0;+ list-style: none;+ display: flex;+ flex-direction: column;+ gap: 4px;+}++.atlas-projects-row {+ border: 1px solid var(--atlas-line);+ background: var(--atlas-panel);+ padding: 6px 10px;+}++.atlas-projects-row[data-open='true'] {+ border-color: var(--atlas-phosphor-mute);+ background: var(--atlas-select);+}++.atlas-projects-row-line {+ display: flex;+ align-items: baseline;+ gap: 12px;+}++.atlas-projects-row-name {+ color: var(--atlas-cyan);+ overflow-wrap: anywhere;+}++.atlas-projects-row-meta,+.atlas-projects-row-path,+.atlas-projects-row-note {+ color: var(--atlas-dim);+ font-size: 11px;+ overflow-wrap: anywhere;+}++.atlas-projects-row-open {+ margin-left: auto;+ color: var(--atlas-phosphor);+ font-size: 11px;+ white-space: nowrap;+}++.atlas-projects-row-health {+ margin-top: 4px;+ color: var(--atlas-fg);+ font-size: 12px;+}++.atlas-projects-row-actions,+.atlas-projects-armed {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 8px;+ margin-top: 6px;+}++.atlas-projects-armed {+ color: var(--atlas-alarm);+ font-size: 12px;+}++.atlas-projects-action,+.atlas-projects-browse-dir {+ appearance: none;+ border: 1px solid var(--atlas-line);+ background: var(--atlas-panel-raised);+ color: var(--atlas-dim);+ font: inherit;+ font-size: 11px;+ padding: 2px 8px;+ cursor: pointer;+}++.atlas-projects-action:hover,+.atlas-projects-action:focus-visible,+.atlas-projects-browse-dir:hover,+.atlas-projects-browse-dir:focus-visible {+ border-color: var(--atlas-phosphor-mute);+ color: var(--atlas-phosphor);+}++.atlas-projects-action[data-primary='true'] {+ border-color: var(--atlas-phosphor-mute);+ color: var(--atlas-phosphor);+}++.atlas-projects-action[data-danger='true']:hover,+.atlas-projects-action[data-danger='true']:focus-visible {+ border-color: var(--atlas-alarm);+ color: var(--atlas-alarm);+}++.atlas-projects-form {+ display: flex;+ flex-direction: column;+ gap: 8px;+ margin: 8px 0;+}++.atlas-projects-field {+ display: flex;+ flex-direction: column;+ gap: 3px;+}++.atlas-projects-label {+ color: var(--atlas-dim);+ font-size: 11px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+}++.atlas-projects-input,+.atlas-projects-adr-text {+ appearance: none;+ border: 1px solid var(--atlas-line);+ background: var(--atlas-panel);+ color: var(--atlas-fg);+ font: inherit;+ padding: 4px 8px;+}++.atlas-projects-input:focus,+.atlas-projects-adr-text:focus {+ outline: none;+ border-color: var(--atlas-phosphor-mute);+}++.atlas-projects-adr-text {+ width: 100%;+ min-height: 14em;+ resize: vertical;+ line-height: 1.5;+}++.atlas-projects-browse {+ border: 1px solid var(--atlas-line);+ background: var(--atlas-panel);+ padding: 6px 10px;+}++.atlas-projects-browse-head {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 8px;+ margin-bottom: 6px;+ color: var(--atlas-dim);+ font-size: 11px;+ overflow-wrap: anywhere;+}++.atlas-projects-browse-list {+ flex-direction: row;+ flex-wrap: wrap;+}++.atlas-projects-job {+ display: flex;+ gap: 12px;+ align-items: baseline;+}++.atlas-projects-job-path {+ color: var(--atlas-fg);+ overflow-wrap: anywhere;+}++.atlas-projects-job-state {+ margin-left: auto;+ color: var(--atlas-dim);+ font-size: 11px;+ white-space: nowrap;+}++.atlas-projects-job[data-status='indexing'] .atlas-projects-job-state {+ color: var(--atlas-phosphor);+}++.atlas-projects-job[data-status='error'] .atlas-projects-job-state {+ color: var(--atlas-alarm);+}++.atlas-projects-proc-list li {+ color: var(--atlas-fg);+ font-size: 12px;+}++.atlas-projects-logs {+ margin: 0 0 8px;+ max-height: 24em;+ overflow: auto;+ border: 1px solid var(--atlas-line);+ background: var(--atlas-panel);+ color: var(--atlas-dim);+ font: inherit;+ font-size: 11px;+ line-height: 1.4;+ padding: 6px 10px;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}diff --git a/graph-ui/tools/lib/chrome-scan.mjs b/graph-ui/tools/lib/chrome-scan.mjsindex 43032d167..b05ff9084 100644--- a/graph-ui/tools/lib/chrome-scan.mjs+++ b/graph-ui/tools/lib/chrome-scan.mjs@@ -91,6 +91,9 @@ export const CHROME_FILES = [// was das Zeichnen kostet) und ueber kein einzelnes Fachgebiet. Sein Text// steht darum im Katalog und nicht neben ihm.'src/settings/SettingsPanel.tsx',+ // The projects panel speaks about the product as a whole too (what is+ // indexed, what the server is doing); its text sits in the catalog.+ 'src/projects/ProjectsPanel.tsx','src/why/WhyPanel.tsx','src/tours/TourCard.tsx','src/search/SearchOverlay.tsx',