Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Space documents: Documents tab, quote chips and the passage viewer (stacked on #601) (#613)
Oleksandr Ivanchenko678fa6902eb6
diff --git a/frontend/src/components/DocMark.tsx b/frontend/src/components/DocMark.tsxnew file mode 100644index 00000000..a2530087--- /dev/null+++ b/frontend/src/components/DocMark.tsx@@ -0,0 +1,18 @@+import React from 'react';+import { docKind, markOf } from '../spaceDocs';++/** The type mark: PDF, MD or TXT (or the odd extension). It tells the types apart; it is not a status. */+export const DocMark: React.FC<{ name: string; size?: 28 | 32 }> = ({ name, size = 32 }) => {+ const k = docKind(name);+ const tone = k === 'pdf' ? 'text-rose-200' : k === 'md' ? 'text-violet-200' : 'text-zinc-200';+ return (+ <span+ aria-hidden="true"+ className={`shrink-0 inline-flex items-center justify-center rounded-lg border border-zinc-700 bg-zinc-900 font-bold tracking-[.04em] ${tone} ${+ size === 28 ? 'w-7 h-7 text-[9px]' : 'w-8 h-8 text-[9.5px]'+ }`}+ >+ {markOf(name)}+ </span>+ );+};diff --git a/frontend/src/components/DocQuoteChip.tsx b/frontend/src/components/DocQuoteChip.tsxnew file mode 100644index 00000000..748e5529--- /dev/null+++ b/frontend/src/components/DocQuoteChip.tsx@@ -0,0 +1,63 @@+import React, { useEffect, useState } from 'react';+import { AlertTriangle, CircleCheck, FileText } from 'lucide-react';+import { CiteState, parseDocUrl, recheckQuote } from '../spaceDocs';+import { DocViewerSheet } from './DocViewerSheet';++/**+ * A `kwant-doc://` link in a reply (design §2): the file and page the address names, and a teal tick once+ * kwant has checked the quote against the file right now. Amber when the words aren't there now. Never holo:+ * the reply's own sticker stays the one earned mark. The bot's link text is not shown.+ */+export const DocQuoteChip: React.FC<{ href: string; fallback?: React.ReactNode }> = ({ href, fallback = null }) => {+ const ref = parseDocUrl(href);+ const [state, setState] = useState<CiteState | null>(null);+ const [open, setOpen] = useState(false);++ useEffect(() => {+ if (!ref?.quote) return;+ let live = true;+ recheckQuote(ref.space, ref.file, ref.quote).then((s) => live && setState(s));+ return () => {+ live = false;+ };+ }, [ref?.space, ref?.file, ref?.quote]);++ if (!ref) return <>{fallback}</>;+ const bad = state === 'missing' || state === 'gone';+ const where = ref.page ? `${ref.file}, page ${ref.page}` : ref.file;+ const tip = state === 'ok' ? `Checked word for word in ${where}` : bad ? `Not found in ${ref.file} now` : where;+ const label =+ state === 'ok'+ ? `${where}, quote checked word for word. Open the passage.`+ : bad+ ? `${where}, quote not found in the file now. Open the passage.`+ : `${where}. Open the passage.`;++ return (+ <>+ <button+ type="button"+ onClick={() => setOpen(true)}+ aria-label={label}+ data-tip={tip}+ data-doc-chip={state ?? 'checking'}+ data-compact+ className={`kws-tip relative inline-flex items-center gap-1 h-7 sm:h-6 max-w-[260px] px-1.5 mx-0.5 align-[2px] rounded-md border text-xs font-medium not-italic whitespace-nowrap transition-colors motion-reduce:transition-none before:absolute before:-inset-y-2 before:inset-x-0 before:content-[''] sm:before:hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950 ${+ bad ? 'border-amber-300/40 bg-zinc-900/70 text-amber-200 hover:bg-zinc-800' : 'border-zinc-700 bg-zinc-900/70 text-zinc-200 hover:bg-zinc-800 hover:border-zinc-600'+ }`}+ >+ <FileText size={12} className="shrink-0 text-zinc-400" aria-hidden="true" />+ <span className="truncate max-w-[118px] sm:max-w-[150px]">{ref.file}</span>+ {ref.page && <span className="shrink-0 font-normal text-zinc-400">· p. {ref.page}</span>}+ {state === 'ok' && <CircleCheck size={12} className="shrink-0 text-ok motion-safe:animate-[kw-dd-in_150ms_ease-out]" aria-hidden="true" />}+ {bad && <AlertTriangle size={12} className="shrink-0 text-amber-300" aria-hidden="true" />}+ </button>+ {open && (+ <DocViewerSheet+ open={{ space: ref.space, file: ref.file, page: ref.page ?? 1, quote: ref.quote, check: state ?? undefined }}+ onClose={() => setOpen(false)}+ />+ )}+ </>+ );+};diff --git a/frontend/src/components/DocViewerSheet.tsx b/frontend/src/components/DocViewerSheet.tsxnew file mode 100644index 00000000..42b362fb--- /dev/null+++ b/frontend/src/components/DocViewerSheet.tsx@@ -0,0 +1,251 @@+import React, { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { AlertTriangle, ChevronLeft, ChevronRight, CircleCheck, Copy, RotateCw, X } from 'lucide-react';+import { CiteState, DocPage, copyQuote, docKind, formatSize, spaceDocsApi, updatedWhen } from '../spaceDocs';+import { DocMark } from './DocMark';++const focusRing = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400';+const secondaryBtn = `inline-flex items-center justify-center gap-1.5 px-3 rounded-lg text-xs font-medium text-zinc-200 border border-zinc-700 bg-zinc-900 hover:bg-zinc-800 disabled:opacity-40 disabled:pointer-events-none ${focusRing}`;++export interface DocViewerOpen {+ space: string;+ file: string;+ /** 1 from the list; the quote's page from a chip (PDFs). */+ page: number;+ /** Set when opened from a chip. */+ quote?: string | null;+ /** The chip's re-check, when opened from one. */+ check?: CiteState;+ /** For .md and .txt: the list's size and date for the sub line. */+ size?: number;+ modified?: string;+ /** PDFs: page count from the list, until the page answers. */+ pages?: number;+}++/**+ * The passage viewer (design §3): the page's plain text with the quote marked. A side sheet from 640 px,+ * a bottom sheet below. Focus moves to ✕, stays inside, Esc closes and focus goes back to the opener+ * (TaskPanel's pattern).+ */+export const DocViewerSheet: React.FC<{ open: DocViewerOpen; onClose: () => void }> = ({ open, onClose }) => {+ const { space, file, quote } = open;+ const pdf = docKind(file) === 'pdf';+ const [page, setPage] = useState(open.page);+ const [data, setData] = useState<DocPage | 'gone' | 'no_route' | 'failed' | null>(null);+ const [seq, setSeq] = useState(0);+ const [copied, setCopied] = useState(false);+ const [shown, setShown] = useState(false);+ const closeRef = useRef<HTMLButtonElement>(null);+ const panelRef = useRef<HTMLDivElement>(null);+ const bodyRef = useRef<HTMLDivElement>(null);+ const markRef = useRef<HTMLElement>(null);+ const subId = useId();+ const gone = open.check === 'gone' || data === 'gone';+ const missing = open.check === 'missing';++ useEffect(() => {+ const back = document.activeElement as HTMLElement | null;+ closeRef.current?.focus();+ const raf = requestAnimationFrame(() => setShown(true));+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ onClose();+ return;+ }+ if (e.key !== 'Tab' || !panelRef.current) return;+ const items = [...panelRef.current.querySelectorAll<HTMLElement>('button:not([disabled]), [href], [tabindex]:not([tabindex="-1"])')];+ if (!items.length) return;+ const first = items[0];+ const last = items[items.length - 1];+ if (e.shiftKey && document.activeElement === first) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ };+ window.addEventListener('keydown', onKey, true);+ return () => {+ cancelAnimationFrame(raf);+ window.removeEventListener('keydown', onKey, true);+ back?.focus?.();+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ if (open.check === 'gone') return;+ let live = true;+ setData(null);+ spaceDocsApi.page(space, file, page, quote).then((d) => live && setData(d));+ return () => {+ live = false;+ };+ }, [space, file, page, quote, seq, open.check]);++ // The mark at about the middle of the body, with no smooth scroll.+ useLayoutEffect(() => {+ if (data && typeof data === 'object' && data.match) markRef.current?.scrollIntoView({ block: 'center' });+ else bodyRef.current?.scrollTo?.(0, 0);+ }, [data]);++ const pages = data && typeof data === 'object' ? data.pages : open.pages ?? 1;+ const quotePage = open.page;+ const sub = pdf ? `Page ${page} of ${pages}` : [open.size != null ? formatSize(open.size) : '', open.modified ? `updated ${updatedWhen(open.modified)}` : ''].filter(Boolean).join(' · ');++ const copy = () => {+ if (!quote) return;+ navigator.clipboard?.writeText(copyQuote(quote, file, pdf ? quotePage : null)).catch(() => {});+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1500);+ };++ const body = (() => {+ if (gone) return null;+ if (data === null)+ return (+ <div className="space-y-2.5 pt-1" aria-hidden="true" data-viewer-loading>+ {[92, 84, 96, 70, 88, 52].map((w, i) => (+ <div key={i} className="h-3 rounded bg-zinc-800" style={{ width: `${w}%` }} />+ ))}+ </div>+ );+ if (data === 'no_route')+ return quote ? (+ <>+ <div className="whitespace-pre-wrap break-words" data-viewer-text>+ <mark className="rounded-[3px] bg-violet-400/[.22] text-zinc-50 px-0.5 -mx-0.5 shadow-[inset_0_-2px_0_rgb(157_143_255/.65)]" data-viewer-mark>+ {quote}+ </mark>+ </div>+ <p className="mt-3 text-xs text-zinc-500" data-viewer-no-route>+ Only the quoted words are shown here for now. The rest of the page opens after the next update.+ </p>+ </>+ ) : (+ <p className="text-sm text-zinc-400" data-viewer-no-route>+ This file’s text opens here after the next update. Bots can already read and quote it.+ </p>+ );+ if (data === 'failed')+ return (+ <p className="flex flex-wrap items-center gap-2 text-sm text-zinc-300" role="status">+ <AlertTriangle size={14} className="text-amber-300" aria-hidden="true" />+ Couldn’t open this page.+ <button type="button" className={`${secondaryBtn} h-8`} onClick={() => setSeq((n) => n + 1)}>+ <RotateCw size={12} aria-hidden="true" /> Try again+ </button>+ </p>+ );+ return (+ <>+ {data.cut_before && <p className="mb-3 text-xs text-zinc-500">Earlier text on this page isn’t shown here. Bots still read all of it.</p>}+ <div className="whitespace-pre-wrap break-words" data-viewer-text>+ {data.text_before}+ {data.match && (+ <mark+ ref={markRef}+ className="rounded-[3px] bg-violet-400/[.22] text-zinc-50 px-0.5 -mx-0.5 shadow-[inset_0_-2px_0_rgb(157_143_255/.65)]"+ data-viewer-mark+ >+ {data.match}+ </mark>+ )}+ {data.text_after}+ </div>+ {data.cut_after && <p className="mt-3 text-xs text-zinc-500">Later text on this page isn’t shown here. Bots still read all of it.</p>}+ </>+ );+ })();++ const sheet = (+ <div className="fixed inset-0 z-50 flex items-end sm:items-stretch sm:justify-end" data-doc-viewer>+ <button type="button" aria-label="Close" tabIndex={-1} onClick={onClose} className="absolute inset-0 bg-black/50 cursor-default" />+ <div+ ref={panelRef}+ role="dialog"+ aria-modal="true"+ aria-label={file}+ aria-describedby={subId}+ className={`relative flex flex-col w-full h-[85vh] rounded-t-2xl border-t border-zinc-700 sm:w-[480px] sm:max-w-full sm:h-full sm:rounded-none sm:border-t-0 sm:border-l sm:border-zinc-800 bg-zinc-950 shadow-2xl transition-transform duration-[160ms] ease-out motion-reduce:transition-none ${+ shown ? 'translate-x-0 translate-y-0' : 'translate-y-full sm:translate-y-0 sm:translate-x-full'+ }`}+ >+ <div className="sm:hidden flex justify-center pt-2" aria-hidden="true">+ <span className="w-9 h-1 rounded-full bg-zinc-700" />+ </div>+ <div className="flex items-start gap-2.5 py-3 pl-5 pr-3 border-b border-zinc-800/80 bg-zinc-900/30">+ <DocMark name={file} size={28} />+ <div className="min-w-0 flex-1">+ <h3 className="text-sm font-semibold text-zinc-100 truncate" title={file}>+ {file}+ </h3>+ <p id={subId} className="text-xs text-zinc-400">+ {sub}+ </p>+ </div>+ <button+ ref={closeRef}+ type="button"+ onClick={onClose}+ aria-label="Close"+ className={`shrink-0 inline-flex items-center justify-center w-11 h-11 sm:w-9 sm:h-9 -my-1 rounded-lg text-zinc-300 hover:text-zinc-100 hover:bg-zinc-800 ${focusRing}`}+ >+ <X size={18} aria-hidden="true" />+ </button>+ </div>++ {quote && (gone || missing) ? (+ <div className="flex items-start gap-2 px-5 py-2.5 border-b border-zinc-800 bg-amber-300/[.05] text-[13px] text-zinc-200 leading-relaxed" data-viewer-check={gone ? 'gone' : 'missing'}>+ <AlertTriangle size={14} className="mt-[3px] shrink-0 text-amber-300" aria-hidden="true" />+ {gone ? (+ <p>{file} isn’t in this space’s documents any more.</p>+ ) : (+ <p>+ These words aren’t in {file} now: “{quote}”{/[.!?…]$/.test(quote.trim()) ? '' : '.'} The file may have changed since this reply, so check it before you rely on it.+ </p>+ )}+ </div>+ ) : quote && open.check === 'ok' ? (+ <div className="flex flex-wrap items-center gap-2 px-5 py-2.5 border-b border-zinc-800" data-viewer-check="ok">+ <span className="inline-flex items-center gap-1 h-[22px] px-2 rounded-full border border-teal-300/30 bg-teal-300/10 text-ok text-[11.5px] font-semibold">+ <CircleCheck size={12} aria-hidden="true" />+ {pdf ? `Word for word on page ${quotePage}` : `Word for word in ${file}`}+ </span>+ </div>+ ) : null}++ <div ref={bodyRef} className="flex-1 overflow-y-auto px-5 py-4 text-sm leading-6 text-zinc-300" data-viewer-body>+ {body}+ </div>++ {((pdf && pages > 1 && !gone && data !== 'no_route') || quote) && (+ <div+ className="grid grid-cols-2 gap-2 px-5 py-2.5 border-t border-zinc-800 pb-[max(0.625rem,env(safe-area-inset-bottom))] sm:flex sm:items-center sm:pb-2.5"+ data-viewer-footer+ >+ {pdf && pages > 1 && !gone && data !== 'no_route' && (+ <>+ <button type="button" className={`${secondaryBtn} h-11 sm:h-8`} disabled={page <= 1} onClick={() => setPage((n) => Math.max(1, n - 1))}>+ <ChevronLeft size={14} aria-hidden="true" /> Page {Math.max(1, page - 1)}+ </button>+ <button type="button" className={`${secondaryBtn} h-11 sm:h-8`} disabled={page >= pages} onClick={() => setPage((n) => Math.min(pages, n + 1))}>+ Page {Math.min(pages, page + 1)} <ChevronRight size={14} aria-hidden="true" />+ </button>+ </>+ )}+ {quote && (+ <button type="button" className={`${secondaryBtn} h-11 sm:h-8 col-span-2 sm:col-span-1 sm:ml-auto`} onClick={copy} data-copy-quote>+ <Copy size={13} aria-hidden="true" /> {copied ? 'Copied' : 'Copy quote'}+ </button>+ )}+ </div>+ )}+ </div>+ </div>+ );+ return createPortal(sheet, document.body);+};diff --git a/frontend/src/components/MarkdownRenderer.tsx b/frontend/src/components/MarkdownRenderer.tsxindex fc31743f..43fa32f2 100644--- a/frontend/src/components/MarkdownRenderer.tsx+++ b/frontend/src/components/MarkdownRenderer.tsx@@ -1,5 +1,5 @@import React, { useState } from 'react';-import ReactMarkdown from 'react-markdown';+import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';import remarkGfm from 'remark-gfm';import { Copy, Check, Terminal } from 'lucide-react';import { playSfx } from '../audio/chiptune';@@ -8,6 +8,11 @@ import type { ReplyPart, ReplySource } from './results/registry';import { SmartResult } from './results/SmartResult';import { ReplyText } from './results/ReplyText';import { inlineCodeClass, linkClass } from './markdownInline';+import { DOC_SCHEME } from '../spaceDocs';+import { DocQuoteChip } from './DocQuoteChip';++/** react-markdown drops unknown schemes; a space document's address is kept for its quote chip. */+const urlTransform = (url: string) => (url.startsWith(DOC_SCHEME) ? url : defaultUrlTransform(url));interface CodeBlockProps {language?: string;@@ -180,6 +185,7 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({<div className={`markdown-content text-sm leading-relaxed text-zinc-200 ${className}`}><ReactMarkdownremarkPlugins={[remarkGfm]}+ urlTransform={urlTransform}rehypePlugins={smart ? [rehypeSmartIndex as never, ...(section ? [rehypeSmartSection(content, results) as never] : [])] : undefined}components={{// Pre element pass-through to let CodeBlock handle layout@@ -348,7 +354,10 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({hr: () => <hr className="my-4 border-zinc-800" />,// Links- a: ({ href, children }) => (+ a: ({ href, children }) =>+ href?.startsWith(DOC_SCHEME) ? (+ <DocQuoteChip href={href} fallback={children} />+ ) : (<ahref={href}target="_blank"@@ -357,7 +366,7 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({>{children}</a>- ),+ ),}}>{content}diff --git a/frontend/src/components/SpaceDocsTab.tsx b/frontend/src/components/SpaceDocsTab.tsxnew file mode 100644index 00000000..1f33b977--- /dev/null+++ b/frontend/src/components/SpaceDocsTab.tsx@@ -0,0 +1,509 @@+import React, { useCallback, useEffect, useRef, useState } from 'react';+import { AlertTriangle, Copy, FileText, Loader2, RotateCw, Trash2, Upload, X } from 'lucide-react';+import {+ DOC_ACCEPT,+ DOC_MAX_COUNT,+ SpaceDoc,+ SpaceDocList,+ checkFile,+ docKind,+ docMeta,+ formatSize,+ markOf,+ shortFolder,+ sortDocs,+ spaceDocsApi,+} from '../spaceDocs';+import { DocMark } from './DocMark';+import { DocViewerOpen, DocViewerSheet } from './DocViewerSheet';++const focusRing = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400';+const primaryBtn = `inline-flex items-center justify-center gap-1.5 px-3 rounded-lg text-xs font-medium text-white bg-violet-600 hover:bg-violet-500 transition-colors motion-reduce:transition-none disabled:opacity-50 ${focusRing}`;+const quietBtn = `inline-flex items-center justify-center gap-1.5 px-3 rounded-lg text-xs font-medium text-zinc-200 border border-zinc-700 bg-zinc-900 hover:bg-zinc-800 ${focusRing}`;+const dangerBtn = `inline-flex items-center justify-center gap-1.5 px-3 rounded-lg text-xs font-medium bg-rose-300/[.12] border border-rose-300/40 text-rose-100 hover:bg-rose-300/20 ${focusRing}`;+const tooBig = (size: number) => `It’s ${formatSize(size)}, over the 2 MB bots can read. Save a smaller copy or split it.`;++/** A file the person chose: being added, or why it wasn't. */+type Pending =+ | { id: number; file: File; state: 'adding' }+ | { id: number; file: File; state: 'problem'; text: string }+ | { id: number; file: File; state: 'exists' };++/** Words for a file that wasn't added (design §1 States). */+export function problemText(kind: string, file: { name: string; size: number }): string {+ switch (kind) {+ case 'bad_name':+ return 'Names can’t start with a dot or contain “..”. Rename it, then add it.';+ case 'wrong_kind':+ return 'Bots read .md, .txt and .pdf. Save it as a PDF, then add it.';+ case 'too_large':+ return tooBig(file.size);+ case 'no_text':+ return 'It has no text bots can read (it looks like a scan). Export it with text, or paste the words into a .txt.';+ case 'unreadable':+ return 'Bots couldn’t read it. Save it again as UTF-8 text or a fresh PDF, then add it.';+ case 'docs_link':+ return 'This space’s documents folder is a link, so kwant won’t write into it.';+ case 'limit':+ return 'This space already has 200 documents. Remove one to add another.';+ case 'archived':+ return 'This space is archived, so its documents can’t change.';+ default:+ return 'Something went wrong while adding it. Try again.';+ }+}++/** Settings › Documents (design §1): see, add and remove this space's files. */+export const SpaceDocsTab: React.FC<{ spaceId: string; spaceName: string; isPhone?: boolean }> = ({ spaceId, isPhone = false }) => {+ const [list, setList] = useState<SpaceDocList | null>(null);+ const [failed, setFailed] = useState(false);+ // Add, remove and the page text come in the second server step: hidden until the server has them.+ const [canEdit, setCanEdit] = useState(false);+ const [pending, setPending] = useState<Pending[]>([]);+ const [confirm, setConfirm] = useState<string | null>(null);+ const [said, setSaid] = useState('');+ const [over, setOver] = useState(false);+ const [viewer, setViewer] = useState<DocViewerOpen | null>(null);+ const [copied, setCopied] = useState(false);+ const inputRef = useRef<HTMLInputElement>(null);+ const chooseRef = useRef<HTMLButtonElement>(null);+ const panelRef = useRef<HTMLDivElement>(null);+ const nextId = useRef(1);+ const queue = useRef<Promise<void>>(Promise.resolve());++ const load = useCallback(() => {+ setFailed(false);+ return spaceDocsApi.list(spaceId).then(+ (l) => setList(l),+ () => setFailed(true),+ );+ }, [spaceId]);++ useEffect(() => {+ setList(null);+ setPending([]);+ setConfirm(null);+ load();+ let live = true;+ spaceDocsApi.hasRoutes(spaceId).then((yes) => live && setCanEdit(yes));+ return () => {+ live = false;+ };+ }, [spaceId, load]);++ const docs = list ? sortDocs(list.docs) : [];+ const atLimit = docs.length >= DOC_MAX_COUNT;++ const update = (id: number, p: Pending | null) => setPending((all) => (p ? all.map((x) => (x.id === id ? p : x)) : all.filter((x) => x.id !== id)));++ const send = async (id: number, file: File, replace = false) => {+ update(id, { id, file, state: 'adding' });+ const r = await spaceDocsApi.add(spaceId, file, replace);+ if (r.ok) {+ update(id, null);+ setSaid(`${file.name} added`);+ await load();+ } else if (r.kind === 'exists') update(id, { id, file, state: 'exists' });+ else if (r.kind === 'no_route' || r.kind === 'person_only') {+ // No add here (an older server, or a view that isn't the person's): hide it, no row.+ update(id, null);+ setCanEdit(false);+ } else {+ update(id, { id, file, state: 'problem', text: problemText(r.kind, file) });+ // Full: the list catches up, so the 200-documents box replaces the drop zone.+ if (r.kind === 'limit') await load();+ }+ };++ /** Several files at once go one at a time, each with its own row. */+ const addFiles = (files: File[]) => {+ if (!canEdit || !files.length) return;+ const rows: Pending[] = files.map((file) => {+ const id = nextId.current++;+ const bad = checkFile(file);+ return bad ? { id, file, state: 'problem', text: problemText(bad.kind, file) } : { id, file, state: 'adding' };+ });+ setPending((all) => [...rows, ...all]);+ for (const row of rows) if (row.state === 'adding') queue.current = queue.current.then(() => send(row.id, row.file));+ };++ const remove = async (name: string) => {+ const at = docs.findIndex((d) => d.name === name);+ const r = await spaceDocsApi.remove(spaceId, name);+ setConfirm(null);+ if (r === 'no_route') {+ setCanEdit(false);+ return;+ }+ if (r === 'failed') {+ setSaid(`${name} wasn’t removed. Try again.`);+ return;+ }+ setSaid(`${name} removed`);+ const next = docs.filter((d) => d.name !== name);+ await load();+ // Focus moves to the next row's remove, or to Choose files when the list is empty.+ requestAnimationFrame(() => {+ const target = next[Math.min(at, next.length - 1)];+ const el = target ? panelRef.current?.querySelector<HTMLElement>(`[data-doc-remove="${CSS.escape(target.name)}"]`) : chooseRef.current;+ (el ?? chooseRef.current)?.focus();+ });+ };++ // Drop anywhere on the tab.+ const dragProps = canEdit && !isPhone && !atLimit+ ? {+ onDragOver: (e: React.DragEvent) => {+ if (![...e.dataTransfer.types].includes('Files')) return;+ e.preventDefault();+ setOver(true);+ },+ onDragLeave: (e: React.DragEvent) => {+ if (!panelRef.current?.contains(e.relatedTarget as Node)) setOver(false);+ },+ onDrop: (e: React.DragEvent) => {+ e.preventDefault();+ setOver(false);+ addFiles([...e.dataTransfer.files]);+ },+ }+ : {};++ const choose = (+ <button+ ref={chooseRef}+ type="button"+ onClick={() => inputRef.current?.click()}+ className={`${primaryBtn} ${isPhone ? 'w-full h-11' : 'h-8'}`}+ data-choose-files+ >+ <Upload size={14} aria-hidden="true" /> Choose files+ </button>+ );++ const dropZone =+ !canEdit || !list || docs.length === 0 ? null : atLimit ? (+ <div className="flex items-start gap-2.5 rounded-xl border border-zinc-800 bg-zinc-900/60 p-3.5 text-[13px] text-zinc-300" data-docs-limit>+ <AlertTriangle size={14} className="mt-[3px] shrink-0 text-amber-300" aria-hidden="true" />+ <p>+ <strong className="font-semibold text-zinc-100">200 documents</strong>, the most bots can use in one space. Remove one to add another.+ </p>+ </div>+ ) : isPhone ? (+ <div className="space-y-2 p-4 rounded-xl border border-zinc-800 bg-zinc-900/50" data-docs-drop>+ <p className="text-[13px] font-medium text-zinc-100">Add your files</p>+ <p className="text-xs text-zinc-400">.md, .txt or a PDF with text in it · up to 2 MB each</p>+ {choose}+ </div>+ ) : (+ <div+ className={`flex items-center gap-3.5 p-4 rounded-xl border border-dashed transition-colors motion-reduce:transition-none ${over ? 'border-violet-400 bg-violet-400/[.06]' : 'border-zinc-700 bg-zinc-900/50'}`}+ data-docs-drop+ data-over={over || undefined}+ >+ <span className="shrink-0 inline-flex items-center justify-center w-9 h-9 rounded-[10px] bg-zinc-900 border border-zinc-800" aria-hidden="true">+ <Upload size={18} className="text-violet-300" />+ </span>+ <div className="min-w-0 flex-1">+ <p className="text-[13px] font-medium text-zinc-100">Drop files here, or choose them</p>+ <p className="text-xs text-zinc-400">.md, .txt or a PDF with text in it · up to 2 MB each</p>+ </div>+ {choose}+ </div>+ );++ const empty = list && docs.length === 0 && (+ <div+ className={`flex flex-col items-center text-center gap-2 px-4 py-8 rounded-xl border ${isPhone ? 'border-zinc-800' : 'border-dashed'} ${+ over ? 'border-violet-400 bg-violet-400/[.06]' : `${isPhone ? '' : 'border-zinc-700'} bg-zinc-900/50`+ }`}+ data-docs-empty+ >+ <span className="inline-flex items-center justify-center w-10 h-10 rounded-[10px] bg-zinc-900 border border-zinc-800" aria-hidden="true">+ <FileText size={18} className="text-violet-300" />+ </span>+ <p className="text-sm font-medium text-zinc-100">No documents yet</p>+ <p className="max-w-[420px] text-[13px] text-zinc-300 leading-relaxed">+ Add your FAQ, returns policy or price list. Bots in this space quote them word for word, so answers come from your own papers, not from memory.+ </p>+ {canEdit && <div className={isPhone ? 'w-full mt-1' : 'mt-1'}>{choose}</div>}+ <p className="text-xs text-zinc-400">+ {canEdit && !isPhone ? 'or drop them here · ' : ''}.md, .txt or a PDF with text in it · up to 2 MB each+ </p>+ </div>+ );++ const pendingRow = (p: Pending) => {+ const name = p.file.name;+ if (p.state === 'adding')+ return (+ <li key={`p${p.id}`} className={`flex items-center gap-3 ${isPhone ? 'p-3' : 'px-3.5 py-3'}`} data-doc-pending="adding">+ <DocMark name={name} />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-zinc-100 truncate" title={name}>+ {name}+ </p>+ <p className="flex items-center gap-1 text-xs text-zinc-400">+ <Loader2 size={12} className="motion-safe:animate-spin" aria-hidden="true" /> Adding…+ </p>+ </div>+ </li>+ );+ const dismiss = (+ <button+ type="button"+ aria-label="Dismiss"+ onClick={() => update(p.id, null)}+ className={`shrink-0 inline-flex items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100 ${isPhone ? 'w-11 h-11 -my-1.5 -mr-2' : 'w-8 h-8'} ${focusRing}`}+ >+ <X size={16} aria-hidden="true" />+ </button>+ );+ if (p.state === 'exists')+ return (+ <li key={`p${p.id}`} className={`bg-amber-300/[.05] ${isPhone ? 'p-3' : 'px-3.5 py-3'}`} data-doc-pending="exists">+ <div className={isPhone ? 'space-y-2.5' : 'flex items-center gap-3'}>+ <div className="flex items-center gap-3 min-w-0 flex-1">+ <DocMark name={name} />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-zinc-100 truncate" title={name}>+ {name} is already here+ </p>+ <p className="text-xs text-zinc-300">Replace it with the one you just chose?</p>+ </div>+ </div>+ <div className={isPhone ? 'grid grid-cols-2 gap-2' : 'flex shrink-0 gap-2'}>+ <button type="button" className={`${quietBtn} ${isPhone ? 'h-11' : 'h-7'}`} onClick={() => update(p.id, null)}>+ Keep old+ </button>+ <button type="button" className={`${primaryBtn} ${isPhone ? 'h-11' : 'h-7'}`} onClick={() => (queue.current = queue.current.then(() => send(p.id, p.file, true)))}>+ Replace+ </button>+ </div>+ </div>+ </li>+ );+ const shownMark = docKind(name) ? name : `x.${markOf(name).toLowerCase()}`;+ return (+ <li key={`p${p.id}`} className={`flex items-start gap-3 bg-amber-300/[.05] ${isPhone ? 'p-3' : 'px-3.5 py-3'}`} data-doc-pending="problem">+ <DocMark name={shownMark} />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-zinc-100 truncate" title={name}>+ {name} wasn’t added+ </p>+ <p className="flex items-start gap-1 text-xs text-zinc-300">+ <AlertTriangle size={12} className="mt-0.5 shrink-0 text-amber-300" aria-hidden="true" />+ <span>{p.text}</span>+ </p>+ </div>+ {dismiss}+ </li>+ );+ };++ const docRow = (d: SpaceDoc) => {+ if (confirm === d.name)+ return (+ <li key={d.name} className={`bg-rose-300/[.06] ${isPhone ? 'p-3' : 'px-3.5 py-3'}`} data-doc-confirm={d.name}>+ <RemoveConfirm name={d.name} isPhone={isPhone} onCancel={() => setConfirm(null)} onRemove={() => remove(d.name)} />+ </li>+ );+ return (+ <li key={d.name} className={`flex items-center gap-3 ${isPhone ? 'p-3' : 'px-3.5 py-3'}`} data-doc={d.name}>+ <button+ type="button"+ className={`flex items-center gap-3 min-w-0 flex-1 -m-1.5 p-1.5 rounded-lg text-left hover:bg-zinc-900/70 ${focusRing}`}+ onClick={() =>+ setViewer({ space: spaceId, file: d.name, page: 1, size: d.size, modified: d.modified, pages: d.pages })+ }+ data-doc-open={d.name}+ >+ <DocMark name={d.name} />+ <span className="min-w-0 flex-1">+ <span className="block text-sm font-medium text-zinc-100 truncate" title={d.name}>+ {d.name}+ </span>+ {d.too_large ? (+ <span className="flex items-start gap-1 text-xs text-amber-200">+ <AlertTriangle size={12} className="mt-0.5 shrink-0 text-amber-300" aria-hidden="true" />+ <span>{formatSize(d.size)}, over the 2 MB bots can read. Save a smaller copy or split it.</span>+ </span>+ ) : (+ <span className="block text-xs text-zinc-400 truncate">{docMeta(d)}</span>+ )}+ </span>+ </button>+ {canEdit && (+ <button+ type="button"+ aria-label={`Remove ${d.name}`}+ onClick={() => setConfirm(d.name)}+ data-doc-remove={d.name}+ className={`shrink-0 inline-flex items-center justify-center rounded-lg text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100 ${isPhone ? 'w-11 h-11 -my-1.5 -mr-2' : 'w-8 h-8'} ${focusRing}`}+ >+ <Trash2 size={16} aria-hidden="true" />+ </button>+ )}+ </li>+ );+ };++ const count = docs.length;+ const copyFolder = () => {+ if (!list) return;+ navigator.clipboard?.writeText(list.folder).catch(() => {});+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1500);+ };++ return (+ <div ref={panelRef} className="relative" data-space-docs {...dragProps}>+ <p className="text-[13px] text-zinc-300 leading-relaxed mb-3.5">+ Your FAQ, policies and price lists. Bots in this space answer from these files and quote them word for word, and every quote is checked against the file.+ </p>+ <input+ ref={inputRef}+ type="file"+ multiple+ accept={DOC_ACCEPT}+ className="hidden"+ tabIndex={-1}+ aria-hidden="true"+ onChange={(e) => {+ addFiles([...(e.target.files ?? [])]);+ e.target.value = '';+ }}+ />+ {list === null && !failed && canEdit && !isPhone && (+ <div className="flex items-center gap-3.5 p-4 rounded-xl border border-dashed border-zinc-700 bg-zinc-900/50">+ <span className="shrink-0 inline-flex items-center justify-center w-9 h-9 rounded-[10px] bg-zinc-900 border border-zinc-800" aria-hidden="true">+ <Upload size={18} className="text-violet-300" />+ </span>+ <div className="min-w-0 flex-1">+ <p className="text-[13px] font-medium text-zinc-100">Drop files here, or choose them</p>+ <p className="text-xs text-zinc-400">.md, .txt or a PDF with text in it · up to 2 MB each</p>+ </div>+ {choose}+ </div>+ )}+ {dropZone}+ {empty}++ {(list === null || failed || count > 0 || pending.length > 0) && (+ <div className="mt-5">+ <div className="flex items-baseline justify-between gap-3 mb-2">+ <p className="text-[11px] font-semibold tracking-[.08em] uppercase text-zinc-300" role={list === null && !failed ? 'status' : undefined}>+ {list === null && !failed ? 'Loading documents…' : 'In this space'}+ </p>+ {list && count > 0 && <p className="text-[11px] text-zinc-500">{count === 1 ? '1 document' : `${count} documents`}</p>}+ </div>+ <ul className="rounded-xl border border-zinc-800 bg-zinc-900/60 divide-y divide-zinc-800 overflow-hidden" aria-label="Documents in this space">+ {pending.map(pendingRow)}+ {failed ? (+ <li className="flex flex-wrap items-center gap-2 px-3.5 py-3 text-[13px] text-zinc-300" data-docs-failed>+ <AlertTriangle size={14} className="text-amber-300" aria-hidden="true" />+ Couldn’t load this space’s documents.+ <button type="button" className={`${quietBtn} h-8`} onClick={() => load()}>+ <RotateCw size={12} aria-hidden="true" /> Try again+ </button>+ </li>+ ) : list === null ? (+ [48, 36, 56].map((w, i) => (+ <li key={i} className="flex items-center gap-3 px-3.5 py-3" aria-hidden="true" data-docs-skeleton>+ <span className="w-8 h-8 rounded-lg border border-zinc-700" />+ <span className="flex-1 space-y-1.5">+ <span className="block h-3 rounded bg-zinc-800" style={{ width: `${w}%` }} />+ <span className="block h-2.5 rounded bg-zinc-800" style={{ width: `${w - 14}%` }} />+ </span>+ </li>+ ))+ ) : (+ docs.map(docRow)+ )}+ </ul>+ {list?.more && (+ <p className="mt-2 text-xs text-zinc-400" data-docs-more>+ {list.more_count+ ? `The folder has ${list.more_count} more files than this. Bots only see the first 200, by name.`+ : 'The folder has more files than this. Bots only see the first 200, by name.'}+ </p>+ )}+ </div>+ )}++ {list && (+ <p className="mt-4 text-xs text-zinc-400 leading-relaxed [overflow-wrap:anywhere]" data-docs-folder>+ Files you put in{' '}+ <code className="rounded-md border border-zinc-800 bg-zinc-900 px-1.5 py-0.5 text-[11.5px] text-zinc-300" title={list.folder}>+ {shortFolder(list.folder)}+ </code>{' '}+ show here too.+ {!isPhone && (+ <>+ {' '}+ <button type="button" onClick={copyFolder} className={`inline-flex items-center gap-1 align-middle rounded text-violet-300 hover:text-violet-200 hover:underline ${focusRing}`}>+ <Copy size={12} aria-hidden="true" /> {copied ? 'Copied' : 'Copy folder'}+ </button>+ </>+ )}+ </p>+ )}+ {list && isPhone && (+ <div className="mt-1">+ <button type="button" onClick={copyFolder} className={`inline-flex items-center gap-1 h-11 -my-1.5 rounded text-xs text-violet-300 hover:text-violet-200 hover:underline ${focusRing}`}>+ <Copy size={12} aria-hidden="true" /> {copied ? 'Copied' : 'Copy folder'}+ </button>+ </div>+ )}++ <p className="sr-only" role="status" aria-live="polite">+ {said}+ </p>+ {viewer && <DocViewerSheet open={viewer} onClose={() => setViewer(null)} />}+ </div>+ );+};++/** The inline remove confirm: focus on Cancel, Esc cancels. */+const RemoveConfirm: React.FC<{ name: string; isPhone: boolean; onCancel: () => void; onRemove: () => void }> = ({ name, isPhone, onCancel, onRemove }) => {+ const cancelRef = useRef<HTMLButtonElement>(null);+ const [busy, setBusy] = useState(false);+ useEffect(() => cancelRef.current?.focus(), []);+ return (+ <div+ className={isPhone ? 'space-y-2.5' : 'flex items-center gap-3'}+ onKeyDown={(e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ onCancel();+ }+ }}+ >+ <div className="flex items-center gap-3 min-w-0 flex-1">+ <DocMark name={name} />+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium text-zinc-100 truncate" title={name}>+ Remove {name}?+ </p>+ <p className="text-xs text-zinc-300">Bots can’t quote it after this. Replies that already quote it keep their words.</p>+ </div>+ </div>+ <div className={isPhone ? 'grid grid-cols-2 gap-2' : 'flex shrink-0 gap-2'}>+ <button ref={cancelRef} type="button" className={`${quietBtn} ${isPhone ? 'h-11' : 'h-8'}`} onClick={onCancel}>+ Cancel+ </button>+ <button+ type="button"+ disabled={busy}+ className={`${dangerBtn} ${isPhone ? 'h-11' : 'h-8'}`}+ onClick={() => {+ setBusy(true);+ onRemove();+ }}+ >+ <Trash2 size={14} aria-hidden="true" /> Remove+ </button>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex 97edf72d..dbbed41b 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -7,6 +7,7 @@ import {CalendarClock,Check,Download,+ FileText,FileUp,Globe,LayoutGrid,@@ -36,6 +37,7 @@ import { ImportError, ImportRecord, downloadExport, importApi, importErrorText }import { memberIdsOf, type Channel, type Kwant, type Team } from './Sidebar';import { SpaceApprovalsSetting } from './ApprovalsSetting';import { DevModeSettings } from './DevModeSettings';+import { SpaceDocsTab } from './SpaceDocsTab';import type { AppsSection, SettingsScope, SpaceSettingsTab } from '../nav';import { AppsAccounts } from './AppsAccounts';@@ -50,6 +52,7 @@ const TABS: Array<{ id: SpaceSettingsTab; label: string; icon: React.ReactNode }{ id: 'apps', label: 'Apps & accounts', icon: <LayoutGrid size={15} /> },{ id: 'bots', label: 'Kwant bots', icon: <Bot size={15} /> },{ id: 'teams', label: 'Teams', icon: <Users size={15} /> },+ { id: 'docs', label: 'Documents', icon: <FileText size={15} /> },{ id: 'skills', label: 'Skills', icon: <Sparkles size={15} /> },{ id: 'routines', label: 'Routines', icon: <CalendarClock size={15} /> },{ id: 'import', label: 'Import & export', icon: <FileUp size={15} /> },@@ -257,6 +260,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {)}{tab === 'bots' && <BotsTab {...tp} />}{tab === 'teams' && <TeamsTab {...p} />}+ {tab === 'docs' && <SpaceDocsTab key={space.id} spaceId={space.id} spaceName={space.name} isPhone={p.isPhone} />}{tab === 'skills' && <SkillsTab {...p} />}{tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} onOpenSettings={toApp} onOpenRunResult={p.onOpenRunResult} />}{tab === 'import' && <ImportTab {...tp} />}diff --git a/frontend/src/nav.ts b/frontend/src/nav.tsindex cd137538..08b0d811 100644--- a/frontend/src/nav.ts+++ b/frontend/src/nav.ts@@ -7,7 +7,7 @@export type InboxTab = 'new' | 'loose';/** Settings › This space tabs. Kept here, not in the component, so routing stays pure. */-export const SPACE_SETTINGS_TABS = ['general', 'apps', 'bots', 'teams', 'skills', 'routines', 'import'] as const;+export const SPACE_SETTINGS_TABS = ['general', 'apps', 'bots', 'teams', 'docs', 'skills', 'routines', 'import'] as const;export type SpaceSettingsTab = (typeof SPACE_SETTINGS_TABS)[number];export type SettingsScope = 'space' | 'app';diff --git a/frontend/src/spaceDocs.ts b/frontend/src/spaceDocs.tsnew file mode 100644index 00000000..846b0274--- /dev/null+++ b/frontend/src/spaceDocs.ts@@ -0,0 +1,370 @@+// Space documents (space-docs/design.md): a space's own FAQ, policies and price lists, which bots quote+// word for word. The list and the cite check are #601's routes; add, remove and the page text are the+// second server step, and the tab works read-only until they exist.++import { personFetch } from './auth';++export interface SpaceDoc {+ name: string;+ size: number;+ /** RFC 3339. */+ modified: string;+ /** PDFs only. */+ pages?: number;+ /** Over the 2 MB bots can read. */+ too_large?: boolean;+}++export interface SpaceDocList {+ /** The docs folder's absolute path; shown only in the tab's footer. */+ folder: string;+ docs: SpaceDoc[];+ /** The folder has more files than the 200 listed. */+ more: boolean;+ /** How many more, when the server says. */+ more_count?: number;+}++export interface DocPage {+ file: string;+ page: number;+ pages: number;+ text_before: string;+ match: string;+ text_after: string;+ cut_before: boolean;+ cut_after: boolean;+}++export const DOC_MAX_BYTES = 2 * 1024 * 1024;+export const DOC_MAX_COUNT = 200;+export const DOC_ACCEPT = '.md,.markdown,.txt,.pdf,text/markdown,text/plain,application/pdf';++export type DocKind = 'pdf' | 'md' | 'txt';++/** The file's lower-case extension, without the dot ('' when it has none). */+export function extOf(name: string): string {+ const i = name.lastIndexOf('.');+ return i > 0 ? name.slice(i + 1).toLowerCase() : '';+}++export function docKind(name: string): DocKind | null {+ const e = extOf(name);+ if (e === 'pdf') return 'pdf';+ if (e === 'md' || e === 'markdown') return 'md';+ if (e === 'txt') return 'txt';+ return null;+}++/** The type mark's letters: PDF, MD, TXT, or the odd extension upper-cased ("DOCX"). */+export function markOf(name: string): string {+ const k = docKind(name);+ if (k) return k.toUpperCase();+ return (extOf(name) || 'FILE').toUpperCase().slice(0, 4);+}++/** QA F2 and #601's own name rule: no leading dot, no "..", no folders. */+export function badName(name: string): boolean {+ return !name || name !== name.trim() || name.startsWith('.') || name.includes('..') || /[/\\\0]/.test(name);+}++export type FileProblem = { kind: 'bad_name' } | { kind: 'wrong_kind' } | { kind: 'too_large'; size: number };++/** Checked in the browser before anything is sent: the name, then the kind, then the size. */+export function checkFile(f: { name: string; size: number }): FileProblem | null {+ if (badName(f.name)) return { kind: 'bad_name' };+ if (!docKind(f.name)) return { kind: 'wrong_kind' };+ if (f.size > DOC_MAX_BYTES) return { kind: 'too_large', size: f.size };+ return null;+}++/** KB below 1 MB, one decimal of MB above. */+export function formatSize(bytes: number): string {+ if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++/** "today", "yesterday", "3 days ago", then "Oct 28". */+export function updatedWhen(iso: string, now: number = Date.now()): string {+ const t = Date.parse(iso);+ if (Number.isNaN(t)) return '';+ const day = (ms: number) => {+ const d = new Date(ms);+ return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()) / 86_400_000;+ };+ const d = Math.max(0, day(now) - day(t));+ if (d === 0) return 'today';+ if (d === 1) return 'yesterday';+ if (d < 7) return `${d} days ago`;+ return new Date(t).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });+}++/** "4 pages · 312 KB · updated 3 days ago"; pages only for PDFs. */+export function docMeta(d: SpaceDoc, now: number = Date.now()): string {+ const parts: string[] = [];+ if (docKind(d.name) === 'pdf' && d.pages) parts.push(`${d.pages} ${d.pages === 1 ? 'page' : 'pages'}`);+ parts.push(formatSize(d.size));+ const when = updatedWhen(d.modified, now);+ if (when) parts.push(`updated ${when}`);+ return parts.join(' · ');+}++/** Newest first, so a file just added shows at the top. */+export function sortDocs(docs: SpaceDoc[]): SpaceDoc[] {+ return [...docs].sort((a, b) => (Date.parse(b.modified) || 0) - (Date.parse(a.modified) || 0) || a.name.localeCompare(b.name));+}++/** The folder for the footer: the home folder as "~" and a long space id cut after 8 characters ("spc_7f3a…"). */+export function shortFolder(folder: string): string {+ return folder+ .replace(/^(\/home\/[^/]+|\/Users\/[^/]+|[A-Za-z]:\\Users\\[^\\]+)(?=[/\\]|$)/, '~')+ .replace(/([/\\]spaces[/\\])([^/\\]{10,})(?=[/\\]|$)/, (_m, pre: string, id: string) => `${pre}${id.slice(0, 8)}…`);+}++// ── kwant-doc:// addresses ──++export interface DocRef {+ space: string;+ file: string;+ /** PDFs only. */+ page: number | null;+ /** The `:~:text=` part, decoded; null when the link quotes nothing. */+ quote: string | null;+}++export const DOC_SCHEME = 'kwant-doc://';++const decode = (s: string): string | null => {+ try {+ return decodeURIComponent(s);+ } catch {+ return null;+ }+};++/** `kwant-doc://<space>/<file>[#page=N][:~:text=<quote>]`, as #601's cite route writes it. Null if it isn't one. */+export function parseDocUrl(href: string | null | undefined): DocRef | null {+ if (!href || !href.startsWith(DOC_SCHEME)) return null;+ const rest = href.slice(DOC_SCHEME.length);+ const hash = rest.indexOf('#');+ const path = hash < 0 ? rest : rest.slice(0, hash);+ const frag = hash < 0 ? '' : rest.slice(hash + 1);+ const slash = path.indexOf('/');+ if (slash <= 0) return null;+ const space = decode(path.slice(0, slash));+ const file = decode(path.slice(slash + 1));+ if (!space || !file || badName(file) || !docKind(file)) return null;+ const directive = frag.indexOf(':~:');+ const head = directive < 0 ? frag : frag.slice(0, directive);+ const pageMatch = /^page=(\d+)$/.exec(head);+ const page = docKind(file) === 'pdf' && pageMatch ? Math.max(1, Number(pageMatch[1])) : null;+ let quote: string | null = null;+ if (directive >= 0) {+ const text = /(?:^|&)text=([^&]*)/.exec(frag.slice(directive + 3));+ if (text) quote = decode(text[1]) || null;+ }+ return { space, file, page, quote };+}++/** "Returns policy.pdf, page 2" or "faq.md". */+export const docPlace = (r: Pick<DocRef, 'file' | 'page'>) => (r.page ? `${r.file}, page ${r.page}` : r.file);++// ── Re-checking a quote (§2): once per space, file and quote for the session, at most 4 at a time ──++/** ok: the words are in the file now. missing: not found now (422 or 404). unknown: no mark at all. */+export type CiteState = 'ok' | 'missing' | 'gone' | 'unknown';++export const citeKey = (space: string, file: string, quote: string) => JSON.stringify([space, file, quote]);++const citeCache = new Map<string, Promise<CiteState>>();+let citeRunning = 0;+const citeQueue: Array<() => void> = [];+export const CITE_PARALLEL = 4;++async function limited<T>(job: () => Promise<T>): Promise<T> {+ if (citeRunning >= CITE_PARALLEL) await new Promise<void>((go) => citeQueue.push(go));+ citeRunning++;+ try {+ return await job();+ } finally {+ citeRunning--;+ citeQueue.shift()?.();+ }+}++/** Maps the cite route's answer to the chip's mark. */+export function citeStateOf(status: number): CiteState {+ if (status >= 200 && status < 300) return 'ok';+ if (status === 422) return 'missing';+ if (status === 404) return 'gone';+ return 'unknown';+}++/** The chip's check; a second call for the same quote shares the first one's answer. */+export function recheckQuote(space: string, file: string, quote: string, send: typeof fetch = (...a) => fetch(...a)): Promise<CiteState> {+ const key = citeKey(space, file, quote);+ const hit = citeCache.get(key);+ if (hit) return hit;+ const p = limited(() =>+ send(`/api/spaces/${encodeURIComponent(space)}/docs/cite`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ file, quote }),+ }).then(+ (r) => citeStateOf(r.status),+ () => 'unknown' as const,+ ),+ );+ citeCache.set(key, p);+ // A quiet chip after a network hiccup can try again on the next mount.+ p.then((s) => s === 'unknown' && citeCache.delete(key));+ return p;+}++/** Tests only. */+export function _resetCiteCache() {+ citeCache.clear();+ citeRunning = 0;+ citeQueue.length = 0;+}++// ── The routes ──++const base = (space: string) => `/api/spaces/${encodeURIComponent(space)}/docs`;++/** The server's `{ error, code }`; both '' when the answer has no JSON error of its own. */+async function errorOf(r: Response): Promise<{ error: string; code: string }> {+ const body = (await r+ .clone()+ .json()+ .catch(() => null)) as { error?: unknown; code?: unknown } | null;+ const str = (v: unknown) => (typeof v === 'string' ? v : '');+ return body && typeof body === 'object' ? { error: str(body.error), code: str(body.code) } : { error: '', code: '' };+}++async function errorText(r: Response): Promise<string> {+ return (await errorOf(r)).error;+}++/** A 404 or 405 from a route the server doesn't have yet (no JSON error of its own). */+async function routeMissing(r: Response): Promise<boolean> {+ if (r.status === 405) return true;+ if (r.status !== 404) return false;+ return !(await errorText(r));+}++export type AddProblem =+ | 'exists'+ | 'bad_name'+ | 'wrong_kind'+ | 'too_large'+ | 'no_text'+ | 'unreadable'+ | 'docs_link'+ | 'limit'+ | 'archived'+ | 'person_only'+ | 'no_route'+ | 'failed';++export type AddResult = { ok: true; doc: SpaceDoc } | { ok: false; kind: AddProblem; detail?: string };++const ADD_CODES: Record<string, AddProblem> = {+ bad_name: 'bad_name',+ wrong_kind: 'wrong_kind',+ too_large: 'too_large',+ exists: 'exists',+ docs_link: 'docs_link',+ full: 'limit',+ no_text: 'no_text',+ unreadable: 'unreadable',+ person_only: 'person_only',+};++/**+ * Maps an add's answer (Vega's route) to what the row says. The error's `code` decides, never the status or the+ * words: two 409s and two 422s mean different things, and the words carry the file's own name. Without a code,+ * only a proxy's bare 413 and the archived space's 409 (the one 409 without a code) are told apart.+ */+export function addResultOf(status: number, code: string, error = ''): Exclude<AddResult, { ok: true }> {+ const kind = ADD_CODES[code];+ if (kind) return { ok: false, kind, detail: error };+ if (!code && status === 413) return { ok: false, kind: 'too_large', detail: error };+ if (!code && status === 409) return { ok: false, kind: 'archived', detail: error };+ return { ok: false, kind: 'failed', detail: error };+}++/** The add route's address: the name in the query, as the file goes as the raw body. */+export const addUrl = (space: string, name: string, replace = false) =>+ `${base(space)}?name=${encodeURIComponent(name)}${replace ? '&replace=1' : ''}`;++export const spaceDocsApi = {+ list: async (space: string): Promise<SpaceDocList> => {+ const r = await fetch(base(space), { cache: 'no-store' });+ if (!r.ok) throw new Error((await errorText(r)) || 'Couldn’t load this space’s documents.');+ return r.json();+ },++ /**+ * Whether add, remove and the page text exist on this server (they come in a second server step). The page+ * route with an empty name answers 400 when it is there; a 404 or 405 without an error of its own means it+ * isn't yet. It is a read, so it never asks "Confirm it's you".+ */+ hasRoutes: async (space: string): Promise<boolean> => {+ try {+ const r = await fetch(`${base(space)}/page?file=&page=1`, { cache: 'no-store' });+ return !(await routeMissing(r));+ } catch {+ return false;+ }+ },++ /** The file is the raw body and its name is in the query (Vega's route has no multipart): no FormData, no Content-Type. */+ add: async (space: string, file: File, replace = false): Promise<AddResult> => {+ let r: Response;+ try {+ r = await personFetch(addUrl(space, file.name, replace), { method: 'POST', body: file });+ } catch {+ return { ok: false, kind: 'failed' };+ }+ if (r.ok) {+ const doc = (await r.json().catch(() => null)) as SpaceDoc | null;+ return { ok: true, doc: doc && typeof doc.name === 'string' ? doc : { name: file.name, size: file.size, modified: new Date().toISOString() } };+ }+ if (await routeMissing(r)) return { ok: false, kind: 'no_route' };+ const { error, code } = await errorOf(r);+ const res = addResultOf(r.status, code, error);+ // A replace refused as `exists` is a folder with the document's name: asking again can't help.+ return replace && res.kind === 'exists' ? { ok: false, kind: 'failed', detail: error } : res;+ },++ /** 'ok', 'no_route' (hide remove), or an error to show. */+ remove: async (space: string, name: string): Promise<'ok' | 'no_route' | 'failed'> => {+ try {+ const r = await personFetch(`${base(space)}/${encodeURIComponent(name)}`, { method: 'DELETE' });+ if (r.ok || r.status === 404) return r.ok || (await errorText(r)) ? 'ok' : 'no_route';+ if (await routeMissing(r)) return 'no_route';+ return 'failed';+ } catch {+ return 'failed';+ }+ },++ /** 'no_route' until Vega's page route is on this server: the viewer then shows only the quote. */+ page: async (space: string, file: string, page: number, quote?: string | null): Promise<DocPage | 'gone' | 'no_route' | 'failed'> => {+ const q = new URLSearchParams({ file, page: String(page) });+ if (quote) q.set('quote', quote);+ try {+ const r = await fetch(`${base(space)}/page?${q}`, { cache: 'no-store' });+ if (r.ok) return (await r.json()) as DocPage;+ if (await routeMissing(r)) return 'no_route';+ if (r.status === 404) return 'gone';+ return 'failed';+ } catch {+ return 'failed';+ }+ },+};++/** "faq.md removed" etc., for the polite live region. */+export const copyQuote = (quote: string, file: string, page: number | null) => `${quote} — ${file}${page ? `, p. ${page}` : ''}`;diff --git a/frontend/tests/spaceDocs.test.mjs b/frontend/tests/spaceDocs.test.mjsnew file mode 100644index 00000000..dc1ae523--- /dev/null+++ b/frontend/tests/spaceDocs.test.mjs@@ -0,0 +1,218 @@+// Space documents (space-docs/design.md, Build split 5): the kwant-doc:// address, the re-check cache, and the+// checks a file gets in the browser before it is sent. Table style.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++const m = await loadBundled(`+ export * from './src/spaceDocs';+ export { problemText } from './src/components/SpaceDocsTab';+`);++test('parseDocUrl: name, page and quote, as the cite route writes them', () => {+ for (const [href, want, why] of [+ ['kwant-doc://spc_default/faq.md', { space: 'spc_default', file: 'faq.md', page: null, quote: null }, 'plain'],+ ['kwant-doc://shop/plan.pdf#page=2:~:text=Budget%20is%2042%20euros', { space: 'shop', file: 'plan.pdf', page: 2, quote: 'Budget is 42 euros' }, 'PDF page and quote'],+ ['kwant-doc://shop/Returns%20Policy.pdf#page=1', { space: 'shop', file: 'Returns Policy.pdf', page: 1, quote: null }, 'percent-encoded name'],+ ['kwant-doc://spc_default/faq.md#:~:text=return%20any%20item%20within%2030%20days', { space: 'spc_default', file: 'faq.md', page: null, quote: 'return any item within 30 days' }, '.md quote, no page'],+ ['kwant-doc://s/faq.md#page=3:~:text=x', { space: 's', file: 'faq.md', page: null, quote: 'x' }, 'no page for .md, even if the link has one'],+ ['kwant-doc://s/caf%C3%A9%20menu.txt#:~:text=%E2%80%9Cfree%E2%80%9D%2C%2050%25%20off', { space: 's', file: 'café menu.txt', page: null, quote: '“free”, 50% off' }, 'UTF-8 and punctuation'],+ ['kwant-doc://s/notes.markdown', { space: 's', file: 'notes.markdown', page: null, quote: null }, '.markdown'],+ ])+ assert.deepEqual(m.parseDocUrl(href), want, why);+});++test('parseDocUrl: anything else is not a document address', () => {+ for (const [href, why] of [+ ['https://example.com/faq.md', 'another scheme'],+ ['kwant-doc://faq.md', 'no space'],+ ['kwant-doc:///faq.md', 'empty space'],+ ['kwant-doc://s/../kwnt.db', 'a path out'],+ ['kwant-doc://s/sub/faq.md', 'a folder'],+ ['kwant-doc://s/.env.md', 'leading dot'],+ ['kwant-doc://s/photo.png', 'not a kind kwant reads'],+ ['kwant-doc://s/%E0%A4%A.md', 'broken percent-encoding'],+ ['', 'empty'],+ [null, 'none'],+ ])+ assert.equal(m.parseDocUrl(href), null, why);+});++test('citeKey: one key per space, file and quote', () => {+ const k = m.citeKey('shop', 'faq.md', 'thirty days');+ assert.equal(k, m.citeKey('shop', 'faq.md', 'thirty days'));+ for (const other of [m.citeKey('shop2', 'faq.md', 'thirty days'), m.citeKey('shop', 'faq.txt', 'thirty days'), m.citeKey('shop', 'faq.md', 'thirty day')])+ assert.notEqual(k, other);+ // No separator a name or quote could fake.+ assert.notEqual(m.citeKey('a|b', 'c.md', 'd'), m.citeKey('a', 'b|c.md', 'd'));+});++test('recheckQuote: one call per quote, shared; at most 4 at a time; the answer mapped to the chip', async () => {+ m._resetCiteCache();+ const calls = [];+ let running = 0;+ let peak = 0;+ const send = (url, init) => {+ calls.push([url, JSON.parse(init.body)]);+ running++;+ peak = Math.max(peak, running);+ const { quote } = JSON.parse(init.body);+ const status = quote.startsWith('ok') ? 200 : quote.startsWith('gone') ? 404 : quote.startsWith('big') ? 413 : 422;+ return new Promise((r) => setTimeout(() => (running--, r({ status })), 5));+ };+ const a = m.recheckQuote('shop', 'faq.md', 'ok one', send);+ const b = m.recheckQuote('shop', 'faq.md', 'ok one', send);+ assert.equal(a, b, 'the same promise');+ const many = ['ok 2', 'no 3', 'gone 4', 'big 5', 'ok 6', 'ok 7'].map((q) => m.recheckQuote('shop', 'faq.md', q, send));+ const all = await Promise.all([a, ...many]);+ assert.deepEqual(all, ['ok', 'ok', 'missing', 'gone', 'unknown', 'ok', 'ok']);+ assert.equal(calls.length, 7);+ assert.ok(peak <= 4, `peak ${peak}`);+ assert.equal(calls[0][0], '/api/spaces/shop/docs/cite');+ assert.deepEqual(calls[0][1], { file: 'faq.md', quote: 'ok one' });+ await m.recheckQuote('shop', 'faq.md', 'ok one', send);+ assert.equal(calls.length, 7, 'cached for the session');+});++test('recheckQuote: a network error shows no mark and may try again later', async () => {+ m._resetCiteCache();+ let n = 0;+ const send = () => (n++ === 0 ? Promise.reject(new Error('offline')) : Promise.resolve({ status: 200 }));+ assert.equal(await m.recheckQuote('s', 'a.md', 'q', send), 'unknown');+ await new Promise((r) => setTimeout(r, 0));+ assert.equal(await m.recheckQuote('s', 'a.md', 'q', send), 'ok');+});++test('checkFile: name, then kind, then size, before anything is sent (QA F2 included)', () => {+ const MB = 1024 * 1024;+ for (const [name, size, want, why] of [+ ['faq.md', 10, null, 'fine'],+ ['Returns policy.PDF', MB, null, 'upper-case extension'],+ ['notes.markdown', 10, null, '.markdown'],+ ['prices.txt', 2 * MB, null, 'exactly 2 MB'],+ ['big.pdf', 2 * MB + 1, 'too_large', 'over 2 MB'],+ ['Staff handbook.docx', 10, 'wrong_kind', 'docx'],+ ['README', 10, 'wrong_kind', 'no extension'],+ ['photo.png', 10, 'wrong_kind', 'png'],+ ['.env.md', 10, 'bad_name', 'leading dot'],+ ['..md', 10, 'bad_name', '".." (F2)'],+ ['a..b.md', 10, 'bad_name', '".." inside (F2)'],+ ['../secret.md', 10, 'bad_name', 'path out'],+ ['sub/faq.md', 10, 'bad_name', 'slash'],+ ['sub\\faq.md', 10, 'bad_name', 'backslash'],+ [' faq.md', 10, 'bad_name', 'padded'],+ ['.hidden.docx', 9 * MB, 'bad_name', 'name is checked first'],+ ['huge.docx', 9 * MB, 'wrong_kind', 'kind before size'],+ ])+ assert.equal(m.checkFile({ name, size })?.kind ?? null, want, why);+});++test('words: sizes, meta line, marks, folder and problem rows', () => {+ const now = Date.parse('2026-11-13T12:00:00Z');+ assert.equal(m.formatSize(64), '1 KB');+ assert.equal(m.formatSize(312 * 1024), '312 KB');+ assert.equal(m.formatSize(6.4 * 1024 * 1024), '6.4 MB');+ assert.equal(m.docMeta({ name: 'Returns policy.pdf', size: 312 * 1024, modified: '2026-11-10T09:00:00Z', pages: 4 }, now), '4 pages · 312 KB · updated 3 days ago');+ assert.equal(m.docMeta({ name: 'faq.md', size: 18 * 1024, modified: '2026-11-13T08:00:00Z' }, now), '18 KB · updated today');+ assert.equal(m.docMeta({ name: 'one.pdf', size: 2048, modified: '2026-11-12T08:00:00Z', pages: 1 }, now), '1 page · 2 KB · updated yesterday');+ assert.equal(m.updatedWhen('2026-10-28T08:00:00Z', now), 'Oct 28');+ assert.deepEqual(['a.pdf', 'b.MD', 'c.markdown', 'd.txt', 'e.docx', 'f'].map(m.markOf), ['PDF', 'MD', 'MD', 'TXT', 'DOCX', 'FILE']);+ assert.equal(m.shortFolder('/home/me/.kwnt/docs'), '~/.kwnt/docs');+ assert.equal(m.shortFolder('/Users/ana/Library/kwnt/spaces/7f3a9c2e1b4d/docs'), '~/Library/kwnt/spaces/7f3a9c2e…/docs');+ assert.equal(m.shortFolder('/home/me/.kwnt/spaces/spc_7f3a9c2e1b4d/docs'), '~/.kwnt/spaces/spc_7f3a…/docs', 'a real space id keeps 8 characters');+ assert.equal(m.shortFolder('/srv/kwnt/spaces/shop/docs'), '/srv/kwnt/spaces/shop/docs', 'a short id stays');+ assert.deepEqual(+ m.sortDocs([+ { name: 'old.md', modified: '2026-11-01T00:00:00Z' },+ { name: 'new.md', modified: '2026-11-13T00:00:00Z' },+ ]).map((d) => d.name),+ ['new.md', 'old.md'],+ 'newest first',+ );+ assert.equal(m.problemText('too_large', { name: 'big.pdf', size: 6.4 * 1024 * 1024 }), 'It’s 6.4 MB, over the 2 MB bots can read. Save a smaller copy or split it.');+ assert.match(m.problemText('bad_name', { name: '..md', size: 1 }), /can’t start with a dot or contain “\.\.”/);+ assert.equal(m.copyQuote('Budget is 42 euros', 'plan.pdf', 2), 'Budget is 42 euros — plan.pdf, p. 2');+ assert.equal(m.copyQuote('thirty days', 'faq.md', null), 'thirty days — faq.md');+});++test('add: the error code decides the row, never the status or the words', () => {+ for (const [status, code, error, kind] of [+ [400, 'bad_name', 'names can’t start with a dot', 'bad_name'],+ [415, 'wrong_kind', 'wrong kind', 'wrong_kind'],+ [413, 'too_large', 'kwant reads documents up to 2 MB', 'too_large'],+ [413, '', '', 'too_large'],+ [422, 'no_text', 'PDF has no text layer', 'no_text'],+ [422, 'unreadable', 'faq.md isn’t UTF-8 text', 'unreadable'],+ [409, 'exists', 'almost.md is already in this space’s documents', 'exists'],+ [409, 'exists', 'faq200.md is already in this space’s documents; the most', 'exists'],+ [409, 'full', 'this space has 200 documents, the most kwant reads', 'limit'],+ [409, 'docs_link', 'the space’s docs isn’t a plain folder', 'docs_link'],+ [409, '', 'this space is archived; restore it first', 'archived'],+ [403, 'person_only', 'only the person', 'person_only'],+ [400, 'interrupted', 'The upload was interrupted.', 'failed'],+ [422, 'something_new', 'already exists', 'failed'],+ [500, '', '', 'failed'],+ ])+ assert.equal(m.addResultOf(status, code, error).kind, kind, `${status} ${code} ${error}`);+ for (const kind of ['bad_name', 'wrong_kind', 'no_text', 'unreadable', 'docs_link', 'limit', 'archived'])+ assert.notEqual(m.problemText(kind, { name: 'a.md', size: 1 }), m.problemText('failed', { name: 'a.md', size: 1 }), kind);+});++test('add: the file is the raw body and its name is in the query', async () => {+ const real = globalThis.fetch;+ const calls = [];+ const reply = (status, body) => async (url, init) => {+ calls.push({ url, init });+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });+ };+ try {+ const file = new File(['return any item within 30 days'], 'Returns & FAQ #2.md', { type: 'text/markdown' });+ globalThis.fetch = reply(201, { name: 'Returns & FAQ #2.md', size: 30, modified: '2026-11-14T00:00:00Z' });+ const ok = await m.spaceDocsApi.add('spc 1', file);+ assert.equal(ok.ok, true);+ assert.equal(calls[0].url, '/api/spaces/spc%201/docs?name=Returns%20%26%20FAQ%20%232.md');+ assert.equal(calls[0].init.method, 'POST');+ assert.equal(calls[0].init.body, file, 'the File itself, not FormData');+ assert.ok(!(calls[0].init.body instanceof FormData));+ assert.equal(calls[0].init.headers, undefined, 'no Content-Type override');++ globalThis.fetch = reply(201, { name: 'faq.md', size: 1, modified: '2026-11-14T00:00:00Z' });+ await m.spaceDocsApi.add('s', new File(['x'], 'faq.md'), true);+ assert.equal(calls[1].url, '/api/spaces/s/docs?name=faq.md&replace=1');++ globalThis.fetch = reply(409, { error: 'almost.md is already in this space’s documents', code: 'exists' });+ assert.equal((await m.spaceDocsApi.add('s', new File(['x'], 'almost.md'))).kind, 'exists');+ globalThis.fetch = reply(409, { error: 'dir.md is a folder', code: 'exists' });+ assert.equal((await m.spaceDocsApi.add('s', new File(['x'], 'dir.md'), true)).kind, 'failed', 'replace refused: no second clash row');+ globalThis.fetch = reply(422, { error: 'x isn’t UTF-8 text', code: 'unreadable' });+ assert.equal((await m.spaceDocsApi.add('s', new File(['x'], 'x.txt'))).kind, 'unreadable');+ } finally {+ globalThis.fetch = real;+ }+});++test('routes probe and page text: a missing route is told apart from a missing file', async () => {+ const real = globalThis.fetch;+ const answer = (status, body) => async () => new Response(body === undefined ? 'Not Found' : JSON.stringify(body), { status, headers: body === undefined ? {} : { 'Content-Type': 'application/json' } });+ try {+ for (const [status, body, routes, page, why] of [+ [400, { error: 'file is required' }, true, 'failed', 'route there, empty name refused'],+ [404, undefined, false, 'no_route', 'no route yet: plain 404'],+ [405, undefined, false, 'no_route', 'no route yet: 405'],+ [404, { error: 'no such document' }, true, 'gone', 'route there, file gone'],+ [500, { error: 'boom' }, true, 'failed', 'server error'],+ ]) {+ globalThis.fetch = answer(status, body);+ assert.equal(await m.spaceDocsApi.hasRoutes('s'), routes, `hasRoutes: ${why}`);+ assert.equal(await m.spaceDocsApi.page('s', 'faq.md', 1, 'x'), page, `page: ${why}`);+ }+ const doc = { file: 'a.pdf', page: 2, pages: 4, text_before: 'a ', match: 'b', text_after: ' c', cut_before: false, cut_after: false };+ globalThis.fetch = answer(200, doc);+ assert.deepEqual(await m.spaceDocsApi.page('s', 'a.pdf', 2, 'b'), doc);+ globalThis.fetch = async () => { throw new TypeError('offline'); };+ assert.equal(await m.spaceDocsApi.hasRoutes('s'), false);+ assert.equal(await m.spaceDocsApi.page('s', 'a.pdf', 2), 'failed');+ } finally {+ globalThis.fetch = real;+ }+});