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; renameFile?: (path: string, title: string, expectedVersion: number) => Promise; 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(); 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(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

New file

void save(event)} aria-busy={busy}>
{problem}
; } function SkeletonRows() { return
{Array.from({ length: 6 }, (_, index) => )}
; } function BackButton({ onClick }: { onClick: () => void }) { return ; } export default function IntelligencePage({ api = intelligenceApi, principalKey = "", initialQuery = "", initialPath = "", initialView = "files", initialHistory = false }: IntelligencePageProps) { const [address, setAddress] = useState(() => 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("recent"); const [layout, setLayoutState] = useState(() => { try { return parseLayout(localStorage.getItem(HOME_LAYOUT_KEY)); } catch { return "grid"; } }); const [query, setQuery] = useState({ q: address.q, folder: address.folder, offset: 0, limit: 10 }); const cache = useRef(new Map()); 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(null); const pageRef = useRef(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
invalidate()} onClose={() => setPath("")} />
; } 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
{!databaseNotesFolder ?
{folderAnchor && !databaseNotesFolder ? { const segment = folderSegment(name); setFolderAnchor(null); if (segment) enterFolder(query.folder ? `${query.folder}/${segment}` : segment); }} onDismiss={() => setFolderAnchor(null)} /> : null} {view === "insights" ?
go({ ...address, view: "files" })} /> Insights
: null} {view === "insights" ? : <>
{problem ?
{problem}{page?.files.length ? " Showing the last list." : ""}
: null} {!page && loading ? : null} {page ? <> {query.folder || folders.length ?
{query.folder ?
enterFolder(parent)} /> {folderHeading(query.folder)}
: null} {folders.length ? {(pageItems) => pageItems.map((folder) => changeFolder(folder, name) : undefined} onDelete={api.deleteFolder ? () => changeFolder(folder) : undefined} deleteBody={

Files and nested folders move to the top level.

}>
)}
: null}
: null} {files.length || page.total > 0 ?

{isWikiFolder(query.folder) ? "AutoWiki pages" : "Brain files"}

{files.map((row) => changeFile(row, title)} onDelete={() => changeFile(row)} deleteBody={

This cannot be undone.

}> { if (pending) event.preventDefault(); }}>
)}
{hasPager ? setQuery((current) => ({ ...current, limit: size === 20 ? 20 : 10, offset: 0 }))} /> : null}
: null} {empty ?

{query.q ? "No Brain files match that." : query.folder ? "This folder is empty." : "No Brain files yet."}

: null} : null} } {creating && !databaseNotesFolder ? setCreating(false)} onCreated={created} /> : null}
; }