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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
1 parent
3aa8778427
commit
52cb7c2065
11 files changed
+58
-99
No files matched your search
+6
-6
@@ -18,7 +18,7 @@ import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion
|
|||||||
const MARK: Record<Ref["kind"], string> = { wiki: "W", node: "§", url: "↗" };
|
const MARK: Record<Ref["kind"], string> = { 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. */
|
/** 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);
|
const t = topOf(s, id);
|
||||||
return t && t !== id ? s.nodes[t].title : label(s, s.root);
|
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 === "wiki") return `Wikipedia: ${r.title}`;
|
||||||
if (r.kind === "url") return hostOf(r.url);
|
if (r.kind === "url") return hostOf(r.url);
|
||||||
const s = store.snap;
|
const s = store.snap;
|
||||||
const id = resolveNode(store.snap, r);
|
const id = resolveNode(s, r);
|
||||||
if (!id) return "a note that is gone";
|
if (!id) return "a note that is gone";
|
||||||
const t = topOf(s, id);
|
const t = topOf(s, id);
|
||||||
return `${label(s, id)}${t && t !== id ? ` · in ${s.nodes[t].title}` : ""}`;
|
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") {
|
if (r.kind === "node") {
|
||||||
const s = store.snap;
|
const s = store.snap;
|
||||||
const id = resolveNode(store.snap, r);
|
const id = resolveNode(s, r);
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return (
|
return (
|
||||||
<div class="lcard l-node broken">
|
<div class="lcard l-node broken">
|
||||||
@@ -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
|
* 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.
|
* 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 {
|
export function useWikiSuggest(text: string): { list: Suggestion[]; problem?: string } | null {
|
||||||
const [found, setFound] = useState<{ q: string; list: Suggestion[]; problem?: string } | null>(null);
|
const [found, setFound] = useState<{ list: Suggestion[]; problem?: string } | null>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!text || wikiConfig().mode === "off") return setFound(null);
|
if (!text || wikiConfig().mode === "off") return setFound(null);
|
||||||
const ac = new AbortController();
|
const ac = new AbortController();
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
suggest(text, ac.signal)
|
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(() => {});
|
.catch(() => {});
|
||||||
}, 250);
|
}, 250);
|
||||||
return () => (clearTimeout(timer), ac.abort());
|
return () => (clearTimeout(timer), ac.abort());
|
||||||
|
|||||||
+2
-2
@@ -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. */
|
/** 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 { Component, type ComponentChildren } from "preact";
|
||||||
import { useLayoutEffect, useRef, useState } from "preact/hooks";
|
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 type { Ref } from "../core/ref";
|
||||||
import { clip, overlaps, paragraphs, plain, type Form, type Range } from "../core/text";
|
import { clip, overlaps, paragraphs, plain, type Form, type Range } from "../core/text";
|
||||||
import { streamView } from "../core/marks";
|
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 n = snap.nodes[c];
|
||||||
const ranges = n.anchors.filter((a) => a.end > a.start).map((a): Range => [a.start, a.end]);
|
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);
|
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()) {
|
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 });
|
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 });
|
||||||
|
|||||||
+1
-1
@@ -200,7 +200,7 @@ export function WikiView({ host }: { host: string }) {
|
|||||||
const art = article(h.title, h.lang);
|
const art = article(h.title, h.lang);
|
||||||
if (art.state !== "ready") {
|
if (art.state !== "ready") {
|
||||||
// While the article loads, a summary already at hand is shown at once.
|
// 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 (
|
return (
|
||||||
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
|
<section class={`wiki${embedded ? " embedded" : ""}`} data-host={host}>
|
||||||
<Head title={have?.title ?? h.title} focused={at({ t: "head" })} />
|
<Head title={have?.title ?? h.title} focused={at({ t: "head" })} />
|
||||||
|
|||||||
+11
-9
@@ -11,9 +11,6 @@ export function setLibrary(id: string) {
|
|||||||
library = id;
|
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/<id>/links/jobs. Before a library
|
* A path under this library's API: libApi("/links/jobs") → /api/l/<id>/links/jobs. Before a library
|
||||||
* is chosen (only in the tests: the page chooses one before anything asks) the unprefixed route,
|
* 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[];
|
branches: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
async function call<T>(path: string, init?: RequestInit): Promise<T> {
|
/** A failed answer as an error: the server's `error`, else its status. */
|
||||||
const res = await fetch(path, init);
|
export async function failure(res: Response): Promise<Error> {
|
||||||
let body: Record<string, unknown> = {};
|
let message = `${res.status} ${res.statusText}`;
|
||||||
try {
|
try {
|
||||||
body = await res.json();
|
message = String((await res.json())?.error ?? message);
|
||||||
} catch {
|
} catch {
|
||||||
/* not JSON */
|
/* not JSON */
|
||||||
}
|
}
|
||||||
if (!res.ok) throw new Error(String(body.error ?? `${res.status} ${res.statusText}`));
|
return new Error(message);
|
||||||
return body as T;
|
}
|
||||||
|
|
||||||
|
async function call<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
|
const res = await fetch(path, init);
|
||||||
|
if (!res.ok) throw await failure(res);
|
||||||
|
return res.json().catch(() => ({})) as Promise<T>;
|
||||||
}
|
}
|
||||||
const send = (method: string, body?: unknown): RequestInit => ({ method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
|
const send = (method: string, body?: unknown): RequestInit => ({ method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
|
||||||
|
|
||||||
|
|||||||
@@ -25,12 +25,12 @@ export interface DomLike {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** An inline element around some text. */
|
/** An inline element around some text. */
|
||||||
export interface Mark {
|
interface Mark {
|
||||||
tag: string;
|
tag: string;
|
||||||
attrs: [string, string][];
|
attrs: [string, string][];
|
||||||
}
|
}
|
||||||
/** A stretch of a paragraph with the same inline elements around it; a formula is a run of its own. */
|
/** 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;
|
s: number;
|
||||||
e: number;
|
e: number;
|
||||||
marks: Mark[];
|
marks: Mark[];
|
||||||
|
|||||||
@@ -25,20 +25,6 @@ export async function idbGet<T>(key: string): Promise<T | undefined> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Every stored key. */
|
|
||||||
export async function idbKeys(): Promise<string[]> {
|
|
||||||
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<void> {
|
export async function idbSet(key: string, value: unknown): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const d = await db();
|
const d = await db();
|
||||||
|
|||||||
+16
-18
@@ -21,7 +21,7 @@ import { libApi } from "./api";
|
|||||||
import { clip, overlaps, type Range } from "../core/text";
|
import { clip, overlaps, type Range } from "../core/text";
|
||||||
import type { Nearby } from "../llm/prompts";
|
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). */
|
/** 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";
|
export type AutoMode = "review" | "on" | "suggest" | "off";
|
||||||
|
|
||||||
@@ -45,7 +45,6 @@ export interface LinkRow {
|
|||||||
reason: string | null;
|
reason: string | null;
|
||||||
/** What the reviewer said, when it said something different from how things stand (a person overruled it). */
|
/** What the reviewer said, when it said something different from how things stand (a person overruled it). */
|
||||||
verdict: boolean | null;
|
verdict: boolean | null;
|
||||||
at: number | null;
|
|
||||||
sugg?: Sugg;
|
sugg?: Sugg;
|
||||||
/** The link's own note, when it is linked. */
|
/** The link's own note, when it is linked. */
|
||||||
note?: NodeId;
|
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. */
|
/** 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 {
|
interface Task {
|
||||||
node: NodeId;
|
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 {
|
function place(snap: Snap, s: Sugg, overrule = false): Sugg | null {
|
||||||
const n = snap.nodes[s.node];
|
const n = snap.nodes[s.node];
|
||||||
if (!n || (!overrule && turnedDown(snap, s))) return null;
|
if (!n || (!overrule && turnedDown(snap, s))) return null;
|
||||||
let range = s.range;
|
const range = locate(n.body, s);
|
||||||
if (n.body.slice(range[0], range[1]) !== s.quote) {
|
if (!range) return null;
|
||||||
const at = n.body.indexOf(s.quote);
|
|
||||||
if (at < 0) return null;
|
|
||||||
range = [at, at + s.quote.length];
|
|
||||||
}
|
|
||||||
for (const c of notesOf(snap, s.node)) {
|
for (const c of notesOf(snap, s.node)) {
|
||||||
const note = snap.nodes[c];
|
const note = snap.nodes[c];
|
||||||
for (const a of note.anchors) {
|
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 (!note.ref || !note.anchors.some((a) => overlaps([a.start, a.end], range))) continue;
|
||||||
if (!sameTarget(note.ref, s.target)) return null;
|
if (!sameTarget(note.ref, s.target)) return null;
|
||||||
const by = s.decided?.link ? s.decided.by : s.review?.link ? "reviewer" : 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) {
|
if (n.nolink?.includes(s.key) || s.decided?.link === false) {
|
||||||
const by = s.decided?.link === false ? s.decided.by : null;
|
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 };
|
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, at: s.review?.at ?? null };
|
return { ...base, status: "pending", by: null, verdict: s.review ? s.review.link : null };
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Linker {
|
export class Linker {
|
||||||
@@ -203,12 +201,12 @@ export class Linker {
|
|||||||
const a = note.anchors[0];
|
const a = note.anchors[0];
|
||||||
if (!note.ref || !a || mine.some((x) => x.note === c)) continue;
|
if (!note.ref || !a || mine.some((x) => x.note === c)) continue;
|
||||||
const quote = n.body.slice(a.start, a.end);
|
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));
|
seen.add(phraseKey(quote));
|
||||||
}
|
}
|
||||||
for (const k of n.nolink ?? []) {
|
for (const k of n.nolink ?? []) {
|
||||||
if (seen.has(k) || (this.byNode.get(id) ?? []).some((s) => s.key === k)) continue;
|
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)));
|
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 review = this.effective() === "review" ? (t.origin === "human" ? "unmarked" : "all") : undefined;
|
||||||
const res = await post("scan", { ...this.request(snap, t.node, t.forced), ...(review ? { review } : {}) });
|
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}`);
|
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);
|
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
|
* [[marks]] always, by "linker". Everything still pending waits, drawn in the text; what the
|
||||||
* reviewer rejected waits behind the links list's filter.
|
* 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 mode = this.effective();
|
||||||
const marked = (s: Sugg) => s.kind === "forced";
|
const marked = (s: Sugg) => s.kind === "forced";
|
||||||
const list = r.suggestions;
|
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 (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 (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 (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);
|
this.host.emit(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -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. */
|
/** 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 { JsonReq, LLM, Req, Turn, TurnReq } from "../llm/types";
|
||||||
import type { WebStep } from "../llm/web";
|
import type { WebStep } from "../llm/web";
|
||||||
import { failure } from "./session";
|
import { failure } from "./api";
|
||||||
|
|
||||||
async function fail(res: Response): Promise<never> {
|
async function fail(res: Response): Promise<never> {
|
||||||
throw await failure(res);
|
throw await failure(res);
|
||||||
|
|||||||
+10
-29
@@ -5,12 +5,12 @@
|
|||||||
import { VersionVector } from "loro-crdt";
|
import { VersionVector } from "loro-crdt";
|
||||||
import { Doc } from "../core/model";
|
import { Doc } from "../core/model";
|
||||||
import { Repo, decodeVV, encodeVV, mergeUpdate, vvIncludes, type MergeReport } from "../core/repo";
|
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";
|
import { idbGet, idbSet } from "./idb";
|
||||||
|
|
||||||
type VV = Map<`${number}`, number>;
|
type VV = Map<`${number}`, number>;
|
||||||
|
|
||||||
export interface SessionHooks {
|
interface SessionHooks {
|
||||||
/** A replica changed, locally or by sync. */
|
/** A replica changed, locally or by sync. */
|
||||||
changed(doc: Doc): void;
|
changed(doc: Doc): void;
|
||||||
/** A sync round ended; `ok` says whether the server answered. */
|
/** A sync round ended; `ok` says whether the server answered. */
|
||||||
@@ -25,18 +25,6 @@ export interface SessionHooks {
|
|||||||
message?(msg: Record<string, unknown>): void;
|
message?(msg: Record<string, unknown>): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function failure(res: Response): Promise<Error & { body?: Record<string, unknown> }> {
|
|
||||||
let message = `${res.status} ${res.statusText}`;
|
|
||||||
let body: Record<string, unknown> | undefined;
|
|
||||||
try {
|
|
||||||
body = await res.json();
|
|
||||||
message = String(body?.error ?? message);
|
|
||||||
} catch {
|
|
||||||
/* not JSON */
|
|
||||||
}
|
|
||||||
return Object.assign(new Error(message), { body });
|
|
||||||
}
|
|
||||||
|
|
||||||
export class Session {
|
export class Session {
|
||||||
repo!: Repo;
|
repo!: Repo;
|
||||||
/** Set once the server turns out to hold another library: nothing more is sent to it. */
|
/** 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<Doc | null> {
|
private async fetchBranch(name: string): Promise<Doc | null> {
|
||||||
const res = await fetch(libApi(`/branch/${encodeURIComponent(name)}`));
|
const res = await fetch(libApi(`/branch/${encodeURIComponent(name)}`));
|
||||||
if (!res.ok) {
|
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;
|
return null;
|
||||||
}
|
}
|
||||||
if (res.headers.get("x-library") !== this.library) {
|
if (res.headers.get("x-library") !== this.library) {
|
||||||
this.lost();
|
this.stop("foreign");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const doc = Doc.load(new Uint8Array(await res.arrayBuffer()), this.user);
|
const doc = Doc.load(new Uint8Array(await res.arrayBuffer()), this.user);
|
||||||
@@ -181,9 +169,9 @@ export class Session {
|
|||||||
body: bytes as BodyInit,
|
body: bytes as BodyInit,
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
if (res.status === 409) this.lost();
|
if (res.status === 409) this.stop("foreign");
|
||||||
const err = await failure(res);
|
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;
|
throw err;
|
||||||
}
|
}
|
||||||
const theirs = decodeVV(res.headers.get("x-vv")!);
|
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);
|
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;
|
if (this.foreign) return;
|
||||||
this.foreign = true;
|
this.foreign = true;
|
||||||
this.disconnect();
|
this.disconnect();
|
||||||
this.hooks.foreign();
|
this.hooks[why]();
|
||||||
}
|
|
||||||
|
|
||||||
/** 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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Listen for other writers. */
|
/** Listen for other writers. */
|
||||||
@@ -256,7 +237,7 @@ export class Session {
|
|||||||
/* unreachable */
|
/* unreachable */
|
||||||
}
|
}
|
||||||
if (this.foreign) return;
|
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();
|
if (status >= 200 && status < 300) return this.connect();
|
||||||
setTimeout(() => void this.probe(Math.min(wait * 2, 30_000)), wait);
|
setTimeout(() => void this.probe(Math.min(wait * 2, 30_000)), wait);
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -74,7 +74,7 @@ export const kidClass = (key: string) => {
|
|||||||
return `k${h.toString(36)}`;
|
return `k${h.toString(36)}`;
|
||||||
};
|
};
|
||||||
/** Whether two panes show the same thing (a node, or an article or one of its sections). */
|
/** 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);
|
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:<node id>`, or `w:<title>` with `#<section>`. A link's target has the same key as the pane it opens. */
|
/** What a pane shows, as a key: `n:<node id>`, or `w:<title>` 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}` : ""}`);
|
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(),
|
gone: () => this.libraryGone(),
|
||||||
message: (msg) => {
|
message: (msg) => {
|
||||||
if (msg.linkJob) this.jobUpdate(msg.linkJob as JobState);
|
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);
|
await this.session.load((state?.branches ?? []).map((b) => b.name), this.online);
|
||||||
|
|||||||
+7
-15
@@ -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");
|
return load(senses, wikiKey(lang, title), `/api/wiki/senses?${q(wikiTitle(title))}`, "senses");
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What is already known about an article, without asking for anything. */
|
/** An article's summary if it is here already, without asking for anything. */
|
||||||
export function known(title: string, lang = config.lang): { summary?: Summary; article?: Article } {
|
export function known(title: string, lang = config.lang): Summary | undefined {
|
||||||
const s = summaries.get(wikiKey(lang, title));
|
const s = summaries.get(wikiKey(lang, title));
|
||||||
const a = articles.get(wikiKey(lang, title));
|
return s?.state === "ready" ? s.value : undefined;
|
||||||
return { summary: s?.state === "ready" ? s.value : undefined, article: a?.state === "ready" ? a.value : undefined };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -120,7 +119,7 @@ export function known(title: string, lang = config.lang): { summary?: Summary; a
|
|||||||
* which must never wait on Wikipedia.
|
* which must never wait on Wikipedia.
|
||||||
*/
|
*/
|
||||||
export async function cachedExtract(title: string, ms = 300): Promise<{ title: string; extract: string } | null> {
|
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 (have?.extract) return { title: have.title, extract: have.extract };
|
||||||
if (config.mode === "off") return null;
|
if (config.mode === "off") return null;
|
||||||
const ac = new AbortController();
|
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. */
|
/** 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 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):
|
* 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
|
* 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 {
|
function cleanHtml(html: string): string {
|
||||||
const have = cleaned.get(html);
|
|
||||||
if (have !== undefined) return have;
|
|
||||||
const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");
|
const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");
|
||||||
const walk = (el: Element) => {
|
const walk = (el: Element) => {
|
||||||
for (const child of [...el.children]) {
|
for (const child of [...el.children]) {
|
||||||
@@ -192,10 +187,7 @@ export function cleanHtml(html: string): string {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
walk(doc.body);
|
walk(doc.body);
|
||||||
const out = doc.body.innerHTML;
|
return doc.body.innerHTML;
|
||||||
if (cleaned.size > 400) cleaned.delete(cleaned.keys().next().value as string);
|
|
||||||
cleaned.set(html, out);
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A piece of article HTML as text to select in (articleText.ts). Remembered per string. */
|
/** A piece of article HTML as text to select in (articleText.ts). Remembered per string. */
|
||||||
|
|||||||
Reference in new issue
Block a user