File size: 28,796 Bytes
816fa8a
 
 
8cbc29f
816fa8a
 
 
8cbc29f
816fa8a
 
103a492
 
816fa8a
 
103a492
816fa8a
dec006b
816fa8a
8cbc29f
816fa8a
 
 
 
 
 
 
 
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
103a492
8cbc29f
816fa8a
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
816fa8a
 
 
 
 
 
 
 
07a68d0
 
816fa8a
 
 
 
 
 
 
 
 
 
 
8cbc29f
816fa8a
 
 
 
 
 
 
 
 
8cbc29f
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
8cbc29f
 
 
 
 
103a492
 
dec006b
816fa8a
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
816fa8a
8cbc29f
816fa8a
 
 
 
8cbc29f
 
 
 
 
 
816fa8a
8cbc29f
 
 
 
 
816fa8a
 
 
8cbc29f
816fa8a
 
 
 
 
 
 
 
 
 
 
8cbc29f
816fa8a
 
 
 
 
8cbc29f
103a492
8cbc29f
103a492
 
 
 
 
 
 
8cbc29f
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
103a492
 
 
 
 
 
 
 
 
8cbc29f
 
103a492
 
8cbc29f
103a492
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
103a492
 
816fa8a
dec006b
816fa8a
8cbc29f
816fa8a
 
 
8cbc29f
 
103a492
 
8cbc29f
103a492
816fa8a
103a492
816fa8a
 
dec006b
816fa8a
 
dec006b
 
816fa8a
dec006b
 
 
 
816fa8a
dec006b
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
816fa8a
 
dec006b
816fa8a
8cbc29f
103a492
8cbc29f
103a492
 
 
 
8cbc29f
816fa8a
8cbc29f
103a492
 
816fa8a
 
8cbc29f
dec006b
103a492
 
8cbc29f
103a492
 
 
 
8cbc29f
 
 
816fa8a
8cbc29f
 
 
103a492
 
816fa8a
103a492
8cbc29f
816fa8a
 
 
 
 
 
dec006b
816fa8a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import { useEffect, useId, useRef, useState } from "react";
import type { FormEvent } from "react";
import { Brain, ChartBar, FileText, X } from "@phosphor-icons/react";
import { UNAUTHORIZED_EVENT, WORKSPACE_STALE_EVENT } from "../apiContract";
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
import { FolderMark } from "../customer-grid/icons";
import { GridPager } from "../customer-grid/GridPager";
import { GridIcon, HomeTilePage, HomeTileText, ListIcon, QuickCard, useHomePageGrid } from "../home/HomePage";
import HomeFind from "../home/HomeFind";
import FolderNameDialog from "../home/FolderNameDialog";
import FolderTileMenu, { FolderPermissionError } from "../home/FolderTileMenu";
import ItemTileMenu, { ItemPermissionError } from "../home/ItemTileMenu";
import { ModuleHomeHead } from "../home/ModuleHomeHead";
import { HOME_LAYOUT_KEY, parseLayout } from "../home/homeModel";
import type { HomeLayout, ModuleFolderIndex } from "../home/homeModel";
import type { HomeSort } from "../home/homeFind";
import FileView, { BrainMarkdownEditor } from "./FileView";
import Insights from "./Insights";
import { BRAIN_FILES_CHANGED, BRAIN_FILE_SECTION, IntelligenceApiError, fileDate, intelligenceApi, intelligenceProblem } from "./intelligenceApi";
import type { IntelligenceApi, IntelligenceFile, IntelligenceFileRow, IntelligenceList, IntelligenceQuery } from "./intelligenceApi";
import "../styles/wave50/rail.css";
import "../styles/wave57/home-app.css";
import "../styles/wave58/app-data.css";
import "../styles/wave61/home.css";
import "../styles/wave61/rails.css";
import "../styles/sdlc72/home.css";
import "../styles/sdlc73/intelligence.css";
import "../styles/sdlc76/homes.css";

/** Optional mutation ports stay closed until the served API supplies them and current rights. */
export interface BrainHomeList extends IntelligenceList {
  canManageFolders?: boolean;
  folderRevision?: number;
}
export interface BrainHomeApi extends IntelligenceApi {
  listFiles(query: IntelligenceQuery, signal?: AbortSignal): Promise<BrainHomeList>;
  renameFile?: (path: string, title: string, expectedVersion: number) => Promise<IntelligenceFile>;
  deleteFile?: (path: string, expectedVersion: number) => Promise<{ deleted: string }>;
  renameFolder?: (path: string, name: string, expectedRevision: number) => Promise<{ path: string }>;
  deleteFolder?: (path: string, expectedRevision: number) => Promise<{ deleted: string }>;
}

