diff --git a/README.md b/README.md index 94326c3..e19815a 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,8 @@ use on their own machine. | `EX_USER` | your login name | The name on commits the server makes for you (the page lets you change yours with `/user`). | | `EX_WIKI` | `live` | `mock`: built-in test articles, no network (the browser tests); `off`: every `/api/wiki/*` route answers 503. | | `EX_PAGES` | `live` | Web pages opened from a link (`/api/page/*`): `mock`: built-in test pages, no network (the browser tests); `off`: every route answers 503. Only a page you open is read, robots.txt is honoured, and the text is cached under `EX_DATA/page-cache/`, never in a library (docs/pages.md). | -| `EX_PAGES_ARRANGE` | `on` when a model is configured | `off`: `s` on a web page (a model's summary, and sections for a page divided only by length) is refused. | -| `EX_PAGE_CALLS` | `20` | Model calls a day (UTC) for arranging web pages, for the whole server, counted in `EX_DATA/page-calls.json`. Pages are also not arranged while the plan's limits are nearly used. | +| `EX_PAGES_ARRANGE` | `on` when a model is configured | A model's summary of a web page, and sections for a page divided only by length: on request (`s`), and by itself, once, for a page with no headings when it is first read. `manual`: only on request. `off`: never (`s` is refused). | +| `EX_PAGE_CALLS` | `20` | Model calls a day (UTC) for arranging web pages, by request or by themselves, for the whole server, counted in `EX_DATA/page-calls.json`. Pages are also not arranged while the plan's limits are nearly used. | | `EX_HOSTS` | (none) | Extra host names the dev server answers to, comma-separated. `localhost` and `*.ts.net` (Tailscale) are always allowed. | | `EX_WIKI_LANG` | `en` | Which Wikipedia. | | `EX_WIKI_CONTACT` | unset | An email address, an `https://` URL or `User:Name` for the User-Agent of Wikipedia requests. Without it requests are spaced 6.5 s apart (the page says so once, the first time it is slow); with it, 1 s. Nothing else about you is sent. | @@ -267,10 +267,17 @@ Press `?` for every key. The short version: a page that needs JavaScript) says why and offers the original. `W` opens the original in a new tab. An address on wikipedia.org opens as the article. Nothing is written on a page's text: its annotations are not kept (docs/pages.md). -- On a web page, `s` asks the model (only then, within `EX_PAGE_CALLS` calls a day) for a short - summary, shown above the page's opening and marked as the model's, and, for a page with no - headings that was divided by length, for sections of its choosing; a page with headings keeps - them. Pressed again on the same text it costs nothing. `R` reads the page again (it is otherwise +- A page with **no headings** of its own is first shown divided by length, and the model is asked + once, by itself, for sections of its choosing and a short summary (within `EX_PAGE_CALLS` calls a + day, never while the plan's limits are nearly used; `EX_PAGES_ARRANGE=manual` leaves it to `s`). + A quiet line says "Arranging into sections with a model…" meanwhile, and the page swaps to the + sections when they come (a pane open on one of its parts by length closes, and the status line + says so). When it is not done (the day's calls used, the plan nearly used, no model, the call + failed) the parts stay and the line says why; it is not tried again by itself for the same text. + The result is kept with the page, so opening it again costs nothing. +- On a web page, `s` asks the model for the same: a short summary, shown above the page's opening + and marked as the model's, and, for a page divided by length, sections of its choosing; a page + with headings keeps them. Pressed again on the same text it costs nothing. `R` reads the page again (it is otherwise kept as first read): unchanged text keeps what the model made; a page that no longer answers keeps the copy read before, marked stale. Both are in the page's menu too. A link's card shows the page's title, author, date and first sentence once the page has been read, and choosing an @@ -304,7 +311,16 @@ Press `?` for every key. The short version: is listed at the top of its section as detached, with a link to the old revision. Tables and preformatted blocks are shown but cannot be selected; a formula is selected whole. - To link by hand, select words (`i`, widen with `H` `L`) and press `w`: the picker offers library - sections and notes, Wikipedia articles and, for a pasted address, the web page. `w` on a link + sections and notes, Wikipedia articles and, for a pasted address, the web page. +- **An address typed into a node's text** (`http://` or `https://`, not in a `code span`, not on + words already linked) is linked when the edit is finished, as `w` would link it; then the page's + title is read and put in place of the address, the link moving with it (a Wikipedia article's + address links to the article, under its title). Each is one step of `u`: `u` after the title + brings the address back, still linked, and it is not converted again. A page that cannot be read + keeps its address, linked, and the status line says why. At most five pages are read from one + edit. A section whose whole text is one address becomes a section that is only that link, named + after the page if it had no title of its own. A page with no headings is arranged in the + background meanwhile, so opening the link is immediate. `w` on a link retargets it, `D` removes it (for good: see below); `:/link target` and `:/unlink` do the same. - A link to a deleted node stays in the text, marked broken, with the titles down to it from the library root, so undoing the delete finds it again. @@ -568,7 +584,7 @@ Node ids are the library's, so one batch of ops can work anywhere in it. | `GET /api/wiki/…` | Wikipedia through the server's cache: `summary`, `article` (`&full=1` for every section), `senses`, `suggest`, `media?u=` (a picture on upload.wikimedia.org that an article served here shows; same-origin requests only) (server/wikiRoutes.ts) | | `GET /api/page/…` | a web page through the server's cache: `article?url=`, `summary?url=` (`&cached=1`: never read the page), `media?u=` (an image a cached page shows, or a video's still); same-origin requests only (server/pageRoutes.ts) | | `POST /api/page/reload` `{ url }` | read the page again: the new copy, or the last one with `stale: ` when it no longer answers | -| `POST /api/page/arrange` `{ url }` | a model's summary of a cached page, and sections for one divided by length: `{ article, called, arranged, note? }`; refused with `{ reason, message }` (404 not read here, 422 too long, 429 the day's calls or the plan, 502 the call failed, 503 no model or `EX_PAGES_ARRANGE=off`) | +| `POST /api/page/arrange` `{ url, auto? }` | a model's summary of a cached page, and sections for one divided by length: `{ article, called, arranged, note? }`; refused with `{ reason, message }` (404 not read here, 422 too long, 429 the day's calls or the plan, 502 the call failed, 503 no model or `EX_PAGES_ARRANGE=off`). `auto: true` only waits for an arrangement under way (409 `idle` if there is none) and never makes a call. `article`, `reload` and `summary` start one by themselves for a page divided by length; `article` and `reload` say where it stands in the page's `auto` | | `POST /api/l//links/scan` `{ node, review? }` | scan a node and record what is found as pending; with `review`, the model reviewer judges what is new, and the approved links are handed back to be made | | `GET /api/l//links/pending?node=&subtree=1&tier=auto\|suggest&all=1&claim=1` | pending suggestions with the context a reviewer needs; `all` with every determination; `claim` hands out the approved links no page has made | | `POST /api/l//links/accept` / `reject` `{ ids, author? }` | link them in one commit, or record them as declined | diff --git a/docs/pages.md b/docs/pages.md index 0126475..a5cfd94 100644 --- a/docs/pages.md +++ b/docs/pages.md @@ -32,7 +32,7 @@ Seventeen pages, chosen to cover the kinds of page a reader links to, each fetch | 16 | WordPress | joelonsoftware.com | 200 | 3,675 | `N.` | byline class | meta | pseudo-headings | | 17 | hand-written | norvig.com | 200 | 2,753 | 9 h2 | layout only → none | none | headings | -("model organise": such a page is split by length, and the reader may have a model arrange it, §10.) +("model organise": such a page is split by length, and a model arranges it, by itself once and at the reader's request, §10.) What the table says: @@ -220,7 +220,7 @@ become section titles, the page's `h1` its title, and junk sections are the one | `GET /api/page/summary?url=…[&cached=1]` | 200 `{ ok, cached, summary: WebSummary }`: title, site, author, date, description and the lead's first sentence; `cached=1` never reads the page (404 `uncached`) | | `GET /api/page/media?u=…` | the image, if a kept snapshot shows it (a picture, or a video's still: its poster, YouTube's thumbnail): `image/*` only, 10 MB, `cache-control: private, max-age=604800`, `content-security-policy: sandbox`, `x-content-type-options: nosniff`; 404 for any address no snapshot shows (it is not an open proxy), 415 for something that is not an image | | `POST /api/page/reload` `{ url }` | the page read again: 200 `{ ok, article }`, or the last copy with `stale: ` when it no longer answers; a page never shown that still cannot be is a 422 or 503 `WebUnusable` | -| `POST /api/page/arrange` `{ url }` | §10: 200 `{ ok, article, called, arranged: "sections" \| "summary", note? }`; refused with `{ ok: false, reason, message }`: 404 `uncached`, 409 `old` (a copy read before arranging existed), 422 `too-long`, 429 `budget` or `plan`, 502 `failed`, 503 `no-model` or `off` | +| `POST /api/page/arrange` `{ url, auto? }` | §10: 200 `{ ok, article, called, arranged: "sections" \| "summary", note? }`; refused with `{ ok: false, reason, message }`: 404 `uncached`, 409 `old` (a copy read before arranging existed), 422 `too-long`, 429 `budget` or `plan`, 502 `failed`, 503 `no-model` or `off`. With `auto: true` it only waits for an arrangement by itself under way (§10), answering with what it came to (409 `idle`: none under way), and never makes a call | A page that cannot be shown is a 422 with the `WebUnusable` body; an unreachable or failing site 503. `EX_PAGES=off` answers every route with 503 `reason: "off"`; `/api/state` says @@ -250,7 +250,9 @@ refresh. Video and Wikipedia's pictures came later (§11; docs/wikipedia.md §3) disk. `MOCK_PAGES` lists their addresses; each is named for the shape it imitates (§1), and one, `vanishing`, answers once and then 410, for a Reload that finds a page gone. With `EX_LLM=mock` the mock model arranges a page into three sections, sending them out of order, with a repeat and a -number past the end, so that the cleaning in §10 is exercised every time. +number past the end, so that the cleaning in §10 is exercised every time. Two headingless fixtures +are there for arranging by itself: `drift`, whose title says "mockfail", which the mock model fails +on, and `slow`, whose title says "mockslow", over which it takes 1.5 s. ## 8. If the server is ever reachable by others @@ -327,13 +329,40 @@ instead. The view reuses the article view's structure and classes (`.wiki`, `.wi reader's choice (2.5 s at most, the picker saying so meanwhile, Esc leaving the words unlinked), and keeps it in `Ref.title` in the same commit as the link; a page that is slow or cannot be read is linked without one. A title is never written because a page was opened. +- **An address typed into a node's text** (`src/core/bareLinks.ts`, `Store.typedAddresses`) is + turned into a titled link once the edit is finished, never while typing, in three steps that are + each one commit, so `u` takes each back on its own: + 1. Each bare `http(s)` address new in this edit (not in the text before it; not inside a code span + or words already linked; not a phrase declined in the node's `nolink`; trailing `.,;:!?…` and + an unbalanced `)` or `]` left out; a host with a dot) is linked as typed, all in one commit, as + selecting it and `w` would: a Wikipedia article's address to the article (`wikiRefOf`), any + other to the page. A section whose whole text is one address, with no target and no sections, + instead becomes a section that is only that link (its text cleared, `linkOnly`), so it opens + straight as the page. + 2. Each page is read for its title (`GET /api/page/summary`, up to 20 s; at most five pages from + one edit, the rest staying linked as typed, and the status line says so); an article's title + is in its address. Reading the page also starts arranging it by itself (§10), so the link opens + at once, already arranged. + 3. The address in the text is replaced by the title, with the link's anchor (and `Ref.title`), as + the address out then the title in, so undo puts the link back on the address. Only while those + words are still the whole address as typed and the link still goes there: a concurrent edit of + them, here or merged from another replica, drops the step. A title that arrives while the node's + text is being edited again waits for that edit to finish. For a section made a link, its title + is set to the page's only while it is empty or a placeholder; a title of its own is kept. + + `u` after step 3 brings the address back, still linked; a later edit finds it in the text before + it, so it is never converted again. A page that cannot be read (robots, a refusal, offline, not a + page, `EX_PAGES=off`) keeps its address, linked, and the status line says why, once. It is always + on: unlike link suggestions it acts only on what the reader typed, and every step is undone like + any edit. ## 10. Arranging with a model (server/pageArrange.ts) -A page with no headings is divided by length (§4), which is honest but blind. On the reader's -request (`s` on a page, or "Arrange with a model" in its menu; `POST /api/page/arrange`), a model -writes a short summary of the page and, for a page divided by length, chooses where its sections -begin. Never on opening, never in the background. +A page with no headings is divided by length (§4), which is honest but blind. A model writes a +short summary of the page and, for a page divided by length, chooses where its sections begin: by +itself, once, for a page divided by length when it is first read (below), and on the reader's +request (`s` on a page, or "Arrange with a model" in its menu; `POST /api/page/arrange`) for any +page. - **What is sent.** The page's title, and each unit of the lead and sections numbered in reading order, as its first 150 characters (a figure as `[image: caption]`, a heading as @@ -361,7 +390,10 @@ begin. Never on opening, never in the background. gains only the summary; so does a page short enough to be one lead. - **Panes.** Section ids are namespaced by outline, so a pane open on a part by length (`c2`) names nothing in the model's outline: it closes when the arranged page arrives, and the status - line says so with the result. + line says so with the result. Moving such a pane to the model's section that holds its first + unit was considered and left out: the arrangement usually arrives within seconds of opening, + before the reader has opened a part, and a pane silently showing a different, longer span would + lose the place nearly as much as closing it. - **The gate**, checked before any call, each refusal a sentence the status line shows: no model; `EX_PAGES_ARRANGE=off`; the plan's limits nearly used (`warning`) or refusing (`limited`, server/ usage.ts), so that what is left of a plan goes to writing; the server's day of calls spent @@ -369,6 +401,32 @@ begin. Never on opening, never in the background. UTC, every call made counted, failed ones too). One call per content hash however many ask at once; a page already arranged for the text it now has answers from its snapshot without a call (the status line says "no new call"). +- **By itself** (`Arranger.auto`). The owner expected a page without headings of its own to be given + section titles without being asked, so the routes that read a page for a person, `article`, + `reload` and `summary` (not `&cached=1`: a card never spends anything), start the same call `s` + makes, without waiting for it, for a page whose outline is `chunks` and that has nothing a model + made for its current hash. Pages with headings or pseudo-headings (real text of the page's own, + left as they are), pages short enough to be one lead, and pages that cannot be shown never start + it. It goes through the same gate, the same input cap, the same untrusted-text block, the same + daily budget and the same single flight per hash, plus one more refusal: `EX_PAGES_ARRANGE=manual` + leaves arranging to `s` alone. **One attempt per content hash per server run**: a refusal + (budget, plan, too long, an old copy) or a failure is remembered, in memory, and said each time + the page is sent, but not tried again by itself; `s` still may. A Reload with unchanged text keeps + the hash, and so the arrangement or the refusal; one that changes the text is a new hash and gets + one attempt. No model, `off` and `manual` are not attempts, only said. Kept in memory rather than + in the snapshot, so a restart is the one way a failed page is tried by itself again. +- **What the reader sees.** `article` and `reload` send the page with `auto: { state: "running" }` + or `{ state: "skipped", reason, message }` (never kept in the snapshot). The page is shown at once, + in its parts by length, with one quiet line: "Arranging into sections with a model…", or "Kept in + parts by length: s tries again." (nothing about `s` for no model or `off`, "s arranges it" + for `manual`). While it runs the browser asks `arrange` with `auto: true`, which only joins the + call under way (or answers with the kept result, or why it came to nothing) and can never start a + call, so asking costs nothing whatever happens; there is no other channel. When the sections come + the page swaps to them in place: the reader's pane on the page stays where it is, a focus on one + of its rows moves to its head, and a pane open on a part by length closes (its id, `c2`, names + nothing in the model's outline) with one status line saying why. Nothing else is said, so a page + arranged before the reader got to its parts changes only its rows. A page read for a link's title + (§9) is arranged without any pane open; opening it later finds it done. ## 11. Videos (and what loads when) diff --git a/e2e/addresses.spec.ts b/e2e/addresses.spec.ts new file mode 100644 index 0000000..2d81082 --- /dev/null +++ b/e2e/addresses.spec.ts @@ -0,0 +1,111 @@ +/** + * A bare address typed into a node's text becomes a titled link once the edit is finished + * (src/core/bareLinks.ts, Store.typedAddresses), against the mock web (EX_PAGES=mock) and the mock + * model: linked as typed, then the page's title in place of the address; u brings the address back, + * still linked, and it is not converted again; a page that cannot be read leaves the address linked + * as typed and the status line says why; a Wikipedia address becomes a link to the article; a + * section whose whole text is an address becomes a section that is only the link; several in one + * edit all convert, at most five pages read; a page with no headings is arranged in the background, + * so opening it later is immediate. The browser's own requests elsewhere are refused. + */ +import { expect, test, type Page } from "@playwright/test"; +import { WEB, addTop, keys, pageCalls, settle, state, visit } from "./helpers"; + +const status = (page: Page) => page.locator(".status .message"); +const body = (page: Page) => state(page, (s) => s.snap.nodes[s.focus.node].body as string); +/** The links on the focused node's text: their words and targets. */ +const linksHere = (page: Page) => + state(page, (s) => + s.snap.nodes[s.focus.node].children + .map((c: string) => s.snap.nodes[c]) + .filter((n: any) => n.kind === "note" && n.ref) + .map((n: any) => ({ words: n.anchors[0]?.text, ref: n.ref })), + ); + +test.beforeEach(async ({ context }) => { + await context.route((u) => /(^|\.)(wikipedia\.org|wikimedia\.org|example\.(org|com|net))$/.test(u.hostname), (r) => r.abort()); +}); + +test.afterEach(({ page }) => settle(page)); + +test("an address typed into the text is linked, then titled from its page; u brings the address back, linked, and it is not converted again", async ({ page }) => { + await addTop(page, "Reading the trace", `Start with ${WEB.tracing}, then the rest.`); + await expect.poll(() => body(page)).toBe("Start with Following one request through the stack, then the rest."); + expect(await linksHere(page)).toEqual([{ words: "Following one request through the stack", ref: { kind: "url", url: WEB.tracing, title: "Following one request through the stack" } }]); + await expect(status(page)).toContainText("Linked as “Following one request through the stack”, the page's title. u brings the address back."); + // Two commits of their own, after the edit: the link as typed, then the title (newest first). + const history: string[] = await state(page, (s) => s.commits().slice(0, 8).map((c: any) => c.message)); + const titled = history.findIndex((m) => /^Title the link “https:\/\/tracing\.example\.org.*”: “Following one request through the stack”$/.test(m)); + const linked = history.findIndex((m) => /^Link “https:\/\/tracing\.example\.org.*” to Following one request|^Link “https:\/\/tracing\.example\.org/.test(m)); + expect(titled).toBeGreaterThanOrEqual(0); + expect(linked).toBeGreaterThan(titled); + + await keys(page, "u"); + await expect.poll(() => body(page)).toBe(`Start with ${WEB.tracing}, then the rest.`); + expect(await linksHere(page)).toEqual([{ words: WEB.tracing, ref: { kind: "url", url: WEB.tracing } }]); + // Edited again, the address is not new: it stays as it is. + await keys(page, "c End"); + await page.keyboard.type(" More."); + await page.keyboard.press("Escape"); + await expect.poll(() => body(page)).toBe(`Start with ${WEB.tracing}, then the rest. More.`); + await page.waitForTimeout(300); + expect(await body(page)).toBe(`Start with ${WEB.tracing}, then the rest. More.`); + expect(await linksHere(page)).toEqual([{ words: WEB.tracing, ref: { kind: "url", url: WEB.tracing } }]); +}); + +test("a page that cannot be read leaves its address as typed, linked, and the status line says why", async ({ page }) => { + await addTop(page, "Tides asked", `The answer is at ${WEB.robots}.`); + await expect(status(page)).toContainText(`No title for ${WEB.robots}: qa.example.com asks programs like this one not to read this page (robots.txt).`); + await expect(status(page)).toContainText("The address stays as typed, linked."); + expect(await body(page)).toBe(`The answer is at ${WEB.robots}.`); + expect(await linksHere(page)).toEqual([{ words: WEB.robots, ref: { kind: "url", url: WEB.robots } }]); +}); + +test("a Wikipedia article's address becomes a link to the article, titled with its title", async ({ page }) => { + await addTop(page, "Eight arms", "Read https://en.wikipedia.org/wiki/Octopus first. Not `https://code.example.org/x` though."); + await expect.poll(() => body(page)).toBe("Read Octopus first. Not `https://code.example.org/x` though."); + expect(await linksHere(page)).toEqual([{ words: "Octopus", ref: { kind: "wiki", title: "Octopus", lang: "en" } }]); +}); + +test("several addresses in one edit all convert, at most five pages read; one with no headings is arranged in the background, so opening it is immediate", async ({ page }) => { + const calls = pageCalls(); + const urls = [WEB.essay, WEB.letters, WEB.rules, WEB.phare, WEB.figures, WEB.videos]; + await addTop(page, "Six addresses", urls.join(" and ")); + await expect.poll(() => body(page)).not.toContain(WEB.figures); + await expect.poll(() => body(page)).not.toMatch(new RegExp(urls.slice(0, 5).map((u) => u.replace(/[.?/]/g, "\\$&")).join("|"))); + const titles = await Promise.all(urls.slice(0, 5).map((u) => titleOf(page, u))); + expect(titles.slice(0, 3)).toEqual(["A Hundred Small Maps", "On maps", "Twelve rules for a small team – Notes on Software"]); + expect(await body(page)).toBe([...titles, WEB.videos].join(" and ")); + expect((await linksHere(page)).map((l: any) => l.ref.url)).toEqual(urls); + expect(await state(page, (s) => s.log.map((l: any) => l.text))).toContain("Linked 6 addresses; reading the page titles… 1 more is linked as typed, without reading its page (at most 5 are read from one edit)."); + // The essay has no headings: the server arranged it by itself, with no pane open on it. + await expect.poll(pageCalls).toBe(calls + 1); + const opened = await (await page.request.get(`/api/page/article?url=${encodeURIComponent(WEB.essay)}`)).json(); + expect(opened).toMatchObject({ cached: true, article: { outline: "model" } }); +}); + +test("a section whose whole text is an address becomes a section that is only the link, named after its page", async ({ page }) => { + const root = (await (await page.request.get("/api/tree")).json()).root as string; + const made = await page.request.post("/api/ops", { data: { author: "tester", message: "Add a holder", ops: [{ op: "create", parent: root, title: "Address holder", body: "" }, { op: "create", parent: "$0", title: "", body: "" }] } }); + expect(made.ok()).toBe(true); + const tree = await (await page.request.get("/api/tree")).json(); + const holder = Object.values(tree.nodes as Record).find((n) => n.title === "Address holder")!; + const id = holder.children[0]; + await visit(page, `/n/${encodeURIComponent(id)}`); + await page.waitForFunction(() => (globalThis as any).__ie?.ready); + await page.evaluate((i) => (globalThis as any).__ie.setFocus({ node: i, grain: "node" }), id); + await keys(page, "c"); + await page.keyboard.type(WEB.letters); + await page.keyboard.press("Escape"); + await expect.poll(() => state(page, (s) => s.snap.nodes[s.focus.node].title)).toBe("On maps"); + const n = await state(page, (s) => s.snap.nodes[s.focus.node]); + expect(n.id).toBe(id); + expect(n.body).toBe(""); + expect(n.ref).toEqual({ kind: "url", url: WEB.letters, title: "On maps" }); + expect(await state(page, (s) => s.linkOnly(s.focus.node))).toBe(true); +}); + +/** A page's title as the server keeps it. */ +async function titleOf(page: Page, url: string): Promise { + return (await (await page.request.get(`/api/page/summary?url=${encodeURIComponent(url)}&cached=1`)).json()).summary.title; +} diff --git a/e2e/helpers.ts b/e2e/helpers.ts index cfba0f9..0cd09de 100644 --- a/e2e/helpers.ts +++ b/e2e/helpers.ts @@ -7,7 +7,8 @@ * words, links on the screenshot's cells; the articles are the mock * Wikipedia's fixtures in server/wikiMock.ts). */ -import { writeFileSync } from "node:fs"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; import { inflateSync } from "node:zlib"; import { expect, type APIRequestContext, type Page } from "@playwright/test"; @@ -261,6 +262,10 @@ export async function seedLinks(request: APIRequestContext) { export const WEB = { tracing: "https://tracing.example.org/posts/following-a-request", essay: "https://essays.example.com/hundred.html", + /** Headingless, and the mock model fails to arrange it ("mockfail" in its title). */ + drift: "https://notes.example.net/field/unsorted", + /** Headingless, and the mock model takes 1.5 s to arrange it ("mockslow"). */ + slow: "https://tides.example.net/slow-water", letters: "https://letters.example.net/p/on-maps", rules: "https://software.example.com/2003/10/twelve-rules/", phare: "https://encyclopedie.example.org/fr/Phare_de_la_Pointe", @@ -299,6 +304,12 @@ export async function seedWeb(request: APIRequestContext) { if (!res.ok()) throw new Error(`seeding web links failed: ${res.status()} ${await res.text()}`); } +/** Model calls made today to arrange pages, as the e2e server counts them (/page-calls.json). */ +export function pageCalls(): number { + const file = join(process.env.EX_E2E_DATA ?? "", "page-calls.json"); + return existsSync(file) ? (JSON.parse(readFileSync(file, "utf8")) as { used: number }).used : 0; +} + /** A screenshot's pixels (a PNG of 8-bit RGB or RGBA, as Playwright writes them): px(x, y) is [r, g, b]. */ export function pixels(buf: Buffer): { w: number; h: number; px: (x: number, y: number) => [number, number, number] } { let at = 8; diff --git a/e2e/web.spec.ts b/e2e/web.spec.ts index 4a108cf..c044d24 100644 --- a/e2e/web.spec.ts +++ b/e2e/web.spec.ts @@ -4,15 +4,16 @@ * its sections as rows that open as panes, and where it is from at its foot; each outline the * server makes (headings, pseudo-headings, parts by length); a page that cannot be shown says why * and offers the original; figures come through the app's media route; a reload keeps the panes; - * a hostile page runs nothing and loads nothing from elsewhere; s has the mock model arrange a page - * and R reads one again; a link's card shows what the server's cache knows of its page, and the + * a hostile page runs nothing and loads nothing from elsewhere; a page with no headings is arranged + * by the mock model by itself, once (or says why not), s has it arrange or summarise one, and R + * reads one again; a link's card shows what the server's cache knows of its page, and the * link picker keeps an address's title; a section that is only a link is shown as its page or * article at once (its pane reads as the article's; in the column, under its row), and L opens a * section's target to the right of its pane. Nothing here touches the network: * the server's fetch is the mock's, and the browser's requests elsewhere are refused. */ import { expect, test, type Page } from "@playwright/test"; -import { WEB, command, jump, keys, noFaults, pane, seedLinks, seedWeb, settle, state, still, visit, wide } from "./helpers"; +import { WEB, command, jump, keys, noFaults, pageCalls, pane, seedLinks, seedWeb, settle, state, still, visit, wide } from "./helpers"; /** The panes' refs, left to right, as short names: a node's title, W:article, U:host/path#section. */ const trail = (page: Page) => @@ -109,7 +110,7 @@ test("panes: a link to a web page opens it in the next pane: its site, title and await keys(page, "Escape Escape"); }); -test("each outline the server makes: pseudo-headings, strong headings with a byline class, parts by length, junk sections left out", async ({ page }) => { +test("each outline the server makes: pseudo-headings, strong headings with a byline class, parts by length (arranged by a model by itself, or not), junk sections left out", async ({ page }) => { await wide(page, "Error-correcting codes"); await follow(page, WEB.letters); let web = page.locator(".wiki-pane.web").last(); @@ -124,11 +125,19 @@ test("each outline the server makes: pseudo-headings, strong headings with a byl await expect(web.locator(".web-byline")).toHaveText("Jo Calloway · Notes on Software · 9 Oct 2003"); await expect(web.locator(".wrow").first()).toContainText("1. Do you keep a list of bugs?"); + // No headings: divided by length, and arranged by the model by itself. No metadata at all: the byline is the site alone. await follow(page, WEB.essay); web = page.locator(".wiki-pane.web").last(); - await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "chunks"); - // No metadata at all: the byline is the site alone, and each part is named by its first words. await expect(web.locator(".web-byline")).toHaveText("essays.example.com"); + await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "model"); + await expect(web.locator(".web-auto")).toHaveCount(0); + + // One the model cannot arrange keeps its parts, each named by its first words, and says why in one quiet line. + await follow(page, WEB.drift); + web = page.locator(".wiki-pane.web").last(); + await expect(web.locator(".web-auto")).toHaveAttribute("data-auto", "skipped"); + await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "chunks"); + await expect(web.locator(".web-auto")).toHaveText(/^Kept in parts by length: The model call failed: .* s tries again\.$/); expect((await web.locator(".wrow > .row .title").allTextContents()).every((t) => t.endsWith("…"))).toBe(true); await expect(web.locator(".wiki > .wattr")).toContainText("divided into parts by length"); @@ -377,39 +386,54 @@ async function posted(page: Page, key: string, route: "arrange" | "reload"): Pro return (await res).json(); } -test("s: the model arranges a page divided by length; a pane on an old part closes; the summary is shown, labelled; a second s makes no call; a page with headings gains only the summary", async ({ page }) => { +test("a page with no headings is arranged by itself, once: “arranging…” meanwhile; a pane on a part by length closes when the sections arrive; the summary is shown, labelled; s then makes no call; a page with headings gains only the summary", async ({ page }) => { await wide(page, "Error-correcting codes"); - await follow(page, WEB.essay); + const calls = pageCalls(); + // The mock model takes 1.5 s over this page: it shows its parts by length meanwhile, and says so. + await follow(page, WEB.slow); const web = page.locator(".wiki-pane.web").last(); await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "chunks"); + await expect(web.locator(".web-auto")).toHaveText("Arranging into sections with a model…"); await expect(web.locator(".web-model")).toHaveCount(0); - // A part by length open as the next pane. + // A part by length open as the next pane, while the model works. await keys(page, "j l"); - expect((await trail(page)).at(-1)).toBe("U:essays.example.com/hundred.html#c1"); - const first = await posted(page, "s", "arrange"); - expect(first).toMatchObject({ ok: true, called: true, arranged: "sections" }); + expect((await trail(page)).at(-1)).toBe("U:tides.example.net/slow-water#c1"); + // The sections arrive: the page swaps to them, and the pane on the old part closes, the status line saying so. await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "model"); await expect(web.locator(".wrow > .row .title")).toHaveText(["Mock part one", "Mock part two", "Mock part three"]); - // The pane on the old part is closed, and the status line says so. - await expect(status(page)).toContainText("Arranged by the model into 3 sections"); - await expect(status(page)).toContainText("A pane on one of its old parts is closed."); - expect((await trail(page)).at(-1)).toBe("U:essays.example.com/hundred.html"); + await expect(web.locator(".web-auto")).toHaveCount(0); + await expect(status(page)).toContainText("A model has arranged this page into sections; the pane on one of its parts by length is closed."); + expect((await trail(page)).at(-1)).toBe("U:tides.example.net/slow-water"); + expect(pageCalls()).toBe(calls + 1); // The summary above the page's own opening, marked as the model's; the foot says what the model did. const summary = web.locator(".web-model"); await expect(summary.locator(".web-model-label")).toContainText("Summary written by a model (mock)"); - await expect(summary.locator(".web-model-text")).toContainText("Mock summary of “A Hundred Small Maps”"); - await expect(web.locator(".wiki > .wiki-text")).toContainText("A Hundred Small Maps"); + await expect(summary.locator(".web-model-text")).toContainText("Mock summary of “Slow water (mockslow)”"); await expect(web.locator(".web-arranged")).toContainText("Sections arranged by a model"); const foot = web.locator(".wiki > .wattr"); await expect(foot).toContainText("sections arranged by a model; summary written by a model"); await expect(foot).not.toContainText("divided into parts by length"); // A section of the model's opens as a pane like any other. await keys(page, "j l"); - expect((await trail(page)).at(-1)).toBe("U:essays.example.com/hundred.html#m1"); + expect((await trail(page)).at(-1)).toBe("U:tides.example.net/slow-water#m1"); await keys(page, "h"); - // Again: the kept result, no call. + // s: the kept result, no call. Opened again, or read again unchanged: no call either. expect(await posted(page, "s", "arrange")).toMatchObject({ ok: true, called: false, arranged: "sections" }); await expect(status(page)).toContainText("no new call"); + expect(await posted(page, "R", "reload")).toMatchObject({ ok: true, article: { outline: "model" } }); + await follow(page, WEB.letters); + await follow(page, WEB.slow); + await expect(page.locator(".wiki-pane.web").last().locator(".wiki")).toHaveAttribute("data-outline", "model"); + expect(pageCalls()).toBe(calls + 1); + + // One the model failed on, by itself: s tries again (a call), and says why it failed again. + await follow(page, WEB.drift); + const drift = page.locator(".wiki-pane.web").last(); + await expect(drift.locator(".web-auto")).toHaveAttribute("data-auto", "skipped"); + const before = pageCalls(); + expect(await posted(page, "s", "arrange")).toMatchObject({ ok: false, reason: "failed" }); + await expect(status(page)).toContainText("Not arranged: The model call failed"); + expect(pageCalls()).toBe(before + 1); // A page with headings of its own keeps them, and gains the summary only. await follow(page, WEB.tracing); @@ -429,6 +453,25 @@ test("s: the model arranges a page divided by length; a pane on an old part clos await page.keyboard.press("Escape"); }); +test("when the day's budget is spent, a page with no headings keeps its parts with one quiet line saying so, and s says it again", async ({ page }) => { + // The server's own refusal is tested in tests/pageArrange.test.ts; here the browser is given it, as + // a server with its budget spent would send it, so the shared server's budget is left alone. + const spent = "Today's 20 model calls for arranging pages are used up on this server (EX_PAGE_CALLS); it starts again tomorrow (UTC)."; + await page.route((u) => u.pathname === "/api/page/article" && u.searchParams.get("url") === WEB.drift, async (route) => { + const res = await route.fetch(); + const body = await res.json(); + await route.fulfill({ response: res, json: { ...body, article: { ...body.article, auto: { state: "skipped", reason: "budget", message: spent } } } }); + }); + await page.route((u) => u.pathname === "/api/page/arrange", (route) => route.fulfill({ status: 429, json: { ok: false, reason: "budget", message: spent } })); + await wide(page, "Error-correcting codes"); + await follow(page, WEB.drift); + const web = page.locator(".wiki-pane.web").last(); + await expect(web.locator(".web-auto")).toHaveText(`Kept in parts by length: ${spent} s tries again.`); + await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "chunks"); + expect(await posted(page, "s", "arrange")).toMatchObject({ ok: false, reason: "budget" }); + await expect(status(page)).toContainText(`Not arranged: ${spent}`); +}); + test("R reads a page again: unchanged text keeps the model's sections; a page that no longer answers keeps the copy read before, marked stale", async ({ page }) => { // The essay read and arranged (as the test before leaves it, when it ran). await page.request.get(`/api/page/article?url=${encodeURIComponent(WEB.essay)}`); diff --git a/server/index.ts b/server/index.ts index 25c7724..e5a1ef3 100644 --- a/server/index.ts +++ b/server/index.ts @@ -27,7 +27,7 @@ import { usage, withMockUsage } from "./usage"; import { HttpError, ROOT as root, abortOnClose, dataDir, readJson, sendJson as json } from "./util"; import { PageClient, pages } from "./page"; import { makeMockPageFetch } from "./pageMock"; -import { Arranger, serverBudget } from "./pageArrange"; +import { Arranger, arrangeMode, serverBudget } from "./pageArrange"; import { pageOff, pageRoutes } from "./pageRoutes"; import { applyWebPolicy, webConfig } from "./web"; import { WikiClient, validContact, wiki, wikiLang } from "./wiki"; @@ -109,12 +109,13 @@ const pageMode: PageMode = pagesWanted === "live" || pagesWanted === "mock" ? pa if (pageMode !== pagesWanted) console.warn(`EX_PAGES=${pagesWanted} is not live, mock or off; reading web pages is off.`); // The mock keeps its snapshots in memory only, so each run starts from nothing read. const mockPages = pageMode === "mock" ? new PageClient({ fetch: makeMockPageFetch(), spacingMs: 0, persist: false }) : null; -// Arranging a page with a model (s on a page) is always the reader's own request, through the -// shared model, within EX_PAGE_CALLS calls a day for the whole server (default 20, counted in -// /page-calls.json), and never while the plan's limits are nearly used. EX_PAGES_ARRANGE=off -// turns it off. -const arrangeOn = process.env.EX_PAGES_ARRANGE !== "off"; -const arranger = new Arranger({ pages: () => mockPages ?? pages(), llm: () => llm, on: arrangeOn, budget: serverBudget(process.env, DATA), plan: () => usage.summary().plan }); +// Arranging a page with a model: at the reader's request (s on a page), and by itself, once, for a +// page with no headings of its own (divided by length) when it is first read. Through the shared +// model, within EX_PAGE_CALLS calls a day for the whole server (default 20, counted in +// /page-calls.json), and never while the plan's limits are nearly used. +// EX_PAGES_ARRANGE=manual leaves it to s alone; EX_PAGES_ARRANGE=off turns it off. +const { on: arrangeOn, auto: arrangeAuto } = arrangeMode(process.env); +const arranger = new Arranger({ pages: () => mockPages ?? pages(), llm: () => llm, on: arrangeOn, auto: arrangeAuto, budget: serverBudget(process.env, DATA), plan: () => usage.summary().plan }); const handlePages = pageMode === "off" ? pageOff : pageRoutes(() => mockPages ?? pages(), () => arranger); /** A short reason for a failed model call, whichever provider made it. */ @@ -350,5 +351,5 @@ createServer(async (req, res) => { console.log( `wikipedia: ${wikiMode === "live" ? `live (${wikiState.lang}.wikipedia.org, ${wikiState.contact ? "with" : "without"} a contact)` : wikiMode === "mock" ? "mock (fixtures, no network)" : "off"}`, ); - console.log(`web pages: ${pageMode === "live" ? "live (only pages you open)" : pageMode === "mock" ? "mock (fixtures, no network)" : "off"}${pageMode !== "off" ? `; arranged by a model: ${arrangeOn && llm ? `on request, at most ${arranger.budgetMax} calls a day` : "off"}` : ""}`); + console.log(`web pages: ${pageMode === "live" ? "live (only pages you open)" : pageMode === "mock" ? "mock (fixtures, no network)" : "off"}${pageMode !== "off" ? `; arranged by a model: ${arrangeOn && llm ? `${arranger.automatic ? "pages without headings by themselves, and " : ""}on request, at most ${arranger.budgetMax} calls a day` : "off"}` : ""}`); }); diff --git a/server/page.ts b/server/page.ts index 42b74cf..5f7dd47 100644 --- a/server/page.ts +++ b/server/page.ts @@ -80,11 +80,19 @@ export interface WebArticle { words: number; attribution: WebAttribution; /** - * What a model added at the reader's request (POST /api/page/arrange), never the page's own + * What a model added (POST /api/page/arrange, or by itself: server/pageArrange.ts), never the page's own * words: a summary, and whether the sections are the model's (outline "model"). */ model?: { summary: string; sections: boolean; by?: string; at: string; note?: string }; + /** + * For a page divided by length that a model has not arranged: whether it is being arranged by + * itself now, or why it was not (server/pageArrange.ts `auto`). Added by the routes to the page + * they send; never kept in the snapshot. + */ + auto?: AutoArrange; } +/** A page divided by length, arranged by itself after it is read: under way, or why not (a refusal's reason and words). */ +export type AutoArrange = { state: "running" } | { state: "skipped"; reason: string; message: string }; export type WebUnusableReason = "robots" | "refused" | "type" | "empty" | "too-large" | "offline" | "error" | "off"; /** A page that is not shown: the reader is offered the original, with the reason in plain words. */ export interface WebUnusable { diff --git a/server/pageArrange.ts b/server/pageArrange.ts index 8a6572e..f45ee32 100644 --- a/server/pageArrange.ts +++ b/server/pageArrange.ts @@ -1,6 +1,7 @@ /** - * Arranging a web page with a model, at the reader's request (POST /api/page/arrange): a short - * summary, and for a page divided only by length, sections at the places the model chooses. See + * Arranging a web page with a model (POST /api/page/arrange): a short summary, and for a page + * divided only by length, sections at the places the model chooses. At the reader's request (s), and + * by itself once for a page divided by length when it is first read (`auto`, below). See * docs/pages.md §10 for why it is shaped as it is. * * What is sent: the page's title and the opening of each of its units, numbered (at most @@ -23,11 +24,19 @@ * the server's daily budget of calls (EX_PAGE_CALLS, default 20) is spent. One call per content hash * however many ask at once, and none for a page already arranged as it now reads. The call goes * through the server's shared model, so it is counted in the usage like every other. + * + * By itself (`auto`, started by the routes when a page is read or opened, or read for a link's + * title): only a page divided by length (outline "chunks"; a page with headings or pseudo-headings, + * one short enough to be a lead, and one that cannot be shown never are), not yet arranged as it + * now reads, with the same gate, the same call and the same flight as the reader's s, plus + * EX_PAGES_ARRANGE=manual, which leaves arranging to s alone. One attempt per content hash in a + * server's run: one refused or failed is not tried again by itself (s still may), so nothing loops; + * a Reload that changes the text gives it a new hash, and so one more attempt. */ import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import type { ArrangeReply, JsonReq, LLM } from "../src/llm/types"; -import type { ModelWork, PageClient, PageMaterial, WebArticle, WebSection } from "./page"; +import type { AutoArrange, ModelWork, PageClient, PageMaterial, WebArticle, WebSection } from "./page"; import { clipText, type PageUnit } from "./pageHtml"; import type { UsageSummary } from "./usage"; import { dataDir, writeAtomic } from "./util"; @@ -214,7 +223,7 @@ export class DailyBudget { // ---- the arranger ---- -export type ArrangeRefusal = "uncached" | "old" | "no-model" | "off" | "plan" | "budget" | "too-long" | "failed"; +export type ArrangeRefusal = "uncached" | "old" | "no-model" | "off" | "manual" | "plan" | "budget" | "too-long" | "failed" | "idle"; export type ArrangeResult = | { ok: true; @@ -233,11 +242,22 @@ export interface ArrangerOptions { llm: () => LLM | null; /** False when EX_PAGES_ARRANGE=off. */ on?: boolean; + /** False when EX_PAGES_ARRANGE=manual (or off): a page is arranged only at the reader's request. */ + auto?: boolean; budget: DailyBudget; /** The usage tracker's view of the plan (server/usage.ts summary().plan). */ plan?: () => UsageSummary["plan"]; } +/** What EX_PAGES_ARRANGE says: off (never), manual (at the reader's request only), anything else both that and by itself. */ +export function arrangeMode(env: NodeJS.ProcessEnv = process.env): { on: boolean; auto: boolean } { + const v = (env.EX_PAGES_ARRANGE ?? "").trim().toLowerCase(); + return { on: v !== "off", auto: v !== "off" && v !== "manual" }; +} + +/** Pages remembered as tried by themselves, at most (the oldest forgotten first). */ +const TRIED_MAX = 2000; + /** The budget the server keeps: EX_PAGE_CALLS calls a day, counted in /page-calls.json. */ export function serverBudget(env: NodeJS.ProcessEnv = process.env, dir = dataDir()): DailyBudget { const n = Number(env.EX_PAGE_CALLS); @@ -246,6 +266,8 @@ export function serverBudget(env: NodeJS.ProcessEnv = process.env, dir = dataDir export class Arranger { private flying = new Map>(); + /** Content hashes tried by themselves in this run: null while the call is made, else why it came to nothing. */ + private tried = new Map(); constructor(private o: ArrangerOptions) {} @@ -254,8 +276,18 @@ export class Arranger { return this.o.budget.max; } - /** Arrange (or summarise) a page already read here. Never reads the page; never throws. */ - async arrange(url: string): Promise { + /** Whether pages divided by length are arranged by themselves (a model, and EX_PAGES_ARRANGE neither off nor manual). */ + get automatic(): boolean { + return this.o.on !== false && this.o.auto !== false && !!this.o.llm(); + } + + /** + * Arrange (or summarise) a page already read here. Never reads the page; never throws. `join`: + * only wait for an arrangement already under way (or answer with the one kept, or why the + * automatic attempt came to nothing), never start a call: what the browser asks while a page + * is being arranged by itself, so that asking can never spend a call. + */ + async arrange(url: string, o: { join?: boolean } = {}): Promise { const m = this.o.pages().material(url); if (!m) return { ok: false, reason: "uncached", message: "Only a page already read here can be arranged: open it first." }; const done = this.kept(m); @@ -263,6 +295,10 @@ export class Arranger { // One call per content hash, however many ask. const k = m.article.hash; let p = this.flying.get(k); + if (!p && o.join) { + const was = this.tried.get(k); + return { ok: false, ...(was ?? { reason: "idle", message: "This page is not being arranged now: s arranges it." }) }; + } if (!p) { p = this.call(url, m).finally(() => this.flying.delete(k)); this.flying.set(k, p); @@ -270,16 +306,50 @@ export class Arranger { return p; } + /** + * Arrange a page by itself, after it was read or opened: only a page divided by length, not yet + * arranged as it now reads, and not tried by itself before in this run. Starts the call (the same + * one s makes, in the same flight) and does not wait for it. Returns where that stands for the + * page as now kept: under way, or why it is not done; undefined when there is nothing to say (a + * page with sections of its own, one already arranged, one not kept here). Never throws. + */ + auto(url: string): AutoArrange | undefined { + const m = this.o.pages().material(url); + if (!m || m.article.outline !== "chunks" || this.kept(m)) return undefined; + const k = m.article.hash; + if (this.flying.has(k)) return { state: "running" }; + const was = this.tried.get(k); + if (was) return { state: "skipped", ...was }; + if (was === null) return undefined; // tried, and kept or gone since + // Refusals that hold for the whole run are not attempts: they are said each time, never remembered. + const always = this.refusal(true); + if (always && (always.reason === "no-model" || always.reason === "off" || always.reason === "manual")) return { state: "skipped", ...always }; + const now = always ?? (m.units ? null : { reason: "old" as const, message: "This copy of the page was read before pages could be arranged: R reads it again, and it is arranged then." }); + this.remember(k, now); + if (now) return { state: "skipped", ...now }; + void this.arrange(url).then((r) => { + if (!r.ok) this.remember(k, { reason: r.reason, message: r.message }); + }); + return { state: "running" }; + } + + private remember(k: string, v: { reason: ArrangeRefusal; message: string } | null) { + this.tried.delete(k); + this.tried.set(k, v); + if (this.tried.size > TRIED_MAX) this.tried.delete(this.tried.keys().next().value as string); + } + /** The result kept for the page as it now reads, if there is one. */ private kept(m: PageMaterial): ArrangeResult | null { if (m.model?.hash !== m.article.hash) return null; return { ok: true, article: m.view, called: false, arranged: m.model.sections ? "sections" : "summary", ...(m.model.note ? { note: m.model.note } : {}) }; } - /** Why no call may be made now, or null. */ - private refusal(): { reason: ArrangeRefusal; message: string } | null { + /** Why no call may be made now, or null. `auto`: for an attempt by itself, which EX_PAGES_ARRANGE=manual refuses too. */ + private refusal(auto = false): { reason: ArrangeRefusal; message: string } | null { if (!this.o.llm()) return { reason: "no-model", message: "No model is configured on this server, so pages cannot be arranged." }; if (this.o.on === false) return { reason: "off", message: "Arranging pages with a model is turned off on this server (EX_PAGES_ARRANGE=off)." }; + if (auto && this.o.auto === false) return { reason: "manual", message: "This server arranges pages only when asked (EX_PAGES_ARRANGE=manual)." }; const plan = this.o.plan?.(); if (plan?.limited) return { reason: "plan", message: `The plan is refusing requests now${plan.limitLabel ? ` (its ${plan.limitLabel} limit)` : ""}${plan.limitResetsAt ? `, until ${plan.limitResetsAt.slice(0, 16).replace("T", " ")} UTC` : ""}; pages are not arranged until it lifts.` }; if (plan?.warning) return { reason: "plan", message: `The plan's limits are nearly used${plan.remainingPercent !== null ? ` (${plan.remainingPercent}% left)` : ""}; pages are not arranged until they reset, so the calls are kept for writing.` }; diff --git a/server/pageMock.ts b/server/pageMock.ts index 2199e25..f54bf4c 100644 --- a/server/pageMock.ts +++ b/server/pageMock.ts @@ -6,6 +6,10 @@ * * tracing a blog post whose sections are all h3, with and a