From 52cb7c2065c852ce2a20ee535ba0d5895b9a9ffc Mon Sep 17 00:00:00 2001 From: Tyler Hallada Date: Tue, 17 Nov 2026 16:22:53 -0500 Subject: [PATCH] Links, Wikipedia and the replica: duplicates merged, dead fields and caches out - One failure(res) in api.ts for every fetch that can fail (session, remote and the libraries calls each had their own; the error's attached body was never read). Session's lost() and vanished() were the same but for the hook: stop("foreign" | "gone"). - linker: place() locates the words with locate() instead of a copy; the scan reply's type is written once; LinkRow.at was never read; the "import" origin is never passed. - wiki.ts: cleanHtml's cache could never hit (its only caller, articleText, is cached on the same key and evicts the same way); known() returned an article nobody read. - Gone: currentLibrary and idbKeys (no callers), useWikiSuggest's q, a node's link flag spelled out where isLink says it. Exports used only in their own file are not exported. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab --- src/ui/Links.tsx | 12 ++++++------ src/ui/Node.tsx | 4 ++-- src/ui/Wiki.tsx | 2 +- src/ui/api.ts | 20 +++++++++++--------- src/ui/articleText.ts | 4 ++-- src/ui/idb.ts | 14 -------------- src/ui/linker.ts | 34 ++++++++++++++++------------------ src/ui/remote.ts | 2 +- src/ui/session.ts | 39 ++++++++++----------------------------- src/ui/store.ts | 4 ++-- src/ui/wiki.ts | 22 +++++++--------------- 11 files changed, 58 insertions(+), 99 deletions(-) diff --git a/src/ui/Links.tsx b/src/ui/Links.tsx index 240c4fe..e68467d 100644 --- a/src/ui/Links.tsx +++ b/src/ui/Links.tsx @@ -18,7 +18,7 @@ import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion const MARK: Record = { wiki: "W", node: "§", url: "↗" }; /** Where a node is, in a word: the title of the top-level node it is under, or for a top-level node itself, the library's. */ -export function whereIs(s: Snap, id: NodeId): string { +function whereIs(s: Snap, id: NodeId): string { const t = topOf(s, id); return t && t !== id ? s.nodes[t].title : label(s, s.root); } @@ -28,7 +28,7 @@ function where(r: Ref): string { if (r.kind === "wiki") return `Wikipedia: ${r.title}`; if (r.kind === "url") return hostOf(r.url); const s = store.snap; - const id = resolveNode(store.snap, r); + const id = resolveNode(s, r); if (!id) return "a note that is gone"; const t = topOf(s, id); return `${label(s, id)}${t && t !== id ? ` · in ${s.nodes[t].title}` : ""}`; @@ -77,7 +77,7 @@ export function LinkCard({ r, compact }: { r: Ref; compact?: boolean }) { } if (r.kind === "node") { const s = store.snap; - const id = resolveNode(store.snap, r); + const id = resolveNode(s, r); if (!id) { return (
@@ -263,14 +263,14 @@ export const articleChoice = (w: Suggestion): Choice => ({ group: "Wikipedia", l * Wikipedia's title suggestions for some text, after a pause in typing. A superseded request is * abandoned, and the server then never sends it. Empty text asks for nothing. */ -export function useWikiSuggest(text: string): { q: string; list: Suggestion[]; problem?: string } | null { - const [found, setFound] = useState<{ q: string; list: Suggestion[]; problem?: string } | null>(null); +export function useWikiSuggest(text: string): { list: Suggestion[]; problem?: string } | null { + const [found, setFound] = useState<{ list: Suggestion[]; problem?: string } | null>(null); useEffect(() => { if (!text || wikiConfig().mode === "off") return setFound(null); const ac = new AbortController(); const timer = setTimeout(() => { suggest(text, ac.signal) - .then((r) => !ac.signal.aborted && setFound(Array.isArray(r) ? { q: text, list: r } : { q: text, list: [], problem: r.message })) + .then((r) => !ac.signal.aborted && setFound(Array.isArray(r) ? { list: r } : { list: [], problem: r.message })) .catch(() => {}); }, 250); return () => (clearTimeout(timer), ac.abort()); diff --git a/src/ui/Node.tsx b/src/ui/Node.tsx index fb8aa98..f027a21 100644 --- a/src/ui/Node.tsx +++ b/src/ui/Node.tsx @@ -1,7 +1,7 @@ /** Rendering shared by both page layouts: a node's body with its notes, the outline rows, and the top of the page. */ import { Component, type ComponentChildren } from "preact"; import { useLayoutEffect, useRef, useState } from "preact/hooks"; -import { anchorLost, ancestors, descendants, isLibraryRoot, label, libraryNodeCount, notesOf, sections, staleness, type NodeId, type Snap } from "../core/model"; +import { anchorLost, ancestors, descendants, isLibraryRoot, isLink, label, libraryNodeCount, notesOf, sections, staleness, type NodeId, type Snap } from "../core/model"; import type { Ref } from "../core/ref"; import { clip, overlaps, paragraphs, plain, type Form, type Range } from "../core/text"; import { streamView } from "../core/marks"; @@ -33,7 +33,7 @@ function notesFor(snap: Snap, id: NodeId): { placed: VNote[]; orphans: NodeId[] const n = snap.nodes[c]; const ranges = n.anchors.filter((a) => a.end > a.start).map((a): Range => [a.start, a.end]); if (!ranges.length || n.anchors.every(anchorLost)) orphans.push(c); - else placed.push({ key: c, id: c, form: n.form ?? "note", ranges, open: store.open.has(c), lens: n.lens, ref: n.ref, link: !!n.ref && !n.body.trim() }); + else placed.push({ key: c, id: c, form: n.form ?? "note", ranges, open: store.open.has(c), lens: n.lens, ref: n.ref, link: isLink(n) }); } for (const p of store.pending.values()) { if (p.node === id && p.kind === "note" && p.range) placed.push({ key: p.key, form: p.form ?? "note", ranges: [p.range], open: true, pending: p, lens: p.lens }); diff --git a/src/ui/Wiki.tsx b/src/ui/Wiki.tsx index 1bed2bf..e49cd14 100644 --- a/src/ui/Wiki.tsx +++ b/src/ui/Wiki.tsx @@ -200,7 +200,7 @@ export function WikiView({ host }: { host: string }) { const art = article(h.title, h.lang); if (art.state !== "ready") { // While the article loads, a summary already at hand is shown at once. - const have = known(h.title, h.lang).summary; + const have = known(h.title, h.lang); return (
diff --git a/src/ui/api.ts b/src/ui/api.ts index 3b34b77..8d23da5 100644 --- a/src/ui/api.ts +++ b/src/ui/api.ts @@ -11,9 +11,6 @@ export function setLibrary(id: string) { library = id; } -/** The library this page holds, once boot has chosen it. */ -export const currentLibrary = () => library; - /** * A path under this library's API: libApi("/links/jobs") → /api/l//links/jobs. Before a library * is chosen (only in the tests: the page chooses one before anything asks) the unprefixed route, @@ -33,16 +30,21 @@ export interface LibraryInfo { branches: string[]; } -async function call(path: string, init?: RequestInit): Promise { - const res = await fetch(path, init); - let body: Record = {}; +/** A failed answer as an error: the server's `error`, else its status. */ +export async function failure(res: Response): Promise { + let message = `${res.status} ${res.statusText}`; try { - body = await res.json(); + message = String((await res.json())?.error ?? message); } catch { /* not JSON */ } - if (!res.ok) throw new Error(String(body.error ?? `${res.status} ${res.statusText}`)); - return body as T; + return new Error(message); +} + +async function call(path: string, init?: RequestInit): Promise { + const res = await fetch(path, init); + if (!res.ok) throw await failure(res); + return res.json().catch(() => ({})) as Promise; } const send = (method: string, body?: unknown): RequestInit => ({ method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }); diff --git a/src/ui/articleText.ts b/src/ui/articleText.ts index 0164eff..85274be 100644 --- a/src/ui/articleText.ts +++ b/src/ui/articleText.ts @@ -25,12 +25,12 @@ export interface DomLike { } /** An inline element around some text. */ -export interface Mark { +interface Mark { tag: string; attrs: [string, string][]; } /** A stretch of a paragraph with the same inline elements around it; a formula is a run of its own. */ -export interface Run { +interface Run { s: number; e: number; marks: Mark[]; diff --git a/src/ui/idb.ts b/src/ui/idb.ts index 1841c1f..bb48377 100644 --- a/src/ui/idb.ts +++ b/src/ui/idb.ts @@ -25,20 +25,6 @@ export async function idbGet(key: string): Promise { } } -/** Every stored key. */ -export async function idbKeys(): Promise { - try { - const d = await db(); - return await new Promise((resolve, reject) => { - const req = d.transaction("kv").objectStore("kv").getAllKeys(); - req.onsuccess = () => resolve(req.result.map(String)); - req.onerror = () => reject(req.error); - }); - } catch { - return []; - } -} - export async function idbSet(key: string, value: unknown): Promise { try { const d = await db(); diff --git a/src/ui/linker.ts b/src/ui/linker.ts index 53d9a3e..5df3707 100644 --- a/src/ui/linker.ts +++ b/src/ui/linker.ts @@ -21,7 +21,7 @@ import { libApi } from "./api"; import { clip, overlaps, type Range } from "../core/text"; import type { Nearby } from "../llm/prompts"; -export type { JobState, ReviewReport, Sugg }; +export type { JobState, Sugg }; /** After an edit: the model reviews what was found and links what it approves (review), the sure tier is linked (on), all is suggested (suggest), nothing is looked for (off). */ export type AutoMode = "review" | "on" | "suggest" | "off"; @@ -45,7 +45,6 @@ export interface LinkRow { reason: string | null; /** What the reviewer said, when it said something different from how things stand (a person overruled it). */ verdict: boolean | null; - at: number | null; sugg?: Sugg; /** The link's own note, when it is linked. */ note?: NodeId; @@ -65,7 +64,10 @@ interface Host { } /** Who wrote the text being scanned: a person's marks always resolve; a model's follow the mode. */ -type Origin = "human" | "model" | "import"; +type Origin = "human" | "model"; + +/** What the server answers a scan. */ +type ScanReply = { suggestions: Sugg[]; entries?: Sugg[]; apply?: Sugg[]; review?: ReviewReport; unresolved: string[]; degraded: string[] }; interface Task { node: NodeId; @@ -86,12 +88,8 @@ const turnedDown = (snap: Snap, s: Sugg) => !!snap.nodes[s.node]?.nolink?.includ function place(snap: Snap, s: Sugg, overrule = false): Sugg | null { const n = snap.nodes[s.node]; if (!n || (!overrule && turnedDown(snap, s))) return null; - let range = s.range; - if (n.body.slice(range[0], range[1]) !== s.quote) { - const at = n.body.indexOf(s.quote); - if (at < 0) return null; - range = [at, at + s.quote.length]; - } + const range = locate(n.body, s); + if (!range) return null; for (const c of notesOf(snap, s.node)) { const note = snap.nodes[c]; for (const a of note.anchors) { @@ -129,14 +127,14 @@ function rowOf(snap: Snap, s: Sugg): LinkRow | null { if (!note.ref || !note.anchors.some((a) => overlaps([a.start, a.end], range))) continue; if (!sameTarget(note.ref, s.target)) return null; const by = s.decided?.link ? s.decided.by : s.review?.link ? "reviewer" : null; - return { ...base, status: "linked", by, verdict: s.review && by !== "reviewer" ? s.review.link : null, at: s.decided?.at ?? s.review?.at ?? null, note: c }; + return { ...base, status: "linked", by, verdict: s.review && by !== "reviewer" ? s.review.link : null, note: c }; } if (n.nolink?.includes(s.key) || s.decided?.link === false) { const by = s.decided?.link === false ? s.decided.by : null; - return { ...base, status: "rejected", by, verdict: s.review ? s.review.link : null, at: s.decided?.at ?? null }; + return { ...base, status: "rejected", by, verdict: s.review ? s.review.link : null }; } - if (s.review?.link === false && !s.decided?.link) return { ...base, status: "rejected", by: "reviewer", verdict: null, at: s.review.at }; - return { ...base, status: "pending", by: null, verdict: s.review ? s.review.link : null, at: s.review?.at ?? null }; + if (s.review?.link === false && !s.decided?.link) return { ...base, status: "rejected", by: "reviewer", verdict: null }; + return { ...base, status: "pending", by: null, verdict: s.review ? s.review.link : null }; } export class Linker { @@ -203,12 +201,12 @@ export class Linker { const a = note.anchors[0]; if (!note.ref || !a || mine.some((x) => x.note === c)) continue; const quote = n.body.slice(a.start, a.end); - mine.push({ key: `note:${c}`, node: id, range: [a.start, a.end], quote, target: note.ref, title: titleOf(snap, note.ref), status: "linked", by: null, reason: null, verdict: null, at: null, note: c }); + mine.push({ key: `note:${c}`, node: id, range: [a.start, a.end], quote, target: note.ref, title: titleOf(snap, note.ref), status: "linked", by: null, reason: null, verdict: null, note: c }); seen.add(phraseKey(quote)); } for (const k of n.nolink ?? []) { if (seen.has(k) || (this.byNode.get(id) ?? []).some((s) => s.key === k)) continue; - mine.push({ key: `nolink:${id}:${k}`, node: id, range: null, quote: k, target: null, title: "", status: "rejected", by: null, reason: null, verdict: null, at: null }); + mine.push({ key: `nolink:${id}:${k}`, node: id, range: null, quote: k, target: null, title: "", status: "rejected", by: null, reason: null, verdict: null }); } out.push(...mine.sort((a, b) => (a.range?.[0] ?? 1e9) - (b.range?.[0] ?? 1e9))); } @@ -283,7 +281,7 @@ export class Linker { const review = this.effective() === "review" ? (t.origin === "human" ? "unmarked" : "all") : undefined; const res = await post("scan", { ...this.request(snap, t.node, t.forced), ...(review ? { review } : {}) }); if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error ?? `the server answered ${res.status}`); - const r = (await res.json()) as { suggestions: Sugg[]; entries?: Sugg[]; apply?: Sugg[]; review?: ReviewReport; unresolved: string[]; degraded: string[] }; + const r = (await res.json()) as ScanReply; this.take(doc, t.node, r, t.origin); } @@ -293,7 +291,7 @@ export class Linker { * [[marks]] always, by "linker". Everything still pending waits, drawn in the text; what the * reviewer rejected waits behind the links list's filter. */ - private take(doc: Doc, node: NodeId, r: { suggestions: Sugg[]; entries?: Sugg[]; apply?: Sugg[]; review?: ReviewReport; unresolved: string[]; degraded: string[] }, origin: Origin) { + private take(doc: Doc, node: NodeId, r: ScanReply, origin: Origin) { const mode = this.effective(); const marked = (s: Sugg) => s.kind === "forced"; const list = r.suggestions; @@ -310,7 +308,7 @@ export class Linker { else if (approved.length) this.host.say(`${this.linkedText(approved)} · u undoes${rejected ? ` · ${rejected} rejected` : ""}${later.length ? ` · ${later.length} to review` : ""} · S lists them`); else if (rep?.fallback && later.length) this.host.say(`${this.fallbackText(rep.fallback)}: ${later.length} link suggestion${later.length > 1 ? "s" : ""} for you · Tab reaches ${later.length > 1 ? "them" : "it"}, y links, n declines`); else if (rejected && !placed.length) this.host.say(`The reviewer rejected ${rejected} link${rejected > 1 ? "s" : ""} here${later.length ? `; ${later.length} left to review` : ""} · S lists them`); - else if (!placed.length && later.length && origin !== "import") this.host.say(`${later.length} link suggestion${later.length > 1 ? "s" : ""}: Tab reaches ${later.length > 1 ? "them" : "it"}, y links, n declines${r.degraded.length ? ` (${r.degraded[0]})` : ""}`); + else if (!placed.length && later.length) this.host.say(`${later.length} link suggestion${later.length > 1 ? "s" : ""}: Tab reaches ${later.length > 1 ? "them" : "it"}, y links, n declines${r.degraded.length ? ` (${r.degraded[0]})` : ""}`); this.host.emit(node); } diff --git a/src/ui/remote.ts b/src/ui/remote.ts index ab3a29e..4f38f28 100644 --- a/src/ui/remote.ts +++ b/src/ui/remote.ts @@ -1,7 +1,7 @@ /** The model, as the browser sees it: the LLM seam (src/llm/types.ts) as fetches to the local server's /api/llm. */ import type { JsonReq, LLM, Req, Turn, TurnReq } from "../llm/types"; import type { WebStep } from "../llm/web"; -import { failure } from "./session"; +import { failure } from "./api"; async function fail(res: Response): Promise { throw await failure(res); diff --git a/src/ui/session.ts b/src/ui/session.ts index 2d2814d..07959d2 100644 --- a/src/ui/session.ts +++ b/src/ui/session.ts @@ -5,12 +5,12 @@ import { VersionVector } from "loro-crdt"; import { Doc } from "../core/model"; import { Repo, decodeVV, encodeVV, mergeUpdate, vvIncludes, type MergeReport } from "../core/repo"; -import { libApi } from "./api"; +import { failure, libApi } from "./api"; import { idbGet, idbSet } from "./idb"; type VV = Map<`${number}`, number>; -export interface SessionHooks { +interface SessionHooks { /** A replica changed, locally or by sync. */ changed(doc: Doc): void; /** A sync round ended; `ok` says whether the server answered. */ @@ -25,18 +25,6 @@ export interface SessionHooks { message?(msg: Record): void; } -export async function failure(res: Response): Promise }> { - let message = `${res.status} ${res.statusText}`; - let body: Record | undefined; - try { - body = await res.json(); - message = String(body?.error ?? message); - } catch { - /* not JSON */ - } - return Object.assign(new Error(message), { body }); -} - export class Session { repo!: Repo; /** Set once the server turns out to hold another library: nothing more is sent to it. */ @@ -90,11 +78,11 @@ export class Session { private async fetchBranch(name: string): Promise { const res = await fetch(libApi(`/branch/${encodeURIComponent(name)}`)); if (!res.ok) { - if (res.status === 404 && (await failure(res)).message.startsWith("no library")) this.vanished(); + if (res.status === 404 && (await failure(res)).message.startsWith("no library")) this.stop("gone"); return null; } if (res.headers.get("x-library") !== this.library) { - this.lost(); + this.stop("foreign"); return null; } const doc = Doc.load(new Uint8Array(await res.arrayBuffer()), this.user); @@ -181,9 +169,9 @@ export class Session { body: bytes as BodyInit, }); if (!res.ok) { - if (res.status === 409) this.lost(); + if (res.status === 409) this.stop("foreign"); const err = await failure(res); - if (res.status === 404 && err.message.startsWith("no library")) this.vanished(); + if (res.status === 404 && err.message.startsWith("no library")) this.stop("gone"); throw err; } const theirs = decodeVV(res.headers.get("x-vv")!); @@ -201,19 +189,12 @@ export class Session { if (ok && server && !vvIncludes(server, this.repo.branches.get(name)!.loro.version().toJSON())) void this.sync(name); } - private lost() { + /** The server holds another library, or none (gone): stop sending, and say so once. */ + stop(why: "foreign" | "gone") { if (this.foreign) return; this.foreign = true; this.disconnect(); - this.hooks.foreign(); - } - - /** The library is gone from the server: stop sending, and say so once. */ - vanished() { - if (this.foreign) return; - this.foreign = true; - this.disconnect(); - this.hooks.gone(); + this.hooks[why](); } /** Listen for other writers. */ @@ -256,7 +237,7 @@ export class Session { /* unreachable */ } if (this.foreign) return; - if (status === 404 && message.startsWith("no library")) return this.vanished(); + if (status === 404 && message.startsWith("no library")) return this.stop("gone"); if (status >= 200 && status < 300) return this.connect(); setTimeout(() => void this.probe(Math.min(wait * 2, 30_000)), wait); } diff --git a/src/ui/store.ts b/src/ui/store.ts index dfe2714..ddc052f 100644 --- a/src/ui/store.ts +++ b/src/ui/store.ts @@ -74,7 +74,7 @@ export const kidClass = (key: string) => { return `k${h.toString(36)}`; }; /** Whether two panes show the same thing (a node, or an article or one of its sections). */ -export const sameRef = (a: PaneRef, b: PaneRef): boolean => +const sameRef = (a: PaneRef, b: PaneRef): boolean => a.kind === b.kind && (a.kind === "node" ? a.id === (b as { id: NodeId }).id : a.title === (b as { title: string }).title && a.sec === (b as { sec?: number }).sec); /** What a pane shows, as a key: `n:`, or `w:` with `#<section>`. A link's target has the same key as the pane it opens. */ export const refKey = (p: PaneRef): string => (p.kind === "node" ? `n:${p.id}` : `w:${p.title}${p.sec !== undefined ? `#${p.sec}` : ""}`); @@ -1208,7 +1208,7 @@ class Store { gone: () => this.libraryGone(), message: (msg) => { if (msg.linkJob) this.jobUpdate(msg.linkJob as JobState); - if (msg.library === "deleted") this.session.vanished(); + if (msg.library === "deleted") this.session.stop("gone"); }, }); await this.session.load((state?.branches ?? []).map((b) => b.name), this.online); diff --git a/src/ui/wiki.ts b/src/ui/wiki.ts index 76e81aa..5fc649f 100644 --- a/src/ui/wiki.ts +++ b/src/ui/wiki.ts @@ -108,11 +108,10 @@ export function sensesOf(title: string, lang = config.lang): Loadable<Sense[]> { return load(senses, wikiKey(lang, title), `/api/wiki/senses?${q(wikiTitle(title))}`, "senses"); } -/** What is already known about an article, without asking for anything. */ -export function known(title: string, lang = config.lang): { summary?: Summary; article?: Article } { +/** An article's summary if it is here already, without asking for anything. */ +export function known(title: string, lang = config.lang): Summary | undefined { const s = summaries.get(wikiKey(lang, title)); - const a = articles.get(wikiKey(lang, title)); - return { summary: s?.state === "ready" ? s.value : undefined, article: a?.state === "ready" ? a.value : undefined }; + return s?.state === "ready" ? s.value : undefined; } /** @@ -120,7 +119,7 @@ export function known(title: string, lang = config.lang): { summary?: Summary; a * which must never wait on Wikipedia. */ export async function cachedExtract(title: string, ms = 300): Promise<{ title: string; extract: string } | null> { - const have = known(title).summary; + const have = known(title); if (have?.extract) return { title: have.title, extract: have.extract }; if (config.mode === "off") return null; const ac = new AbortController(); @@ -156,16 +155,12 @@ const ATTRS = new Set(["colspan", "rowspan", "start", "data-wiki", "data-wiki-fr /** Elements whose content goes with them. */ const DROP = new Set(["script", "style", "iframe", "object", "embed", "svg", "link", "meta", "base", "form", "template", "noscript", "video", "audio", "img", "picture", "figure", "source", "canvas", "title", "head", "input", "button", "select", "textarea"]); -const cleaned = new Map<string, string>(); - /** * Clean article HTML once more, in an inert document (DOMParser runs no script and loads nothing): * allowlisted elements and attributes only, wiki links kept as data-wiki, other links only if - * http(s) and then in a new tab without an opener. Remembered per string. + * http(s) and then in a new tab without an opener. */ -export function cleanHtml(html: string): string { - const have = cleaned.get(html); - if (have !== undefined) return have; +function cleanHtml(html: string): string { const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html"); const walk = (el: Element) => { for (const child of [...el.children]) { @@ -192,10 +187,7 @@ export function cleanHtml(html: string): string { } }; walk(doc.body); - const out = doc.body.innerHTML; - if (cleaned.size > 400) cleaned.delete(cleaned.keys().next().value as string); - cleaned.set(html, out); - return out; + return doc.body.innerHTML; } /** A piece of article HTML as text to select in (articleText.ts). Remembered per string. */