export interface IntelligencePageProps {
  api?: BrainHomeApi;
  principalKey?: string;
  initialQuery?: string;
  initialPath?: string;
  initialView?: "files" | "insights";
  initialHistory?: boolean;
}

/** Where Brain is: every state lives in the hash so Back and Shell's remount restore it. */
interface BrainAddress { folder: string; view: "files" | "insights"; path: string; q: string }
const BRAIN_HASH = "#/intelligence";
const PAGE_SIZES = [10, 20] as const;
const DATABASE_NOTES_FOLDER = "database-notes";
const WIKI_FOLDER = "wiki";
const isDatabaseNotesFolder = (folder: string) => folder === DATABASE_NOTES_FOLDER || folder.startsWith(DATABASE_NOTES_FOLDER + "/");
const isWikiFolder = (folder: string) => folder === WIKI_FOLDER || folder.startsWith(WIKI_FOLDER + "/");

function isBrainHash(hash: string): boolean {
  return hash === BRAIN_HASH || hash.startsWith(BRAIN_HASH + "?");
}
function readAddress(hash: string): BrainAddress {
  const params = new URLSearchParams(hash.split("?")[1] || "");
  return { folder: params.get("folder") || "", view: params.get("view") === "insights" ? "insights" : "files",
    path: params.get("path") || "", q: params.get("q") || "" };
}
function addressHash(address: BrainAddress): string {
  const params = new URLSearchParams();
  if (address.folder) params.set("folder", address.folder);
  if (address.view === "insights") params.set("view", "insights");
  if (address.path) params.set("path", address.path);
  if (address.q) params.set("q", address.q);
  const query = params.toString();
  return query ? `${BRAIN_HASH}?${query}` : BRAIN_HASH;
}
/** The folders one level below `folder`, from the server's list of every ancestor prefix. */
function childFolders(folders: readonly string[], folder: string): string[] {
  const prefix = folder ? folder + "/" : "";
  const children = new Set<string>();
  for (const entry of folders) {
    if (!entry.startsWith(prefix) || entry === folder) continue;
    const name = entry.slice(prefix.length).split("/")[0];
    if (name) children.add(prefix + name);
  }
  return [...children].sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
}
const folderLabel = (folder: string) => folder === DATABASE_NOTES_FOLDER ? "Database notes"
  : folder === WIKI_FOLDER ? "AutoWiki" : folder.split("/").pop() || folder;
const folderHeading = (folder: string) => folder.split("/").map((part, index) =>
  index === 0 ? folderLabel(part) : part).join(" / ");
/** A folder name becomes one path segment the server accepts: letters, digits, dot, dash, underscore. */
function folderSegment(name: string): string {
  const segment = name.trim().replace(/\s+/g, "-").replace(/[^a-zA-Z0-9._-]/g, "");
  return segment === "." || segment === ".." ? "" : segment;
}
const fileFolder = (path: string) => path.split("/").slice(0, -1).join("/");
const stamp = (row: IntelligenceFileRow) => Math.max(Date.parse(row.updated) || 0, Date.parse(row.lastUsed || "") || 0);
function sortFiles(rows: readonly IntelligenceFileRow[], sort: HomeSort): IntelligenceFileRow[] {
  return [...rows].sort((a, b) => (sort === "recent" ? stamp(b) - stamp(a) : 0)
    || a.title.localeCompare(b.title, undefined, { sensitivity: "base" }) || a.path.localeCompare(b.path));
}

