Web pages: a page without headings is arranged by itself, and a typed address becomes a titled link

A page cut into parts by length is now arranged into titled sections by a
model when it is first read, through the same gates as s (a model, the
daily budget, the plan's limits, one request per text), once per text per
server run. EX_PAGES_ARRANGE=manual keeps it to s. The pane shows the
parts at once, says that it is arranging or why it did not, and swaps the
sections in when they arrive.

A bare http(s) address typed into a node's text is linked when the edit
ends, then replaced by the page's title once that is read; u brings the
address back. A node whose whole text is one address becomes a section
that is only a link. See docs/pages.md.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
thalladaandClaude Fable 5.2 committed 2026-11-18 14:19:21 -05:00
1 parent f8c6576ea1
commit 57b605e13c
19 files changed
+1095 -92

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
/**
* Bare addresses typed into a node's text (src/core/bareLinks.ts): which addresses are picked up
* (trailing punctuation, brackets, code spans, words already linked, only those new in the edit,
* declined ones), the link made as typed, the title swapped in while the words are untouched (and
* not after a concurrent edit of them on another replica), undo bringing the address back without
* it being converted again, a Wikipedia address, and a section whose whole text is an address.
*/
import { UndoManager } from "loro-crdt";
import { describe, expect, it } from "vitest";
import { addressTarget, bareAddresses, linkAddresses, newAddresses, placeholderTitle, titleLink, titleWhole, titleWords } from "../src/core/bareLinks";
import { Doc, SYSTEM_ORIGIN, linkOnly, notesOf, type NodeId } from "../src/core/model";
import { healAnchors, history, mergeUpdate } from "../src/core/repo";
import { phraseKey } from "../src/core/links";
const PAGE = "https://tracing.example.org/posts/following-a-request";
const meta = { author: "alice" };
function lib(body = "", title = "Reading") {
const doc = Doc.library("alice");
const [id] = doc.apply([{ op: "create", parent: doc.snap().root, title, body }], "Add").created;
return { doc, id };
}
/** An edit of a node's text, as commitEdit makes it, and step 1 after it. */
function edit(doc: Doc, id: NodeId, body: string) {
const before = doc.snap().nodes[id].body;
doc.apply([{ op: "update", id, body }], "Edit");
return linkAddresses(doc, id, before, meta);
}
const links = (doc: Doc, id: NodeId) => notesOf(doc.snap(), id).map((c) => doc.snap().nodes[c]).filter((n) => n.ref);
const sync = (into: Doc, from: Doc) => mergeUpdate(into, from.loro.export({ mode: "update", from: into.loro.version() }), from.loro.version().toJSON());
describe("which addresses are picked up", () => {
it("trailing punctuation is not part of an address; a bracket only when it closes one inside", () => {
const text = `See ${PAGE}. Also (https://a.example.org/x), https://en.wikipedia.org/wiki/Mercury_(planet), and https://b.example.org/q?a=1&b=2!`;
expect(bareAddresses(text).map((b) => b.url)).toEqual([PAGE, "https://a.example.org/x", "https://en.wikipedia.org/wiki/Mercury_(planet)", "https://b.example.org/q?a=1&b=2"]);
const [first] = bareAddresses(text);
expect(text.slice(...first.range)).toBe(PAGE);
});
it("none inside a code span or a fenced block; not half-typed ones, nor hosts without a dot", () => {
expect(bareAddresses("`https://code.example.org/a` and\n```\nhttps://fence.example.org/b\n```\nbut https://real.example.org/c")).toEqual([
{ range: expect.any(Array), url: "https://real.example.org/c" },
]);
expect(bareAddresses("https:// and http://localhost/x and ftp://x.example.org/ and xhttps://y.example.org/")).toEqual([]);
});
it("only addresses the edit brought: one already in the text before is never new", () => {
expect(newAddresses(`old ${PAGE}`, `old ${PAGE} and https://new.example.org/`).map((b) => b.url)).toEqual(["https://new.example.org/"]);
});
it("titles become plain words; placeholders say nothing yet", () => {
expect(titleWords(" A *bold*\n`title` [[x]] ")).toBe("A bold title x");
expect(placeholderTitle("", PAGE)).toBe(true);
expect(placeholderTitle("Untitled", PAGE)).toBe(true);
expect(placeholderTitle(PAGE, PAGE)).toBe(true);
expect(placeholderTitle("My reading", PAGE)).toBe(false);
expect(addressTarget("https://fr.m.wikipedia.org/wiki/Phare#Histoire")).toEqual({ kind: "wiki", title: "Phare", lang: "fr" });
expect(addressTarget(PAGE)).toEqual({ kind: "url", url: PAGE });
});
});
describe("an address typed into a node's text", () => {
it("is linked as typed, then titled from its page in a commit of its own; undo brings the address back, and it is not converted again", () => {
const { doc, id } = lib("A first line.");
const u = new UndoManager(doc.loro, { mergeInterval: 0, maxUndoSteps: 50, excludeOriginPrefixes: [SYSTEM_ORIGIN] });
doc.group = { start: () => u.groupStart(), end: () => u.groupEnd() };
const r = edit(doc, id, `A first line. Read ${PAGE}, then sleep.`);
expect(r.whole).toBeNull();
expect(r.links).toHaveLength(1);
let [link] = links(doc, id);
expect(link.ref).toEqual({ kind: "url", url: PAGE });
expect(link.anchors[0].text).toBe(PAGE);
expect(history(doc).map((c) => c.message).join("\n")).toMatch(/^Link “https:\/\/tracing/);
expect(titleLink(doc, r.links[0], "Following one request through the stack", meta)).toBe(true);
expect(doc.snap().nodes[id].body).toBe("A first line. Read Following one request through the stack, then sleep.");
[link] = links(doc, id);
expect(link.anchors[0].text).toBe("Following one request through the stack");
expect(link.ref).toEqual({ kind: "url", url: PAGE, title: "Following one request through the stack" });
// u: the address back, still linked to the page.
u.undo();
doc.touch();
healAnchors(doc);
expect(doc.snap().nodes[id].body).toBe(`A first line. Read ${PAGE}, then sleep.`);
[link] = links(doc, id);
expect(link.anchors[0].text).toBe(PAGE);
// A later edit of the same node does not take it for new.
const again = edit(doc, id, `A first line, changed. Read ${PAGE}, then sleep.`);
expect(again).toEqual({ links: [], whole: null });
});
it("several addresses in one edit are linked in one commit; words already linked and declined phrases are left alone", () => {
const { doc, id } = lib("Start.");
const one = edit(doc, id, "Start. https://one.example.org/a and https://two.example.org/b");
expect(one.links.map((l) => l.url)).toEqual(["https://one.example.org/a", "https://two.example.org/b"]);
expect(links(doc, id)).toHaveLength(2);
// An address typed where it is already linked (the same words, linked by hand before) stays as it is.
const { doc: d2, id: n2 } = lib("Start.");
const before = d2.snap().nodes[n2].body;
d2.apply([{ op: "update", id: n2, body: "Start. https://three.example.org/c" }], "Edit");
d2.apply([{ op: "create", parent: n2, kind: "note", quote: "https://three.example.org/c", ref: { kind: "wiki", title: "Octopus", lang: "en" } }], "Link by hand");
expect(linkAddresses(d2, n2, before, meta).links).toEqual([]);
// A declined phrase (D on the link) is not linked again.
const { doc: d3, id: n3 } = lib("Start.", "Declined");
const r3 = edit(d3, n3, "Start. https://four.example.org/d");
d3.apply([{ op: "delete", id: r3.links[0].note }, { op: "update", id: n3, body: "Start.", nolink: [phraseKey("https://four.example.org/d")] }], "Decline");
expect(edit(d3, n3, "Start. https://four.example.org/d").links).toEqual([]);
});
it("the swap is dropped when the words were changed meanwhile, here or on another replica", () => {
const { doc, id } = lib("Start.");
const r = edit(doc, id, `Start. ${PAGE}`);
// Another replica edits the address before the title arrives here.
const other = doc.fork("bob");
other.apply([{ op: "update", id, body: `Start. ${PAGE}/more` }], "Edit");
sync(doc, other);
expect(titleLink(doc, r.links[0], "Following one request", meta)).toBe(false);
expect(doc.snap().nodes[id].body).toBe(`Start. ${PAGE}/more`);
// And a retargeted link keeps its words.
const { doc: d2, id: n2 } = lib("Start.");
const r2 = edit(d2, n2, `Start. ${PAGE}`);
d2.apply([{ op: "update", id: r2.links[0].note, ref: { kind: "wiki", title: "Octopus", lang: "en" } }], "Retarget");
expect(titleLink(d2, r2.links[0], "Following one request", meta)).toBe(false);
});
it("a Wikipedia article's address is linked to the article, and titled with its title", () => {
const { doc, id } = lib("Start.");
const r = edit(doc, id, "Start. See https://en.wikipedia.org/wiki/Common_octopus.");
expect(r.links[0].target).toEqual({ kind: "wiki", title: "Common octopus", lang: "en" });
expect(titleLink(doc, r.links[0], "Common octopus", meta)).toBe(true);
expect(doc.snap().nodes[id].body).toBe("Start. See Common octopus.");
expect(links(doc, id)[0].ref).toEqual({ kind: "wiki", title: "Common octopus", lang: "en" });
});
});
describe("a section whose whole text is an address", () => {
it("becomes a section that is only the link, named by its page when its title says nothing yet", () => {
const { doc, id } = lib("", "");
const r = edit(doc, id, ` ${PAGE} `);
expect(r.links).toEqual([]);
expect(r.whole).toEqual({ node: id, url: PAGE, target: { kind: "url", url: PAGE } });
let n = doc.snap().nodes[id];
expect(n.body).toBe("");
expect(n.ref).toEqual({ kind: "url", url: PAGE });
expect(linkOnly(doc.snap(), id)).toBe(true);
expect(titleWhole(doc, r.whole!, "Following one request through the stack", meta)).toBe(true);
n = doc.snap().nodes[id];
expect(n.title).toBe("Following one request through the stack");
expect(n.ref).toEqual({ kind: "url", url: PAGE, title: "Following one request through the stack" });
});
it("keeps a title of its own", () => {
const { doc, id } = lib("", "My reading");
const r = edit(doc, id, PAGE);
expect(r.whole).not.toBeNull();
expect(titleWhole(doc, r.whole!, "Following one request", meta)).toBe(false);
expect(doc.snap().nodes[id].title).toBe("My reading");
});
it("a Wikipedia address makes it a section about the article", () => {
const { doc, id } = lib("", "");
const r = edit(doc, id, "https://en.wikipedia.org/wiki/Octopus");
expect(doc.snap().nodes[id].ref).toEqual({ kind: "wiki", title: "Octopus", lang: "en" });
expect(titleWhole(doc, r.whole!, "Octopus", meta)).toBe(true);
expect(doc.snap().nodes[id].title).toBe("Octopus");
});
});
+144 -3
View File
@@ -14,7 +14,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { mockLLM } from "../src/llm/mock";
import type { ArrangeReply, JsonReq, LLM } from "../src/llm/types";
import { BY_MODEL, PageClient, SUMMARY_BY_MODEL, type WebArticle } from "../server/page";
import { ARRANGE_SYSTEM, Arranger, DailyBudget, MAX_TOKENS, MIN_OPENING, OPENING, arrangeInput, cleanSections, estimate, serverBudget, type ArrangerOptions } from "../server/pageArrange";
import { ARRANGE_SYSTEM, Arranger, DailyBudget, MAX_TOKENS, MIN_OPENING, OPENING, arrangeInput, arrangeMode, cleanSections, estimate, serverBudget, type ArrangerOptions } from "../server/pageArrange";
import type { PageUnit } from "../server/pageHtml";
import { MOCK_PAGES, makeMockPageFetch } from "../server/pageMock";
import { pageRoutes } from "../server/pageRoutes";
@@ -377,6 +377,119 @@ describe("Reload", () => {
});
});
describe("arranging by itself (Arranger.auto)", () => {
const settled = () => new Promise((r) => setTimeout(r, 5));
it("a page divided by length: one call, started and not waited for; then kept, so opening it again costs nothing", async () => {
const { pages, llm, arranger } = await setup({ llm: counting(undefined, 20) });
const calls = (llm as ReturnType<typeof counting>).calls;
expect(arranger.auto(MOCK_PAGES.essay)).toEqual({ state: "running" });
// Asked again while it runs: the same flight, no second call; the browser's join waits for it.
expect(arranger.auto(MOCK_PAGES.essay)).toEqual({ state: "running" });
const joined = await arranger.arrange(MOCK_PAGES.essay, { join: true });
expect(joined).toMatchObject({ ok: true, called: true, arranged: "sections" });
expect(calls).toHaveLength(1);
// Arranged as it now reads: nothing more to say, and no call, however often it is opened.
expect(arranger.auto(MOCK_PAGES.essay)).toBeUndefined();
const again = (await pages.article(MOCK_PAGES.essay)) as { ok: true; value: WebArticle };
expect(again.value.outline).toBe("model");
expect(await arranger.arrange(MOCK_PAGES.essay, { join: true })).toMatchObject({ ok: true, called: false });
expect(calls).toHaveLength(1);
// What is sent is what s sends: the same cap and the same untrusted-text block.
expect(calls[0].system).toBe(ARRANGE_SYSTEM);
expect(calls[0].prompt).toContain("<page_text>");
expect(calls[0].vars?.mode).toBe("arrange");
});
it("a page with headings, one short enough to be a lead, and one not read here: nothing, no call", async () => {
const { llm, arranger } = await setup({ read: [MOCK_PAGES.tracing, MOCK_PAGES.letters, MOCK_PAGES.vanishing, MOCK_PAGES.pdf] });
for (const u of [MOCK_PAGES.tracing, MOCK_PAGES.letters, MOCK_PAGES.vanishing, MOCK_PAGES.pdf, MOCK_PAGES.essay]) expect(arranger.auto(u)).toBeUndefined();
await settled();
expect((llm as ReturnType<typeof counting>).calls).toHaveLength(0);
});
it("the day's budget spent: not tried, and why, every time it is asked; the join and s are refused the same, with no call", async () => {
const llm = counting();
const { arranger } = await setup({ llm, budget: new DailyBudget(null, 0) });
const st = arranger.auto(MOCK_PAGES.essay);
expect(st).toMatchObject({ state: "skipped", reason: "budget", message: expect.stringMatching(/used up/) });
expect(arranger.auto(MOCK_PAGES.essay)).toEqual(st);
expect(await arranger.arrange(MOCK_PAGES.essay, { join: true })).toMatchObject({ ok: false, reason: "budget" });
expect(await arranger.arrange(MOCK_PAGES.essay)).toMatchObject({ ok: false, reason: "budget" });
expect(llm.calls).toHaveLength(0);
});
it("the plan nearly used, no model, EX_PAGES_ARRANGE=off or manual: skipped with the reason, no call; manual leaves s working", async () => {
const plan = () => ({ windows: [], tightest: null, remainingPercent: 8, resetsAt: null, warning: true, limited: false, limitResetsAt: null, limitLabel: null, overage: null, updatedAt: null, source: null });
const cases: [Setup, string][] = [
[{ plan }, "plan"],
[{ llm: null }, "no-model"],
[{ on: false, auto: false }, "off"],
[{ auto: false }, "manual"],
];
for (const [o, reason] of cases) {
const llm = o.llm === null ? null : counting();
const { arranger } = await setup({ ...o, llm });
expect(arranger.auto(MOCK_PAGES.essay)).toMatchObject({ state: "skipped", reason });
await settled();
if (llm) expect((llm as ReturnType<typeof counting>).calls).toHaveLength(0);
if (reason === "manual") {
expect(arranger.automatic).toBe(false);
expect(await arranger.arrange(MOCK_PAGES.essay)).toMatchObject({ ok: true, called: true });
}
}
});
it("a failed attempt is not tried again by itself (it waits for s); a Reload that changes the text tries once more", async () => {
let fail = true;
const llm = counting((req) => {
if (fail) throw new Error("the model is down");
return { summary: "Arranged.", sections: [{ title: "One", start: Number(req.vars?.first) }, { title: "Two", start: Number(req.vars?.first) + 3 }] };
});
const base = makeMockPageFetch();
let html = await (await base(MOCK_PAGES.essay)).text();
const fetch = (async (input: string | URL | Request, init?: RequestInit) =>
String(input) === MOCK_PAGES.essay ? new Response(html, { headers: { "content-type": "text/html" } }) : base(input, init)) as typeof globalThis.fetch;
const pages = client(fetch);
await pages.article(MOCK_PAGES.essay);
const arranger = new Arranger({ pages: () => pages, llm: () => llm, budget: new DailyBudget(null, 20) });
expect(arranger.auto(MOCK_PAGES.essay)).toEqual({ state: "running" });
expect(await arranger.arrange(MOCK_PAGES.essay, { join: true })).toMatchObject({ ok: false, reason: "failed" });
await settled();
for (let i = 0; i < 3; i++) expect(arranger.auto(MOCK_PAGES.essay)).toMatchObject({ state: "skipped", reason: "failed", message: /the model is down/ });
expect(llm.calls).toHaveLength(1);
// Read again, unchanged: the same hash, still not tried again.
await pages.reload(MOCK_PAGES.essay);
expect(arranger.auto(MOCK_PAGES.essay)).toMatchObject({ state: "skipped", reason: "failed" });
expect(llm.calls).toHaveLength(1);
// s tries again, and works.
fail = false;
expect(await arranger.arrange(MOCK_PAGES.essay)).toMatchObject({ ok: true, called: true, arranged: "sections" });
expect(llm.calls).toHaveLength(2);
// Changed text: a new hash, the parts by length again, and one attempt for it.
html = html.replace("June 2019", "July 2019");
const r = await pages.reload(MOCK_PAGES.essay);
expect(r.ok && r.value.outline).toBe("chunks");
expect(arranger.auto(MOCK_PAGES.essay)).toEqual({ state: "running" });
expect(await arranger.arrange(MOCK_PAGES.essay, { join: true })).toMatchObject({ ok: true, called: true });
expect(llm.calls).toHaveLength(3);
});
it("the join never starts a call", async () => {
const llm = counting();
const { arranger } = await setup({ llm });
expect(await arranger.arrange(MOCK_PAGES.essay, { join: true })).toMatchObject({ ok: false, reason: "idle" });
expect(llm.calls).toHaveLength(0);
});
it("EX_PAGES_ARRANGE: off, manual, else both", () => {
expect(arrangeMode({})).toEqual({ on: true, auto: true });
expect(arrangeMode({ EX_PAGES_ARRANGE: "manual" })).toEqual({ on: true, auto: false });
expect(arrangeMode({ EX_PAGES_ARRANGE: "off" })).toEqual({ on: false, auto: false });
expect(arrangeMode({ EX_PAGES_ARRANGE: "on" })).toEqual({ on: true, auto: true });
});
});
describe("POST /api/page/reload and /api/page/arrange", () => {
let server: Server;
let base: string;
@@ -410,15 +523,43 @@ describe("POST /api/page/reload and /api/page/arrange", () => {
it("arrange: 404 for a page not read here; then the page arranged; then the kept result", async () => {
expect(await post("arrange", { url: MOCK_PAGES.essay })).toMatchObject({ status: 404, body: { ok: false, reason: "uncached" } });
expect((await post("reload", { url: MOCK_PAGES.essay })).status).toBe(200);
// Read (here by a Reload): a page divided by length is arranged by itself, and s finds it done or joins it.
expect(await post("reload", { url: MOCK_PAGES.essay })).toMatchObject({ status: 200, body: { article: { outline: "chunks", auto: { state: "running" } } } });
const r = await post("arrange", { url: MOCK_PAGES.essay });
expect(r).toMatchObject({ status: 200, body: { ok: true, called: true, arranged: "sections", article: { outline: "model" } } });
expect(r).toMatchObject({ status: 200, body: { ok: true, arranged: "sections", article: { outline: "model" } } });
expect((await post("arrange", { url: MOCK_PAGES.essay })).body).toMatchObject({ ok: true, called: false });
expect(llm.calls).toHaveLength(1);
const article = await (await fetch(`${base}/api/page/article?url=${encodeURIComponent(MOCK_PAGES.essay)}`)).json();
expect(article.article.outline).toBe("model");
});
it("article starts arranging a page divided by length and says so; the join waits for it; a page with headings says nothing", async () => {
const before = llm.calls.length;
const first = await (await fetch(`${base}/api/page/article?url=${encodeURIComponent(MOCK_PAGES.drift)}`)).json();
expect(first.article).toMatchObject({ outline: "chunks", auto: { state: "running" } });
const joined = await post("arrange", { url: MOCK_PAGES.drift, auto: true });
// The mock model fails a page whose title says "mockfail": the join answers with the failure.
expect(joined).toMatchObject({ status: 502, body: { ok: false, reason: "failed" } });
const again = await (await fetch(`${base}/api/page/article?url=${encodeURIComponent(MOCK_PAGES.drift)}`)).json();
expect(again.article.auto).toMatchObject({ state: "skipped", reason: "failed" });
expect(llm.calls.length).toBe(before + 1);
const tracing = await (await fetch(`${base}/api/page/article?url=${encodeURIComponent(MOCK_PAGES.tracing)}`)).json();
expect(tracing.article.auto).toBeUndefined();
expect(llm.calls.length).toBe(before + 1);
});
it("summary, read for a link's title, starts it too; a card's look at the cache does not", async () => {
const before = llm.calls.length;
const card = await fetch(`${base}/api/page/summary?url=${encodeURIComponent(MOCK_PAGES.slow)}&cached=1`);
expect(card.status).toBe(404);
expect((await (await fetch(`${base}/api/page/summary?url=${encodeURIComponent(MOCK_PAGES.slow)}`)).json()).summary.title).toBe("Slow water (mockslow)");
expect(await post("arrange", { url: MOCK_PAGES.slow, auto: true })).toMatchObject({ status: 200, body: { ok: true, called: true, arranged: "sections" } });
expect(llm.calls.length).toBe(before + 1);
const read = await (await fetch(`${base}/api/page/summary?url=${encodeURIComponent(MOCK_PAGES.slow)}&cached=1`)).json();
expect(read.ok).toBe(true);
expect(llm.calls.length).toBe(before + 1);
});
it("reload: a page that cannot be shown is a 422, as for article", async () => {
expect(await post("reload", { url: MOCK_PAGES.pdf })).toMatchObject({ status: 422, body: { ok: false, reason: "type" } });
});