function NewFile({ api, folder, onClose, onCreated }: {
  api: IntelligenceApi; folder: string;
  onClose: () => void; onCreated: (file: IntelligenceFile) => void;
}) {
  const panelRef = useRef<HTMLElement>(null);
  const titleId = useId();
  const [title, setTitle] = useState("");
  const [chosenFolder, setFolder] = useState(folder);
  const templates = [
    { name: "Note", markdown: "## Summary\n\nWrite a summary here.\n\n## Details\n\nAdd the details here.\n" },
    { name: "Procedure", markdown: "## Purpose\n\nDescribe the outcome.\n\n## Steps\n\n1. Add the first step.\n2. Add the next step.\n" },
  ];
  const [template, setTemplate] = useState(0);
  const [markdown, setMarkdown] = useState(templates[0].markdown);
  const [busy, setBusy] = useState(false);
  const [problem, setProblem] = useState("");
  const writing = useRef(false);
  const alive = useRef(true);
  useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
  useOverlayLayer({ panelRef, onDismiss: () => { if (!writing.current) onClose(); }, dismissOnOutside: false,
    initialFocus: "[data-new-title]", restoreFocus: true, trapFocus: true });
  async function save(event: FormEvent) {
    event.preventDefault();
    if (writing.current) return;
    writing.current = true; setBusy(true); setProblem("");
    try {
      // The folder selects AutoWiki or the ordinary Brain file section.
      const file = await api.createFile({ title, section: isWikiFolder(chosenFolder.trim()) ? "wiki" : BRAIN_FILE_SECTION,
        folder: chosenFolder, markdown, tools: [] });
      if (alive.current) onCreated(file);
    } catch (error) {
      if (alive.current) setProblem(intelligenceProblem(error, "The file could not be saved. Try again."));
    } finally {
      writing.current = false;
      if (alive.current) setBusy(false);
    }
  }
  return <BodyPortal><div className="intelligence-scrim">
    <section ref={panelRef} className="intelligence-drawer" role="dialog" aria-modal="true" aria-labelledby={titleId}
      data-testid="intelligence-new-file">
      <header className="intelligence-drawer-head"><h2 id={titleId}>New file</h2>
        <button className="intelligence-button intelligence-icon-button" type="button" aria-label="Close new file"
          disabled={busy} onClick={onClose}><X size={20} aria-hidden="true" /></button></header>
      <form className="intelligence-create" onSubmit={(event) => void save(event)} aria-busy={busy}>
        <label>Title<input data-new-title required value={title} disabled={busy} onChange={(event) => setTitle(event.target.value)} /></label>
        <label>Folder<input value={chosenFolder} disabled={busy} placeholder="Optional" onChange={(event) => setFolder(event.target.value)} /></label>
        <label>Template<select value={template} disabled={busy} onChange={(event) => {
          const index = Number(event.target.value); setTemplate(index); setMarkdown(templates[index].markdown);
        }}>{templates.map((item, index) => <option key={item.name} value={index}>{item.name}</option>)}</select></label>
        <BrainMarkdownEditor key={template} body={markdown} title={title} disabled={busy} onChange={setMarkdown} />
        <div className="intelligence-create-feedback" role="alert">{problem}</div>
        <div className="intelligence-create-actions"><button className="intelligence-button" type="button" disabled={busy} onClick={onClose}>Cancel</button>
          <button className="intelligence-button intelligence-primary" type="submit" disabled={busy || !title.trim()}>{busy ? "Saving…" : "Create file"}</button></div>
      </form>
    </section>
  </div></BodyPortal>;
}

function SkeletonRows() {
  return <div className="home-tiles home-paged-grid is-grid intelligence-loading" data-testid="intelligence-loading" role="status" aria-label="Loading files">
    {Array.from({ length: 6 }, (_, index) => <div key={index} className="home-tile intelligence-skeleton" aria-hidden="true"><span /><span /><span /></div>)}
  </div>;
}

function BackButton({ onClick }: { onClick: () => void }) {
  return <button type="button" className="cg-btn" aria-label="Back" title="Back" onClick={onClick}>
    <svg viewBox="0 0 16 16" aria-hidden="true" className="home-layout-icon" fill="none" stroke="currentColor">
      <path d="M10 3 5 8l5 5" />
    </svg>
  </button>;
}

export default function IntelligencePage({ api = intelligenceApi, principalKey = "", initialQuery = "", initialPath = "",
  initialView = "files", initialHistory = false }: IntelligencePageProps) {
  const [address, setAddress] = useState<BrainAddress>(() => isBrainHash(window.location.hash)
    ? readAddress(window.location.hash) : { folder: "", view: initialView, path: initialPath, q: initialQuery });
  const [search, setSearch] = useState(address.q);
  const [sort, setSort] = useState<HomeSort>("recent");
  const [layout, setLayoutState] = useState<HomeLayout>(() => {
    try { return parseLayout(localStorage.getItem(HOME_LAYOUT_KEY)); } catch { return "grid"; }
  });
  const [query, setQuery] = useState<IntelligenceQuery>({ q: address.q, folder: address.folder, offset: 0, limit: 10 });
  const cache = useRef(new Map<string, BrainHomeList>());
  const generation = useRef(0);
  const owner = useRef({ api, principalKey });
  if (owner.current.api !== api || owner.current.principalKey !== principalKey) {
    cache.current.clear(); generation.current += 1;
    owner.current = { api, principalKey };
  }
  const queryKey = JSON.stringify([query.folder, query.q, query.offset, query.limit]);
  const [loaded, setLoaded] = useState<{ key: string; folder: string; value: BrainHomeList; owner: typeof owner.current } | null>(null);
  const [verified, setVerified] = useState<{ key: string; owner: typeof owner.current } | null>(null);
  const [loading, setLoading] = useState(true);
  const [problem, setProblem] = useState("");
  const [retry, setRetry] = useState(0);
  const [creating, setCreating] = useState(false);
  const [folderAnchor, setFolderAnchor] = useState<HTMLElement | null>(null);
  const pageRef = useRef<HTMLDivElement>(null);
  const { view, path } = address;
  const cached = cache.current.get(queryKey);
  const previous = loaded?.owner === owner.current ? loaded : null;
  const page = cached ?? previous?.value ?? null;
  const displayedFolder = cached ? query.folder : previous?.folder ?? query.folder;
  const pending = loading || verified?.key !== queryKey || verified.owner !== owner.current;
  const hasPager = !!page && page.total > PAGE_SIZES[0];
  const gridRef = useHomePageGrid(hasPager, layout);
  const databaseNotesFolder = isDatabaseNotesFolder(query.folder);

  function invalidate(clearDisplayed = false, refresh = true) {
    cache.current.clear(); generation.current += 1;
    setVerified(null);
    if (clearDisplayed) setLoaded(null);
    if (refresh) setRetry((value) => value + 1);
  }
  useEffect(() => {
    const changed = () => invalidate(true);
    const unauthorized = () => invalidate(true, false);
    const visibility = () => invalidate(true, document.visibilityState !== "hidden");
    window.addEventListener(BRAIN_FILES_CHANGED, changed);
    window.addEventListener(UNAUTHORIZED_EVENT, unauthorized);
    window.addEventListener(WORKSPACE_STALE_EVENT, changed);
    document.addEventListener("visibilitychange", visibility);
    return () => {
      cache.current.clear(); generation.current += 1;
      window.removeEventListener(BRAIN_FILES_CHANGED, changed);
      window.removeEventListener(UNAUTHORIZED_EVENT, unauthorized);
      window.removeEventListener(WORKSPACE_STALE_EVENT, changed);
      document.removeEventListener("visibilitychange", visibility);
    };
  }, []);

  function apply(next: BrainAddress) {
    setAddress(next); setSearch(next.q);
    if (isDatabaseNotesFolder(next.folder)) { setCreating(false); setFolderAnchor(null); }
    setQuery((current) => current.folder === next.folder && current.q === next.q ? current
      : { ...current, folder: next.folder, q: next.q, offset: 0 });
  }
  function go(next: BrainAddress) {
    const hash = addressHash(next);
    if (window.location.hash !== hash) window.location.hash = hash;
    apply(next);
  }
  function setPath(next: string) { go({ ...address, path: next }); }
  useEffect(() => {
    const onHash = () => { if (isBrainHash(window.location.hash)) apply(readAddress(window.location.hash)); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  useEffect(() => {
    const timer = window.setTimeout(() => {
      const q = search.trim();
      setQuery((current) => current.q === q ? current : { ...current, q, offset: 0 });
      setAddress((current) => {
        if (current.q === q) return current;
        const next = { ...current, q };
        // Typing must not remount the page, so the query rides the hash without a hashchange.
        if (isBrainHash(window.location.hash)) window.history.replaceState(window.history.state, "", addressHash(next));
        return next;
      });
    }, 250);
    return () => window.clearTimeout(timer);
  }, [search]);
  useEffect(() => {
    if (path || view === "insights") return;
    const abort = new AbortController();
    const requestGeneration = generation.current;
    setLoading(true); setVerified(null); setProblem("");
    void api.listFiles({ ...query, direct: !query.q.trim() }, abort.signal).then((value) => {
      if (abort.signal.aborted || requestGeneration !== generation.current) return;
      if (query.offset > 0 && query.offset >= value.total) {
        setQuery((current) => ({ ...current, offset: Math.max(0, Math.ceil(value.total / current.limit) - 1) * current.limit }));
        return;
      }
      const prior = cache.current.get(queryKey);
      if (prior && JSON.stringify(prior) !== JSON.stringify(value)) cache.current.clear();
      if (cache.current.size >= 40) cache.current.delete(cache.current.keys().next().value!);
      if (value.cacheable === true) cache.current.set(queryKey, value);
      setLoaded({ key: queryKey, folder: query.folder, value, owner: owner.current });
      setVerified({ key: queryKey, owner: owner.current });
    }).catch((error: unknown) => {
      if (abort.signal.aborted || requestGeneration !== generation.current) return;
      cache.current.clear(); setVerified(null);
      if (error instanceof IntelligenceApiError && [401, 403, 404].includes(error.status)) {
        setLoaded(null);
      }
      setProblem(intelligenceProblem(error, "The file list could not be read. Try again."));
    }).finally(() => { if (!abort.signal.aborted) setLoading(false); });
    return () => abort.abort();
  }, [api, principalKey, query, queryKey, retry, path, view]);

  function setLayout(next: HomeLayout) {
    setLayoutState(next);
    try { localStorage.setItem(HOME_LAYOUT_KEY, next); } catch { /* A private window keeps the choice in memory. */ }
  }
  function choosePage(offset: number) {
    setQuery((current) => ({ ...current, offset }));
    pageRef.current?.scrollTo({ top: 0 });
  }
  function enterFolder(folder: string) { go({ folder, view: "files", path: "", q: "" }); }
  function created(file: IntelligenceFile) {
    invalidate();
    setCreating(false);
    go({ folder: fileFolder(file.path), view: "files", path: file.path, q: "" });
  }
  const fileHref = (row: IntelligenceFileRow) => addressHash({ ...address, view: "files", path: row.path });

  const revokeFile = (_filePath: string) => invalidate(true);
  async function changeFile(row: IntelligenceFileRow, title?: string) {
    if (pending) throw new ItemPermissionError("Wait for the current folder to load.");
    try {
      const fresh = await api.readFile(row.path);
      if (fresh.canEdit !== true) {
        revokeFile(row.path);
        throw new ItemPermissionError("You no longer have permission to edit this file.");
      }
      if (fresh.version !== row.version) {
        invalidate();
        throw new Error("This file changed. Reload it before trying again.");
      }
      if (title !== undefined && api.renameFile) {
        const saved = await api.renameFile(row.path, title, row.version);
        if (saved.path !== row.path || saved.title !== title || saved.version <= row.version) {
          throw new Error("The rename could not be confirmed. Reload to check.");
        }
        setLoaded((current) => current ? { ...current, value: { ...current.value,
          files: current.value.files.map((file) => file.path === row.path ? saved : file),
        } } : null);
      } else if (title === undefined && api.deleteFile) {
        const saved = await api.deleteFile(row.path, row.version);
        if (saved.deleted !== row.path) throw new Error("The deletion could not be confirmed. Reload to check.");
        setLoaded((current) => current ? { ...current, value: { ...current.value,
          files: current.value.files.filter((file) => file.path !== row.path), total: Math.max(0, current.value.total - 1),
        } } : null);
      } else throw new Error("This file action is unavailable. Reload to check.");
      invalidate();
    } catch (error) {
      if (error instanceof IntelligenceApiError && [401, 403, 404].includes(error.status)) {
        revokeFile(row.path);
        throw new ItemPermissionError(error.message);
      }
      throw error;
    }
  }
  async function changeFolder(folder: string, name?: string) {
    if (pending) throw new FolderPermissionError("Wait for the current folder to load.");
    invalidate();
    try {
      const fresh = await api.listFiles({ ...query, direct: !query.q.trim() });
      setLoaded({ key: queryKey, folder: query.folder, value: fresh, owner: owner.current });
      const revision = fresh.folderRevision;
      if (fresh.canManageFolders !== true || typeof revision !== "number" || !Number.isSafeInteger(revision) || revision < 0) {
        throw new FolderPermissionError("Folder permissions could not be confirmed. Reload to check.");
      }
      if (revision !== page?.folderRevision) throw new Error("Folders changed. Try again with the current list.");
      if (name !== undefined && api.renameFolder) {
        const segment = folderSegment(name);
        if (!segment) throw new Error("Use letters or numbers in the folder name.");
        const saved = await api.renameFolder(folder, segment, revision);
        const expected = [fileFolder(folder), segment].filter(Boolean).join("/");
        if (saved.path !== expected) throw new Error("The rename could not be confirmed. Reload to check.");
      } else if (name === undefined && api.deleteFolder) {
        const saved = await api.deleteFolder(folder, revision);
        if (saved.deleted !== folder) throw new Error("The deletion could not be confirmed. Reload to check.");
      } else throw new Error("This folder action is unavailable. Reload to check.");
    } catch (error) {
      if (error instanceof IntelligenceApiError && [401, 403].includes(error.status)) {
        setLoaded((current) => current ? { ...current, value: { ...current.value, canManageFolders: false } } : null);
        throw new FolderPermissionError(error.message);
      }
      throw error;
    } finally { invalidate(); }
  }

  if (path) {
    return <div className="intel-page intelligence-file-home" role="region" aria-label="Brain" data-testid="intelligence-page">
      <FileView key={path} path={path} api={api} initialHistory={initialHistory}
        onChanged={() => invalidate()} onClose={() => setPath("")} />
    </div>;
  }

  const showWiki = !!page && !displayedFolder && !query.q.trim();
  const folders = page ? childFolders(showWiki ? [WIKI_FOLDER, ...page.folders] : page.folders, displayedFolder) : [];
  const folderIndex: ModuleFolderIndex = { rev: page?.folderRevision ?? 0, itemFolders: {},
    folders: (page?.folders ?? []).map((folder) => ({ id: folder, name: folderLabel(folder), parent: fileFolder(folder) || null })) };
  const canManageFolders = !pending && page?.canManageFolders === true && Number.isSafeInteger(page.folderRevision)
    && page.folderRevision! >= 0;
  const files = page ? sortFiles(page.files, sort) : [];
  const empty = !!page && page.total === 0 && !folders.length && !problem;
  const parent = query.folder.split("/").slice(0, -1).join("/");

  return <div className="intel-page shell-home intelligence-home" ref={pageRef} role="region" aria-label="Brain" data-testid="intelligence-page">
    <ModuleHomeHead title="Brain" module="intelligence" />
    <div className="home-cards is-app">
      {!databaseNotesFolder ? <QuickCard icon={<span className="intelligence-card-icon" aria-hidden="true"><Brain size={16} /></span>}
        title="Create new" detail="Write a new Brain file" onClick={() => setCreating(true)} /> : null}
      <QuickCard icon={<span className="intelligence-card-icon" aria-hidden="true"><ChartBar size={16} /></span>}
        title="Insights" detail="See who changed Brain files" onClick={() => go({ ...address, view: "insights", path: "" })} />
      {!databaseNotesFolder ? <QuickCard icon={<span className="home-card-icon" aria-hidden="true"><FolderMark size={16} /></span>}
        title="New folder" detail="Group Brain files into folders"
        onClick={(event) => setFolderAnchor(event.currentTarget)} /> : null}
    </div>
    {folderAnchor && !databaseNotesFolder ? <FolderNameDialog anchor={folderAnchor} title="New folder"
      siblingNames={folders.map(folderLabel)}
      onSubmit={(name) => {
        const segment = folderSegment(name);
        setFolderAnchor(null);
        if (segment) enterFolder(query.folder ? `${query.folder}/${segment}` : segment);
      }}
      onDismiss={() => setFolderAnchor(null)} /> : null}

    {view === "insights" ? <div className="home-section-head">
      <BackButton onClick={() => go({ ...address, view: "files" })} />
      <span className="home-folder-name">Insights</span>
    </div> : null}
    {view === "insights" ? <Insights api={api} /> : <>
      <div className="home-recents-bar">
        <div className="home-layout-toggle home-find-toolbar" role="group" aria-label="Layout">
          <HomeFind moduleName="Brain" query={search} sort={sort} onQueryChange={setSearch} onSortChange={setSort} />
          <div className="home-find-layout">
            <button type="button" className={"home-layout-btn" + (layout === "list" ? " is-on" : "")}
              aria-pressed={layout === "list"} aria-label="List" title="List" onClick={() => setLayout("list")}>
              <ListIcon />
            </button>
            <button type="button" className={"home-layout-btn" + (layout === "grid" ? " is-on" : "")}
              aria-pressed={layout === "grid"} aria-label="Grid" title="Grid" onClick={() => setLayout("grid")}>
              <GridIcon />
            </button>
          </div>
        </div>
      </div>

      {problem ? <div className="intelligence-feedback" role="alert" data-testid="intelligence-error">
        <span>{problem}{page?.files.length ? " Showing the last list." : ""}</span>
        <button type="button" className="intelligence-button" onClick={() => setRetry((value) => value + 1)}>Retry</button></div> : null}
      {!page && loading ? <SkeletonRows /> : null}
      {page ? <>
        {query.folder || folders.length ? <section className="home-section" aria-label="Brain folders" aria-busy={pending}>
          {query.folder ? <div className="home-section-head">
            <BackButton onClick={() => enterFolder(parent)} />
            <span className="home-folder-name">{folderHeading(query.folder)}</span>
          </div> : null}
          {folders.length ? <HomeTilePage items={folders} layout={layout} scopeKey={displayedFolder}>
            {(pageItems) => pageItems.map((folder) => <FolderTileMenu key={folder}
              folder={{ id: folder, name: folderLabel(folder), parent: displayedFolder || null }} index={folderIndex}
              canManage={canManageFolders && !isDatabaseNotesFolder(folder)}
              onRename={api.renameFolder ? (name) => changeFolder(folder, name) : undefined}
              onDelete={api.deleteFolder ? () => changeFolder(folder) : undefined}
              deleteBody={<p>Files and nested folders move to the top level.</p>}>
              <button type="button" className="home-tile" disabled={pending} onClick={() => enterFolder(folder)}>
              <span className="home-tile-chip home-folder-glyph" aria-hidden="true"><FolderMark size={16} /></span>
              <HomeTileText tile={{ id: folder, name: folderLabel(folder) }} fallback="Folder" />
              </button>
            </FolderTileMenu>)}
          </HomeTilePage> : null}
        </section> : null}
        {files.length || page.total > 0 ? <section className="home-section" aria-busy={pending}>
          <h2 className="home-section-title">{isWikiFolder(query.folder) ? "AutoWiki pages" : "Brain files"}</h2>
          <div ref={gridRef} className={"home-tiles home-paged-grid is-" + layout} data-testid="intelligence-list"
            data-page-size={query.limit} data-page-capacity={hasPager ? PAGE_SIZES[1] : undefined}>
            {files.map((row) => <ItemTileMenu key={row.path} id={row.path} kind="Brain file" name={row.title} busy={pending}
              canRename={row.canEdit === true && row.section !== "database-notes" && !!api.renameFile}
              canDelete={row.canEdit === true && row.section !== "database-notes" && !!api.deleteFile}
              onRename={(title) => changeFile(row, title)} onDelete={() => changeFile(row)}
              deleteBody={<p>This cannot be undone.</p>}>
              <a className="home-tile cg-view-row" href={pending ? undefined : fileHref(row)} data-file-path={row.path}
              aria-disabled={pending || undefined} tabIndex={pending ? -1 : undefined}
              onClick={(event) => { if (pending) event.preventDefault(); }}>
              <span className="home-tile-chip home-app-glyph" aria-hidden="true"><FileText size={16} /></span>
              <HomeTileText tile={{ id: row.path, name: row.title }} fallback={[
                fileFolder(row.path) !== displayedFolder ? folderHeading(fileFolder(row.path)) : "",
                `Edited ${fileDate(row.updated)}`].filter(Boolean).join(" · ")} />
              </a>
            </ItemTileMenu>)}
          </div>
          {hasPager ? <GridPager offset={page.offset} size={query.limit} sizes={PAGE_SIZES}
            total={page.total} pending={pending} itemsLabel="Items" onPage={choosePage}
            onSize={(size) => setQuery((current) => ({ ...current, limit: size === 20 ? 20 : 10, offset: 0 }))} /> : null}
        </section> : null}
        {empty ? <p className="home-empty" data-testid="intelligence-empty" role="status">
          {query.q ? "No Brain files match that." : query.folder ? "This folder is empty." : "No Brain files yet."}</p> : null}
      </> : null}
    </>}
    {creating && !databaseNotesFolder ? <NewFile api={api} folder={query.folder} onClose={() => setCreating(false)} onCreated={created} /> : null}
  </div>;
}