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

+24 -8
View File
@@ -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_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_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` | `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_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, 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_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_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_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. | | `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 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 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). 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 - A page with **no headings** of its own is first shown divided by length, and the model is asked
summary, shown above the page's opening and marked as the model's, and, for a page with no once, by itself, for sections of its choosing and a short summary (within `EX_PAGE_CALLS` calls a
headings that was divided by length, for sections of its choosing; a page with headings keeps day, never while the plan's limits are nearly used; `EX_PAGES_ARRANGE=manual` leaves it to `s`).
them. Pressed again on the same text it costs nothing. `R` reads the page again (it is otherwise 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 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 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 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 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. 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 - 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. 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 - 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. 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/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) | | `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: <why>` when it no longer answers | | `POST /api/page/reload` `{ url }` | read the page again: the new copy, or the last one with `stale: <why>` 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/<id>/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 | | `POST /api/l/<id>/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/<id>/links/pending?node=<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 | | `GET /api/l/<id>/links/pending?node=<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/<id>/links/accept` / `reject` `{ ids, author? }` | link them in one commit, or record them as declined | | `POST /api/l/<id>/links/accept` / `reject` `{ ids, author? }` | link them in one commit, or record them as declined |
+66 -8
View File
@@ -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 | `<strong>N.` | byline class | meta | pseudo-headings | | 16 | WordPress | joelonsoftware.com | 200 | 3,675 | `<strong>N.` | byline class | meta | pseudo-headings |
| 17 | hand-written | norvig.com | 200 | 2,753 | 9 h2 | layout only → none | none | 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: 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/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 | | `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: <why>` when it no longer answers; a page never shown that still cannot be is a 422 or 503 `WebUnusable` | | `POST /api/page/reload` `{ url }` | the page read again: 200 `{ ok, article }`, or the last copy with `stale: <why>` 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 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 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, 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 `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 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 ## 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 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 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. 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) ## 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 A page with no headings is divided by length (§4), which is honest but blind. A model writes a
request (`s` on a page, or "Arrange with a model" in its menu; `POST /api/page/arrange`), a model short summary of the page and, for a page divided by length, chooses where its sections begin: by
writes a short summary of the page and, for a page divided by length, chooses where its sections itself, once, for a page divided by length when it is first read (below), and on the reader's
begin. Never on opening, never in the background. 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 - **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 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. 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`) - **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 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; - **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/ `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 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; 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 a page already arranged for the text it now has answers from its snapshot without a call (the
status line says "no new call"). 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: <why> 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) ## 11. Videos (and what loads when)
+111
View File
@@ -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<string, { title: string; children: string[] }>).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<string> {
return (await (await page.request.get(`/api/page/summary?url=${encodeURIComponent(url)}&cached=1`)).json()).summary.title;
}
+12 -1
View File
@@ -7,7 +7,8 @@
* words, links on the screenshot's cells; the articles are the mock * words, links on the screenshot's cells; the articles are the mock
* Wikipedia's fixtures in server/wikiMock.ts). * 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 { inflateSync } from "node:zlib";
import { expect, type APIRequestContext, type Page } from "@playwright/test"; import { expect, type APIRequestContext, type Page } from "@playwright/test";
@@ -261,6 +262,10 @@ export async function seedLinks(request: APIRequestContext) {
export const WEB = { export const WEB = {
tracing: "https://tracing.example.org/posts/following-a-request", tracing: "https://tracing.example.org/posts/following-a-request",
essay: "https://essays.example.com/hundred.html", 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", letters: "https://letters.example.net/p/on-maps",
rules: "https://software.example.com/2003/10/twelve-rules/", rules: "https://software.example.com/2003/10/twelve-rules/",
phare: "https://encyclopedie.example.org/fr/Phare_de_la_Pointe", 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()}`); 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 (<EX_DATA>/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]. */ /** 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] } { export function pixels(buf: Buffer): { w: number; h: number; px: (x: number, y: number) => [number, number, number] } {
let at = 8; let at = 8;
+63 -20
View File
@@ -4,15 +4,16 @@
* its sections as rows that open as panes, and where it is from at its foot; each outline the * 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 * 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; * 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 * a hostile page runs nothing and loads nothing from elsewhere; a page with no headings is arranged
* and R reads one again; a link's card shows what the server's cache knows of its page, and the * 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 * 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 * 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: * 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. * 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 { 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. */ /** The panes' refs, left to right, as short names: a node's title, W:article, U:host/path#section. */
const trail = (page: Page) => 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"); 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 wide(page, "Error-correcting codes");
await follow(page, WEB.letters); await follow(page, WEB.letters);
let web = page.locator(".wiki-pane.web").last(); 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(".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?"); 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); await follow(page, WEB.essay);
web = page.locator(".wiki-pane.web").last(); 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(".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); 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"); 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(); 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 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(); const web = page.locator(".wiki-pane.web").last();
await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "chunks"); 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); 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"); await keys(page, "j l");
expect((await trail(page)).at(-1)).toBe("U:essays.example.com/hundred.html#c1"); expect((await trail(page)).at(-1)).toBe("U:tides.example.net/slow-water#c1");
const first = await posted(page, "s", "arrange"); // The sections arrive: the page swaps to them, and the pane on the old part closes, the status line saying so.
expect(first).toMatchObject({ ok: true, called: true, arranged: "sections" });
await expect(web.locator(".wiki")).toHaveAttribute("data-outline", "model"); 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"]); 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(web.locator(".web-auto")).toHaveCount(0);
await expect(status(page)).toContainText("Arranged by the model into 3 sections"); await expect(status(page)).toContainText("A model has arranged this page into sections; the pane on one of its parts by length is closed.");
await expect(status(page)).toContainText("A pane on one of its old parts is closed."); expect((await trail(page)).at(-1)).toBe("U:tides.example.net/slow-water");
expect((await trail(page)).at(-1)).toBe("U:essays.example.com/hundred.html"); 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. // 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"); 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-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(summary.locator(".web-model-text")).toContainText("Mock summary of “Slow water (mockslow)”");
await expect(web.locator(".wiki > .wiki-text")).toContainText("A Hundred Small Maps");
await expect(web.locator(".web-arranged")).toContainText("Sections arranged by a model"); await expect(web.locator(".web-arranged")).toContainText("Sections arranged by a model");
const foot = web.locator(".wiki > .wattr"); const foot = web.locator(".wiki > .wattr");
await expect(foot).toContainText("sections arranged by a model; summary written by a model"); await expect(foot).toContainText("sections arranged by a model; summary written by a model");
await expect(foot).not.toContainText("divided into parts by length"); await expect(foot).not.toContainText("divided into parts by length");
// A section of the model's opens as a pane like any other. // A section of the model's opens as a pane like any other.
await keys(page, "j l"); 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"); 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" }); expect(await posted(page, "s", "arrange")).toMatchObject({ ok: true, called: false, arranged: "sections" });
await expect(status(page)).toContainText("no new call"); 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. // A page with headings of its own keeps them, and gains the summary only.
await follow(page, WEB.tracing); 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"); 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 }) => { 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). // 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)}`); await page.request.get(`/api/page/article?url=${encodeURIComponent(WEB.essay)}`);
+9 -8
View File
@@ -27,7 +27,7 @@ import { usage, withMockUsage } from "./usage";
import { HttpError, ROOT as root, abortOnClose, dataDir, readJson, sendJson as json } from "./util"; import { HttpError, ROOT as root, abortOnClose, dataDir, readJson, sendJson as json } from "./util";
import { PageClient, pages } from "./page"; import { PageClient, pages } from "./page";
import { makeMockPageFetch } from "./pageMock"; import { makeMockPageFetch } from "./pageMock";
import { Arranger, serverBudget } from "./pageArrange"; import { Arranger, arrangeMode, serverBudget } from "./pageArrange";
import { pageOff, pageRoutes } from "./pageRoutes"; import { pageOff, pageRoutes } from "./pageRoutes";
import { applyWebPolicy, webConfig } from "./web"; import { applyWebPolicy, webConfig } from "./web";
import { WikiClient, validContact, wiki, wikiLang } from "./wiki"; 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.`); 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. // 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; 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 // Arranging a page with a model: at the reader's request (s on a page), and by itself, once, for a
// shared model, within EX_PAGE_CALLS calls a day for the whole server (default 20, counted in // page with no headings of its own (divided by length) when it is first read. Through the shared
// <EX_DATA>/page-calls.json), and never while the plan's limits are nearly used. EX_PAGES_ARRANGE=off // model, within EX_PAGE_CALLS calls a day for the whole server (default 20, counted in
// turns it off. // <EX_DATA>/page-calls.json), and never while the plan's limits are nearly used.
const arrangeOn = process.env.EX_PAGES_ARRANGE !== "off"; // EX_PAGES_ARRANGE=manual leaves it to s alone; EX_PAGES_ARRANGE=off turns it off.
const arranger = new Arranger({ pages: () => mockPages ?? pages(), llm: () => llm, on: arrangeOn, budget: serverBudget(process.env, DATA), plan: () => usage.summary().plan }); 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); const handlePages = pageMode === "off" ? pageOff : pageRoutes(() => mockPages ?? pages(), () => arranger);
/** A short reason for a failed model call, whichever provider made it. */ /** A short reason for a failed model call, whichever provider made it. */
@@ -350,5 +351,5 @@ createServer(async (req, res) => {
console.log( console.log(
`wikipedia: ${wikiMode === "live" ? `live (${wikiState.lang}.wikipedia.org, ${wikiState.contact ? "with" : "without"} a contact)` : wikiMode === "mock" ? "mock (fixtures, no network)" : "off"}`, `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"}` : ""}`);
}); });
+9 -1
View File
@@ -80,11 +80,19 @@ export interface WebArticle {
words: number; words: number;
attribution: WebAttribution; 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"). * words: a summary, and whether the sections are the model's (outline "model").
*/ */
model?: { summary: string; sections: boolean; by?: string; at: string; note?: string }; 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"; 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. */ /** A page that is not shown: the reader is offered the original, with the reason in plain words. */
export interface WebUnusable { export interface WebUnusable {
+78 -8
View File
@@ -1,6 +1,7 @@
/** /**
* Arranging a web page with a model, at the reader's request (POST /api/page/arrange): a short * Arranging a web page with a model (POST /api/page/arrange): a short summary, and for a page
* summary, and for a page divided only by length, sections at the places the model chooses. See * 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. * 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 * 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 * 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 * 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. * 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 { existsSync, readFileSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
import type { ArrangeReply, JsonReq, LLM } from "../src/llm/types"; 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 { clipText, type PageUnit } from "./pageHtml";
import type { UsageSummary } from "./usage"; import type { UsageSummary } from "./usage";
import { dataDir, writeAtomic } from "./util"; import { dataDir, writeAtomic } from "./util";
@@ -214,7 +223,7 @@ export class DailyBudget {
// ---- the arranger ---- // ---- 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 = export type ArrangeResult =
| { | {
ok: true; ok: true;
@@ -233,11 +242,22 @@ export interface ArrangerOptions {
llm: () => LLM | null; llm: () => LLM | null;
/** False when EX_PAGES_ARRANGE=off. */ /** False when EX_PAGES_ARRANGE=off. */
on?: boolean; on?: boolean;
/** False when EX_PAGES_ARRANGE=manual (or off): a page is arranged only at the reader's request. */
auto?: boolean;
budget: DailyBudget; budget: DailyBudget;
/** The usage tracker's view of the plan (server/usage.ts summary().plan). */ /** The usage tracker's view of the plan (server/usage.ts summary().plan). */
plan?: () => UsageSummary["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 <EX_DATA>/page-calls.json. */ /** The budget the server keeps: EX_PAGE_CALLS calls a day, counted in <EX_DATA>/page-calls.json. */
export function serverBudget(env: NodeJS.ProcessEnv = process.env, dir = dataDir()): DailyBudget { export function serverBudget(env: NodeJS.ProcessEnv = process.env, dir = dataDir()): DailyBudget {
const n = Number(env.EX_PAGE_CALLS); const n = Number(env.EX_PAGE_CALLS);
@@ -246,6 +266,8 @@ export function serverBudget(env: NodeJS.ProcessEnv = process.env, dir = dataDir
export class Arranger { export class Arranger {
private flying = new Map<string, Promise<ArrangeResult>>(); private flying = new Map<string, Promise<ArrangeResult>>();
/** Content hashes tried by themselves in this run: null while the call is made, else why it came to nothing. */
private tried = new Map<string, { reason: ArrangeRefusal; message: string } | null>();
constructor(private o: ArrangerOptions) {} constructor(private o: ArrangerOptions) {}
@@ -254,8 +276,18 @@ export class Arranger {
return this.o.budget.max; return this.o.budget.max;
} }
/** Arrange (or summarise) a page already read here. Never reads the page; never throws. */ /** Whether pages divided by length are arranged by themselves (a model, and EX_PAGES_ARRANGE neither off nor manual). */
async arrange(url: string): Promise<ArrangeResult> { 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<ArrangeResult> {
const m = this.o.pages().material(url); 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." }; 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); const done = this.kept(m);
@@ -263,6 +295,10 @@ export class Arranger {
// One call per content hash, however many ask. // One call per content hash, however many ask.
const k = m.article.hash; const k = m.article.hash;
let p = this.flying.get(k); 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) { if (!p) {
p = this.call(url, m).finally(() => this.flying.delete(k)); p = this.call(url, m).finally(() => this.flying.delete(k));
this.flying.set(k, p); this.flying.set(k, p);
@@ -270,16 +306,50 @@ export class Arranger {
return p; 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. */ /** The result kept for the page as it now reads, if there is one. */
private kept(m: PageMaterial): ArrangeResult | null { private kept(m: PageMaterial): ArrangeResult | null {
if (m.model?.hash !== m.article.hash) return 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 } : {}) }; 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. */ /** Why no call may be made now, or null. `auto`: for an attempt by itself, which EX_PAGES_ARRANGE=manual refuses too. */
private refusal(): { reason: ArrangeRefusal; message: string } | null { 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.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 (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?.(); 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?.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.` }; 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.` };
+14
View File
@@ -6,6 +6,10 @@
* *
* tracing a blog post whose sections are all h3, with <meta name=author> and a <time> * tracing a blog post whose sections are all h3, with <meta name=author> and a <time>
* essay a long headingless essay in a layout table, paragraphs made of <br><br>, no metadata * essay a long headingless essay in a layout table, paragraphs made of <br><br>, no metadata
* drift a headingless page of plain paragraphs whose title says "mockfail": the mock model
* fails to arrange it (an automatic attempt that comes to nothing, then s)
* slow a headingless page whose title says "mockslow": the mock model takes 1.5 s over it
* (the "arranging…" line, and a pane on a part by length when the sections arrive)
* letters sections opened by <p>I.</p>, <p>II.</p>…, author and date in JSON-LD * letters sections opened by <p>I.</p>, <p>II.</p>…, author and date in JSON-LD
* rules <p><strong>1. …</strong></p> sections, a sidebar full of h2s, a byline class * rules <p><strong>1. …</strong></p> sections, a sidebar full of h2s, a byline class
* phare French, h2 and h3 sections, with junk ones (Sommaire, Voir aussi, Notes et références) * phare French, h2 and h3 sections, with junk ones (Sommaire, Voir aussi, Notes et références)
@@ -36,6 +40,8 @@
export const MOCK_PAGES = { export const MOCK_PAGES = {
tracing: "https://tracing.example.org/posts/following-a-request", tracing: "https://tracing.example.org/posts/following-a-request",
essay: "https://essays.example.com/hundred.html", essay: "https://essays.example.com/hundred.html",
drift: "https://notes.example.net/field/unsorted",
slow: "https://tides.example.net/slow-water",
letters: "https://letters.example.net/p/on-maps", letters: "https://letters.example.net/p/on-maps",
rules: "https://software.example.com/2003/10/twelve-rules/", rules: "https://software.example.com/2003/10/twelve-rules/",
phare: "https://encyclopedie.example.org/fr/Phare_de_la_Pointe", phare: "https://encyclopedie.example.org/fr/Phare_de_la_Pointe",
@@ -130,6 +136,12 @@ const tracing = page(
</article></main>${FOOTER}`, </article></main>${FOOTER}`,
); );
/** A page of plain paragraphs and nothing else: no headings, no metadata but its title. */
const headingless = (title: string, from: number) =>
page(`<title>${title}</title>`, `<article>${Array.from({ length: 12 }, (_, i) => `<p>${prose(125, from + i * 2)}</p>`).join("")}</article>`);
const drift = headingless("Field notes, unsorted (mockfail)", 3);
const slow = headingless("Slow water (mockslow)", 7);
const essayParas = Array.from({ length: 14 }, (_, i) => prose(120 + (i % 3) * 15, i * 2)); const essayParas = Array.from({ length: 14 }, (_, i) => prose(120 + (i % 3) * 15, i * 2));
const essay = `<html><head><title>A Hundred Small Maps</title></head><body bgcolor="#ffffff"> const essay = `<html><head><title>A Hundred Small Maps</title></head><body bgcolor="#ffffff">
<table border="0" cellspacing="0" cellpadding="0"><tr valign="top"><td><img src="/nav.gif" width="69" height="357" alt=""></td><td width="26"></td> <table border="0" cellspacing="0" cellpadding="0"><tr valign="top"><td><img src="/nav.gif" width="69" height="357" alt=""></td><td width="26"></td>
@@ -290,6 +302,8 @@ const redirect = (to: string, status = 302) => new Response(null, { status, head
const PAGES: Record<string, () => Response> = { const PAGES: Record<string, () => Response> = {
[MOCK_PAGES.tracing]: () => html(tracing), [MOCK_PAGES.tracing]: () => html(tracing),
[MOCK_PAGES.essay]: () => html(essay, 200, { "content-type": "text/html" }), [MOCK_PAGES.essay]: () => html(essay, 200, { "content-type": "text/html" }),
[MOCK_PAGES.drift]: () => html(drift),
[MOCK_PAGES.slow]: () => html(slow),
[MOCK_PAGES.letters]: () => html(letters), [MOCK_PAGES.letters]: () => html(letters),
[MOCK_PAGES.rules]: () => html(rules, 200, { "last-modified": "Tue, 01 Nov 2022 10:00:00 GMT" }), [MOCK_PAGES.rules]: () => html(rules, 200, { "last-modified": "Tue, 01 Nov 2022 10:00:00 GMT" }),
[MOCK_PAGES.phare]: () => html(phare), [MOCK_PAGES.phare]: () => html(phare),
+30 -10
View File
@@ -5,7 +5,7 @@
* GET /api/page/summary?url=https://…[&cached=1] title, site, author, date, first sentence * GET /api/page/summary?url=https://…[&cached=1] title, site, author, date, first sentence
* GET /api/page/media?u=https://… an image a page read here shows * GET /api/page/media?u=https://… an image a page read here shows
* POST /api/page/reload { url } read the page again (the reader's Reload) * POST /api/page/reload { url } read the page again (the reader's Reload)
* POST /api/page/arrange { url } summarise it with a model, and arrange a page * POST /api/page/arrange { url[, auto: true] } summarise it with a model, and arrange a page
* divided by length into sections (pageArrange.ts) * divided by length into sections (pageArrange.ts)
* *
* summary &cached=1 answers from the snapshot cache only, never reading the page: 404 * summary &cached=1 answers from the snapshot cache only, never reading the page: 404
@@ -27,12 +27,18 @@
* arranging existed), 422 too-long, 429 budget or plan, 502 failed (the call failed), 503 no-model * arranging existed), 422 too-long, 429 budget or plan, 502 failed (the call failed), 503 no-model
* or off (EX_PAGES_ARRANGE=off). * or off (EX_PAGES_ARRANGE=off).
* *
* Arranging by itself: article, reload and summary (not &cached=1) start it for a page divided by
* length that a model has not arranged (Arranger.auto), and article and reload send where it stands
* in the page's `auto`: { state: "running" } or { state: "skipped", reason, message }. While it runs
* the browser asks arrange with `auto: true`, which only waits for the call under way (or answers
* with what it came to: 409 idle when nothing is under way) and never starts one.
*
* Every route refuses a request another site's page makes (Sec-Fetch-Site, else Origin, against * Every route refuses a request another site's page makes (Sec-Fetch-Site, else Origin, against
* the request's own Host). Requests with neither header (curl, the tests) are allowed. The two * the request's own Host). Requests with neither header (curl, the tests) are allowed. The two
* that act (reload reads a site, arrange spends model budget) are POST only; the others GET only. * that act (reload reads a site, arrange spends model budget) are POST only; the others GET only.
*/ */
import type { IncomingMessage, ServerResponse } from "node:http"; import type { IncomingMessage, ServerResponse } from "node:http";
import type { MediaResult, PageClient, PageResult, WebUnusable } from "./page"; import type { MediaResult, PageClient, PageResult, WebArticle, WebUnusable } from "./page";
import type { ArrangeRefusal, Arranger } from "./pageArrange"; import type { ArrangeRefusal, Arranger } from "./pageArrange";
import { HttpError, abortOnClose, readJson, sendJson as send } from "./util"; import { HttpError, abortOnClose, readJson, sendJson as send } from "./util";
import type { Uncached } from "./wiki"; import type { Uncached } from "./wiki";
@@ -94,7 +100,7 @@ export function sendMedia(res: ServerResponse, r: MediaResult | { ok: false; rea
/** The routes that act, and are POST only; the rest are GET only. */ /** The routes that act, and are POST only; the rest are GET only. */
const POSTS = new Set(["reload", "arrange"]); const POSTS = new Set(["reload", "arrange"]);
const REFUSED: Record<ArrangeRefusal, number> = { uncached: 404, old: 409, "too-long": 422, budget: 429, plan: 429, failed: 502, "no-model": 503, off: 503 }; const REFUSED: Record<ArrangeRefusal, number> = { uncached: 404, old: 409, idle: 409, "too-long": 422, budget: 429, plan: 429, failed: 502, "no-model": 503, off: 503, manual: 503 };
function reply<V>(res: ServerResponse, r: PageResult<V> | Uncached | { ok: false; reason: "aborted" }, key: string) { function reply<V>(res: ServerResponse, r: PageResult<V> | Uncached | { ok: false; reason: "aborted" }, key: string) {
if (r.ok) return send(res, 200, { ok: true, cached: r.cached, [key]: r.value }); if (r.ok) return send(res, 200, { ok: true, cached: r.cached, [key]: r.value });
@@ -118,36 +124,50 @@ export function pageRoutes(client: () => PageClient, arranger?: () => Arranger)
send(res, 405, { ok: false, message: `use ${method}` }, { allow: method }); send(res, 405, { ok: false, message: `use ${method}` }, { allow: method });
return true; return true;
} }
// A page read or opened: arranged by itself if it is divided by length (never throws, never waits).
const auto = (u: string) => arranger?.().auto(u);
const withAuto = <R extends { ok: true; value: WebArticle }>(u: string, r: R): R => {
const a = auto(u);
return a ? { ...r, value: { ...r.value, auto: a } } : r;
};
try { try {
const p = client(); const p = client();
const signal = abortOnClose(res); const signal = abortOnClose(res);
switch (route) { switch (route) {
case "reload": { case "reload": {
const body = await readJson<{ url?: unknown }>(req, 16 * 1024); const body = await readJson<{ url?: unknown }>(req, 16 * 1024);
const r = await p.reload(checked(body.url, "url"), { signal }); const u = checked(body.url, "url");
if (r.ok) send(res, 200, { ok: true, cached: false, article: r.value, ...(r.stale ? { stale: r.stale } : {}) }); const r = await p.reload(u, { signal });
if (r.ok) send(res, 200, { ok: true, cached: false, article: withAuto(u, r).value, ...(r.stale ? { stale: r.stale } : {}) });
else reply(res, r, "article"); else reply(res, r, "article");
return true; return true;
} }
case "arrange": { case "arrange": {
const body = await readJson<{ url?: unknown }>(req, 16 * 1024); const body = await readJson<{ url?: unknown; auto?: unknown }>(req, 16 * 1024);
const u = checked(body.url, "url"); const u = checked(body.url, "url");
if (!arranger) { if (!arranger) {
send(res, 503, { ok: false, reason: "off", message: "Arranging pages with a model is not available on this server." }); send(res, 503, { ok: false, reason: "off", message: "Arranging pages with a model is not available on this server." });
return true; return true;
} }
// Not abandoned when the browser goes: the call is made once, and its result kept for the next ask. // Not abandoned when the browser goes: the call is made once, and its result kept for the next ask.
const r = await arranger().arrange(u); const r = await arranger().arrange(u, { join: body.auto === true });
if (r.ok) send(res, 200, r); if (r.ok) send(res, 200, r);
else send(res, REFUSED[r.reason], r); else send(res, REFUSED[r.reason], r);
return true; return true;
} }
case "article": case "article": {
reply(res, await p.article(address(url, "url"), { signal }), "article"); const u = address(url, "url");
const r = await p.article(u, { signal });
reply(res, r.ok ? withAuto(u, r) : r, "article");
return true; return true;
}
case "summary": { case "summary": {
const u = address(url, "url"); const u = address(url, "url");
reply(res, await p.summary(u, { signal, cacheOnly: url.searchParams.get("cached") === "1" }), "summary"); const cacheOnly = url.searchParams.get("cached") === "1";
const r = await p.summary(u, { signal, cacheOnly });
// Read for a link's title (not a card's look at the cache): arranged by itself as when opened.
if (r.ok && !cacheOnly) auto(u);
reply(res, r, "summary");
return true; return true;
} }
case "media": case "media":
+198
View File
@@ -0,0 +1,198 @@
/**
* Bare web addresses typed into a node's text, made into titled links (Store.commitEdit, once an
* edit of a node's text is finished, never while typing). Three steps, each one commit of its own
* that undo takes back on its own:
*
* 1. linkAddresses: each http(s) address new in this edit (not in the text before it, not inside
* a code span or words already linked, not declined in the node's `nolink`) is linked as typed,
* as selecting it and using w would: a page's address to the page, a Wikipedia article's
* address to the article (wikiRefOf). A section whose whole text is one such address, with no
* target and no sections, becomes a section that is only that link (its text cleared,
* model.ts linkOnly), and so opens straight as the page.
* 2. The caller reads each page's title (the article's title is in its address).
* 3. titleLink: the address in the text is replaced by the title, the link's words with it, only
* while those words are still the address exactly as typed (a concurrent edit of them, here or
* on another replica, drops this step). titleWhole names a section made a link in step 1 by
* its page, only while its title is empty or a placeholder.
*
* Undoing step 3 brings the address back, still linked; it is then in the text before any later
* edit, so it is never taken for new and converted again.
*/
import { applyLinks, phraseKey } from "./links";
import { isLibraryRoot, label, notesOf, retitleOps, sections, type Doc, type NodeId, type Op } from "./model";
import { describeTarget, sameTarget, validateRef, wikiRefOf, type Ref } from "./ref";
import { clip, overlaps, type Range } from "./text";
/** An address in a text, where it is. */
export interface Bare {
range: Range;
url: string;
}
/** Addresses longer than this are left alone (the server reads none longer). */
const MAX_URL = 2000;
/** A start of an address: not in the middle of a word or of another address. */
const ADDRESS = /(?<![\w@/.:-])https?:\/\/[^\s<>"`]+/gi;
/** What may end a sentence after an address and is not part of it. */
const TRAILING = /[.,;:!?'"’”*_…]/;
/** The code spans of a text: fenced blocks and `inline` spans. */
function codeSpans(text: string): Range[] {
const out: Range[] = [];
for (const m of text.matchAll(/```[\s\S]*?(```|$)|`[^`\n]*`/g)) out.push([m.index!, m.index! + m[0].length]);
return out;
}
const count = (s: string, c: string) => s.split(c).length - 1;
/**
* The bare http(s) addresses in a text, in order: trailing punctuation left out (a closing bracket
* only when it does not close one opened inside the address), none inside a code span, and only
* what reads as an address (a host with a dot in it).
*/
export function bareAddresses(text: string): Bare[] {
const code = codeSpans(text);
const out: Bare[] = [];
for (const m of text.matchAll(ADDRESS)) {
let url = m[0];
for (;;) {
const last = url[url.length - 1];
if (TRAILING.test(last)) url = url.slice(0, -1);
else if (last === ")" && count(url, ")") > count(url, "(")) url = url.slice(0, -1);
else if (last === "]" && count(url, "]") > count(url, "[")) url = url.slice(0, -1);
else break;
}
const range: Range = [m.index!, m.index! + url.length];
if (url.length > MAX_URL || code.some((c) => overlaps(c, range))) continue;
try {
const x = new URL(url);
if (!/^https?:$/.test(x.protocol) || !x.hostname.includes(".") || x.hostname.endsWith(".")) continue;
} catch {
continue;
}
out.push({ range, url });
}
return out;
}
/** The addresses of `now` that `before` did not have (an address already in the text before the edit is never new). */
export function newAddresses(before: string, now: string): Bare[] {
const had = new Set(bareAddresses(before).map((b) => b.url));
return bareAddresses(now).filter((b) => !had.has(b.url));
}
/** What an address links to: a Wikipedia article's address is the article; any other, the page. */
export function addressTarget(url: string): Ref {
return wikiRefOf(url) ?? validateRef({ kind: "url", url });
}
/** Whether a title says nothing yet: empty, a stand-in, or the address itself. */
export function placeholderTitle(title: string, url: string): boolean {
const t = title.trim();
return !t || t === url || /^\(?(untitled|new section|section)\)?$/i.test(t);
}
/** A title as words in a node's text: one line, and nothing the text would read as markup. */
export const titleWords = (title: string) =>
title
.replace(/[`*]|\[\[|\]\]/g, "")
.replace(/\s+/g, " ")
.trim()
.slice(0, 300);
/** One address linked in step 1: its link (a note on the address), the address, and what it links to. */
export interface AddressLink {
note: NodeId;
url: string;
target: Ref;
}
export interface Linked {
links: AddressLink[];
/** A section made a link to the address that was its whole text. */
whole: { node: NodeId; url: string; target: Ref } | null;
}
/**
* Step 1, after an edit of a node's text from `before` to what it now reads: link the addresses
* new in it, in one commit. Returns the links made (or the section made a link), for steps 2 and 3.
*/
export function linkAddresses(doc: Doc, node: NodeId, before: string, meta: { author: string }): Linked {
const none: Linked = { links: [], whole: null };
const s = doc.snap();
const n = s.nodes[node];
if (!n) return none;
const declined = new Set(n.nolink ?? []);
const fresh = newAddresses(before, n.body).flatMap((b) => {
if (declined.has(phraseKey(b.url))) return [];
try {
return [{ ...b, target: addressTarget(b.url) }];
} catch {
return [];
}
});
if (!fresh.length) return none;
// A section that is nothing but the address: a section that is only the link.
const only = fresh[0];
if (fresh.length === 1 && n.body.trim() === only.url && n.kind === "section" && !n.ref && !isLibraryRoot(s, node) && !sections(s, node).length) {
doc.as(meta.author, () => doc.apply([{ op: "update", id: node, body: "", ref: only.target }], `Make “${clip(label(s, node), 40)}” a link to ${clip(describeTarget(only.target), 50)}`, { tag: "link" }));
return { links: [], whole: { node, url: only.url, target: only.target } };
}
// Words already linked keep their link.
const linked = notesOf(s, node).flatMap((c) => (s.nodes[c].ref ? s.nodes[c].anchors : []));
const todo = fresh.filter((b) => !linked.some((a) => a.start < b.range[1] && b.range[0] < a.end));
if (!todo.length) return none;
const message = todo.length === 1 ? `Link “${clip(todo[0].url, 50)}” to ${clip(describeTarget(todo[0].target), 50)}` : `Link ${todo.length} addresses typed in “${clip(label(s, node), 40)}”`;
applyLinks(doc, todo.map((b) => ({ node, range: b.range, target: b.target })), { author: meta.author, actor: "human", message });
const after = doc.snap();
const links: AddressLink[] = [];
for (const b of todo) {
const note = notesOf(after, node).find((c) => {
const x = after.nodes[c];
return x.anchors.length === 1 && x.anchors[0].start === b.range[0] && x.anchors[0].end === b.range[1] && sameTarget(x.ref, b.target);
});
if (note) links.push({ note, url: b.url, target: b.target });
}
return { links, whole: null };
}
/**
* Step 3: the address a link was made on, replaced in the text by the page's title, the link's
* words with it (and a page's link keeping the title, as w keeps it), in one commit. Only while the
* words are still the address as typed and the link still goes where it went: otherwise nothing is
* done, and false is returned.
*/
export function titleLink(doc: Doc, link: AddressLink, title: string, meta: { author: string }): boolean {
const s = doc.snap();
const c = s.nodes[link.note];
const p = c?.parent ? s.nodes[c.parent] : undefined;
const a = c?.anchors[0];
const words = titleWords(title);
if (!c || !p || !a || c.anchors.length !== 1 || !sameTarget(c.ref, link.target)) return false;
// Still the whole address as typed: not changed, and not run on into a longer one.
if (!words || words === link.url || !bareAddresses(p.body).some((b) => b.url === link.url && b.range[0] === a.start && b.range[1] === a.end)) return false;
const ref = c.ref!.kind === "url" && !c.ref!.title ? { ...c.ref!, title: words } : undefined;
// The address out, then the title in: never a diff that keeps letters the two share, so the
// link's old ends are gone with the address, and undo puts them back on it (repo.ts healAnchors).
const ops: Op[] = [
{ op: "update", id: p.id, body: p.body.slice(0, a.start) + p.body.slice(a.end) },
{ op: "update", id: p.id, body: p.body.slice(0, a.start) + words + p.body.slice(a.end) },
{ op: "update", id: c.id, anchors: [[a.start, a.start + words.length]], ...(ref ? { ref } : {}) },
];
doc.as(meta.author, () => doc.apply(ops, `Title the link “${clip(link.url, 40)}”: “${clip(words, 50)}”`, { tag: "link" }));
return true;
}
/**
* Step 3 for a section made a link to its whole text: named by its page while its title is empty
* or a placeholder (a title of the writer's own is kept), and its target keeping the page's title.
* Only while it still links there; false when nothing was done.
*/
export function titleWhole(doc: Doc, whole: NonNullable<Linked["whole"]>, title: string, meta: { author: string }): boolean {
const s = doc.snap();
const n = s.nodes[whole.node];
const words = titleWords(title);
if (!n || !words || !sameTarget(n.ref, whole.target) || !placeholderTitle(n.title, whole.url)) return false;
const ops: Op[] = [...retitleOps(s, n.id, words), ...(n.ref!.kind === "url" && !n.ref!.title ? [{ op: "update" as const, id: n.id, ref: { ...n.ref!, title: words } }] : [])];
doc.as(meta.author, () => doc.apply(ops, `Name “${clip(words, 50)}” after its page`, { tag: "link" }));
return true;
}
+3 -1
View File
@@ -61,7 +61,8 @@ function mockJson(req: JsonReq): unknown {
// A web page arranged (server/pageArrange.ts). The sections come back out of order, with a // A web page arranged (server/pageArrange.ts). The sections come back out of order, with a
// repeat and a number past the end, as a careless model's might: the cleaning makes them // repeat and a number past the end, as a careless model's might: the cleaning makes them
// three sections starting at the first unit after the lead, a third and two thirds of the // three sections starting at the first unit after the lead, a third and two thirds of the
// way on. A title saying "mockfail" makes the call fail. // way on. A title saying "mockfail" makes the call fail; one saying "mockslow" makes it take
// 1.5 s (mockLLM.json).
if (/mockfail/i.test(v.title ?? "")) throw new Error("mock arranger: the call failed"); if (/mockfail/i.test(v.title ?? "")) throw new Error("mock arranger: the call failed");
const n = Number(v.units ?? 0); const n = Number(v.units ?? 0);
const first = Number(v.first ?? 1); const first = Number(v.first ?? 1);
@@ -228,6 +229,7 @@ export function mockLLM(opts: { delay?: number } = {}): LLM {
}, },
async json<T>(req: JsonReq) { async json<T>(req: JsonReq) {
if (delay) await sleep(delay); if (delay) await sleep(delay);
if (req.schema === "arrange" && /mockslow/i.test(req.vars?.title ?? "")) await sleep(1500);
return mockJson(req) as T; return mockJson(req) as T;
}, },
async turn(req, signal, onWeb) { async turn(req, signal, onWeb) {
+19 -5
View File
@@ -11,9 +11,10 @@
* always clear whose text this is. Its head names the site, the title and who wrote it; its foot * always clear whose text this is. Its head names the site, the title and who wrote it; its foot
* says where it is from, when it was read and what was changed. A page that cannot be shown says * says where it is from, when it was read and what was changed. A page that cannot be shown says
* why in plain words and offers the original. Nothing is written on it: annotations are for * why in plain words and offers the original. Nothing is written on it: annotations are for
* Wikipedia's text and the reader's own. What a model made of it at the reader's request (s) is * Wikipedia's text and the reader's own. What a model made of it (at the reader's request, s, or by
* marked as the model's: its summary above the lead (the page's own opening still follows), a * itself for a page with no headings) is marked as the model's: its summary above the lead (the
* line when the sections are the model's, and the foot. * page's own opening still follows), a line when the sections are the model's, and the foot. While a
* page divided by length is being arranged by itself, or when it was not, one quiet line says so.
*/ */
import { useContext } from "preact/hooks"; import { useContext } from "preact/hooks";
import { clip, type Range } from "../core/text"; import { clip, type Range } from "../core/text";
@@ -94,13 +95,25 @@ function Attribution({ a }: { a: WebArticle["attribution"] }) {
function ModelSummary({ m }: { m: NonNullable<WebArticle["model"]> }) { function ModelSummary({ m }: { m: NonNullable<WebArticle["model"]> }) {
return ( return (
<aside class="web-model" data-model-summary> <aside class="web-model" data-model-summary>
<p class="web-model-label">Summary written by a model{m.by ? ` (${m.by})` : ""} from the page's openings, at your request; not the author's words</p> <p class="web-model-label">Summary written by a model{m.by ? ` (${m.by})` : ""} from the page's openings; not the author's words</p>
<p class="web-model-text">{m.summary}</p> <p class="web-model-text">{m.summary}</p>
{m.note && <p class="web-model-label">{m.note}</p>} {m.note && <p class="web-model-label">{m.note}</p>}
</aside> </aside>
); );
} }
/** What s does after an arrangement by itself was not made, by its reason: nothing, where s would be refused the same. */
const AGAIN: Record<string, string> = { manual: " s arranges it.", "no-model": "", off: "" };
/** One quiet line on a page divided by length: a model is arranging it, or why it is not (and what s does). */
function AutoLine({ auto }: { auto: NonNullable<WebArticle["auto"]> }) {
return (
<p class="web-model-label web-auto" data-auto={auto.state}>
{auto.state === "running" ? "Arranging into sections with a model…" : `Kept in parts by length: ${auto.message}${AGAIN[auto.reason] ?? " s tries again."}`}
</p>
);
}
/** A page that is not shown: what is known of it, why, and the original in a new tab. */ /** A page that is not shown: what is known of it, why, and the original in a new tab. */
function Unusable({ url, p }: { url: string; p: WebProblem }) { function Unusable({ url, p }: { url: string; p: WebProblem }) {
return ( return (
@@ -189,7 +202,8 @@ export function WebView({ host, own, headFocused }: { host: string } & ViewOpts)
{at0.stale && <p class="wiki-wait">The page no longer answers; this is the copy read before. R tries again.</p>} {at0.stale && <p class="wiki-wait">The page no longer answers; this is the copy read before. R tries again.</p>}
{!sec && v.model?.summary && <ModelSummary m={v.model} />} {!sec && v.model?.summary && <ModelSummary m={v.model} />}
{sec || v.lead ? <WebText host={host} row={{ t: "head" }} html={sec ? sec.html : v.lead} /> : null} {sec || v.lead ? <WebText host={host} row={{ t: "head" }} html={sec ? sec.html : v.lead} /> : null}
{!sec && v.outline === "model" && <p class="web-model-label web-arranged">Sections arranged by a model at your request; the page has no headings of its own.</p>} {!sec && v.outline === "model" && <p class="web-model-label web-arranged">Sections arranged by a model; the page has no headings of its own.</p>}
{!sec && v.auto && <AutoLine auto={v.auto} />}
<Rows article={v} host={host} parent={h.sec} nested={!!h.nested} at={at} showing={showing} /> <Rows article={v} host={host} parent={h.sec} nested={!!h.nested} at={at} showing={showing} />
<Attribution a={at0} /> <Attribution a={at0} />
</section> </section>
+1 -1
View File
@@ -47,7 +47,7 @@ export const HELP: [string, [string, string][]][] = [
["w", "on a selection: link it (library, Wikipedia or an address); on a link: retarget it; on a node: give the node a target. A section with a target and nothing else of its own is shown as its article: opened, its pane reads as the article (in one column, the article opens under its row); on that pane's head r w D a c act on the section, and a or c makes it a section like any other"], ["w", "on a selection: link it (library, Wikipedia or an address); on a link: retarget it; on a node: give the node a target. A section with a target and nothing else of its own is shown as its article: opened, its pane reads as the article (in one column, the article opens under its row); on that pane's head r w D a c act on the section, and a or c makes it a section like any other"],
["L", "on a node: open its own target (in panes, to the right of the node's pane when that is open)"], ["L", "on a node: open its own target (in panes, to the right of the node's pane when that is open)"],
["W", "open the focused article on wikipedia.org, or a web page (or a link to one) at its own address, in a new tab"], ["W", "open the focused article on wikipedia.org, or a web page (or a link to one) at its own address, in a new tab"],
["s", "on a web page: have the model summarise it, and arrange a page divided only by length into sections of its choosing (a page with headings of its own keeps them). Only when asked, within the server's daily limit of calls (EX_PAGE_CALLS); the summary is shown above the lead, marked as the model's, and the foot says what the model did. Pressed again on the same text, it costs no call"], ["s", "on a web page: have the model summarise it, and arrange a page divided only by length into sections of its choosing (a page with headings of its own keeps them). A page with no headings is arranged by itself once when first read; s asks again, within the server's daily limit of calls (EX_PAGE_CALLS); the summary is shown above the lead, marked as the model's, and the foot says what the model did. Pressed again on the same text, it costs no call"],
["R", "on a web page: read it again (a page is otherwise kept as first read). Unchanged text keeps what the model made of it; a page that no longer answers keeps the copy read before, marked stale; one that could not be shown is asked again"], ["R", "on a web page: read it again (a page is otherwise kept as first read). Unchanged text keeps what the model made of it; a page that no longer answers keeps the copy read before, marked stale; one that could not be shown is asked again"],
["D", "on a link: remove it, and decline its words in that node so it is not made again (u undoes). Also in the right-click menu: Remove the link"], ["D", "on a link: remove it, and decline its words in that node so it is not made again (u undoes). Also in the right-click menu: Remove the link"],
["y n", "on a suggested link (a faint dashed underline; Tab reaches it): link it / decline it (a declined phrase is not suggested again in that node)"], ["y n", "on a suggested link (a faint dashed underline; Tab reaches it): link it / decline it (a declined phrase is not suggested again in that node)"],
+76 -6
View File
@@ -26,7 +26,8 @@ import { annotationsOf, articleNodes, inArticles, makeAnchor, reanchor, type Art
import { asOpened, describeTarget, formatTarget, hostOf, parseTargetLoose, wikiKey, type Ref } from "../core/ref"; import { asOpened, describeTarget, formatTarget, hostOf, parseTargetLoose, wikiKey, type Ref } from "../core/ref";
import { article as wikiArticle, articleText, cachedExtract, sectionPath, sectionsUnder, sectionTexts, configureWiki, sensesOf as wikiSenses, wikiUrl, type Article, type WikiConfig } from "./wiki"; import { article as wikiArticle, articleText, cachedExtract, sectionPath, sectionsUnder, sectionTexts, configureWiki, sensesOf as wikiSenses, wikiUrl, type Article, type WikiConfig } from "./wiki";
import type { ArticleText } from "./articleText"; import type { ArticleText } from "./articleText";
import { arrangePage, article as webArticle, canArrange, configurePages, knownArticle, reloadPage, sectionsUnder as webSectionsUnder, siteOf, webKey, type PagesConfig } from "./web"; import { arrangePage, article as webArticle, canArrange, configurePages, knownArticle, pageInfo, reloadPage, sectionsUnder as webSectionsUnder, siteOf, webKey, type PagesConfig } from "./web";
import { linkAddresses, titleLink, titleWhole, type AddressLink } from "../core/bareLinks";
import { LENSES } from "../llm/prompts"; import { LENSES } from "../llm/prompts";
import { import {
cascade, commitArticleNote, commitExpansion, deepen, reconcile, resolveConflicts, runAgent, scanContradictions, streamArticleNote, streamExpansion, cascade, commitArticleNote, commitExpansion, deepen, reconcile, resolveConflicts, runAgent, scanContradictions, streamArticleNote, streamExpansion,
@@ -1299,7 +1300,7 @@ class Store {
if (state?.wiki) this.wiki = state.wiki; if (state?.wiki) this.wiki = state.wiki;
this.web = state?.web ?? { on: false, searches: 0, fetches: 0 }; this.web = state?.web ?? { on: false, searches: 0, fetches: 0 };
if (state?.linkJob?.state === "running") this.links.job = state.linkJob; if (state?.linkJob?.state === "running") this.links.job = state.linkJob;
configurePages(state?.pages, () => this.pageArrived()); configurePages(state?.pages, (w) => this.pageArrived(!!w?.arranged));
configureWiki(state?.wiki, () => (this.replayHeld(), this.emit()), () => { configureWiki(state?.wiki, () => (this.replayHeld(), this.emit()), () => {
// Once per browser: why Wikipedia is slow, and what makes it fast. // Once per browser: why Wikipedia is slow, and what makes it fast.
if (lsGet("ie:wiki-hint", false)) return; if (lsGet("ie:wiki-hint", false)) return;
@@ -2286,6 +2287,7 @@ class Store {
this.apply([...(value !== n[e.field] ? [op] : []), ...links], `${e.field === "title" ? "Rename" : "Edit"} “${clip(e.field === "title" ? value : label(s, e.node), 40)}”`); this.apply([...(value !== n[e.field] ? [op] : []), ...links], `${e.field === "title" ? "Rename" : "Edit"} “${clip(e.field === "title" ? value : label(s, e.node), 40)}”`);
if (value !== n[e.field]) this.afterEdit(e.node, `the ${e.field} of “${n.title}” was edited by a person`); if (value !== n[e.field]) this.afterEdit(e.node, `the ${e.field} of “${n.title}” was edited by a person`);
if (e.field === "body") this.links.scan(e.node, "human", marks); if (e.field === "body") this.links.scan(e.node, "human", marks);
if (e.field === "body" && value !== n.body) this.typedAddresses(e.node, n.body);
} else if (n && marks.length) { } else if (n && marks.length) {
this.links.scan(e.node, "human", marks); this.links.scan(e.node, "human", marks);
} else if (n && e.fresh && !n.title && !n.body) { } else if (n && e.fresh && !n.title && !n.body) {
@@ -2296,6 +2298,72 @@ class Store {
this.focus = { node: this.snap.nodes[this.focus.node] ? this.focus.node : this.top, grain: "node" }; this.focus = { node: this.snap.nodes[this.focus.node] ? this.focus.node : this.top, grain: "node" };
this.remember(); this.remember();
this.emit(); this.emit();
// Titles that arrived while this node's text was being edited, tried now against what it reads.
const waiting = e && this.titling.get(e.node);
if (waiting) {
this.titling.delete(e.node);
for (const f of waiting) f();
this.emit();
}
}
/** Titles of typed addresses waiting for an edit of their node's text to finish, by node. */
private titling = new Map<NodeId, (() => void)[]>();
/**
* Bare addresses typed into a node's text, once the edit is finished (src/core/bareLinks.ts):
* linked as typed, one commit; then each page's title read (at most TITLED from one edit; an
* article's title is in its address) and put in place of the address, one commit each, while the
* words are still the address as typed. A page that cannot be read leaves its address linked as
* typed, and the status line says why, once. Always on: the reader asked for it, and each step is
* undone by u like any edit.
*/
private typedAddresses(id: NodeId, before: string) {
const doc = this.doc;
const meta = { author: this.user };
let r: ReturnType<typeof linkAddresses> = { links: [], whole: null };
this.agentUndo = null;
this.attempt(() => (r = linkAddresses(doc, id, before, meta)));
const TITLED = 5;
// Each title is tried when it arrives, or once an edit of the same node in the meantime is finished.
const when = (node: NodeId, f: () => void) => {
if (doc !== this.doc) return;
if (this.edit?.node === node && this.edit.field === "body") this.titling.set(node, [...(this.titling.get(node) ?? []), f]);
else f(), this.emit();
};
const titleOf = (url: string, target: Ref): Promise<{ ok: true; title: string | null } | { ok: false; message: string }> => (target.kind === "wiki" ? Promise.resolve({ ok: true, title: target.title }) : pageInfo(url));
const unread = (url: string, why: string) => this.say(`No title for ${clip(url, 60)}: ${clip(why, 140)} The address stays as typed, linked.`);
if (r.whole) {
const w = r.whole;
this.say(`This section is now a link to ${w.target.kind === "wiki" ? `the article “${w.target.title}”` : hostOf(w.url)}${w.target.kind === "url" ? "; reading the page for its title…" : "."}`);
void titleOf(w.url, w.target).then((t) =>
when(w.node, () => {
if (!t.ok) return unread(w.url, t.message);
if (t.title && titleWhole(doc, w, t.title, meta)) this.say(`Named “${clip(t.title, 60)}” after its page. u to undo.`);
}),
);
return;
}
if (!r.links.length) return;
const urls = [...new Set(r.links.map((l) => l.url))];
const read = urls.filter((u) => r.links.find((l) => l.url === u)!.target.kind === "url");
const left = read.slice(TITLED);
const skip = new Set(left);
this.say(`${r.links.length === 1 ? "Linked the address" : `Linked ${r.links.length} addresses`}${read.length > skip.size ? "; reading the page titles…" : "."}${left.length ? ` ${left.length} more ${left.length === 1 ? "is" : "are"} linked as typed, without reading ${left.length === 1 ? "its page" : "their pages"} (at most ${TITLED} are read from one edit).` : ""}`);
for (const url of urls) {
if (skip.has(url)) continue;
const links: AddressLink[] = r.links.filter((l) => l.url === url);
void titleOf(url, links[0].target).then((t) =>
when(id, () => {
if (!t.ok) return unread(url, t.message);
if (!t.title) return;
let n = 0;
// Last first: titling one occurrence moves the text after it, never before.
for (const l of [...links].reverse()) this.attempt(() => void (titleLink(doc, l, t.title!, meta) && n++));
if (n) this.say(`Linked as “${clip(t.title, 60)}”, the ${links[0].target.kind === "wiki" ? "article's" : "page's"} title. u brings the address back.`);
}),
);
}
} }
/** /**
@@ -3059,12 +3127,14 @@ class Store {
} }
/** /**
* A web page has arrived (or failed): a pane on a section it no longer has closes (livePane), the * A web page has arrived (or failed), or one divided by length has been arranged by itself
* keys that waited for it are done, and the column's page takes its title. * (`arranged`): a pane on a section it no longer has closes (livePane), the keys that waited for
* it are done, and the column's page takes its title.
*/ */
private pageArrived() { private pageArrived(arranged = false) {
const closed = this.pruneSections(); const closed = this.pruneSections();
if (closed) this.say(closed === 1 ? "A pane showed a section this web page no longer has; it is closed." : `${closed} panes showed sections this web page no longer has; they are closed.`); const what = arranged ? (closed === 1 ? "A model has arranged this page into sections; the pane on one of its parts by length is closed." : `A model has arranged this page into sections; the ${closed} panes on its parts by length are closed.`) : closed === 1 ? "A pane showed a section this web page no longer has; it is closed." : `${closed} panes showed sections this web page no longer has; they are closed.`;
if (closed) this.say(what);
this.replayHeld(); this.replayHeld();
if (this.colWiki?.url) this.setTitle(); if (this.colWiki?.url) this.setTitle();
this.emit(); this.emit();
+1 -1
View File
@@ -788,7 +788,7 @@ kbd, .help code { font-family: var(--mono); font-size: 0.86em; border: 1px solid
.web-model { margin: 0.2rem 0 0.8rem; padding: 0.45rem 0.7rem; border-left: 2px dashed var(--web-rule); background: color-mix(in srgb, var(--bg) 45%, transparent); } .web-model { margin: 0.2rem 0 0.8rem; padding: 0.45rem 0.7rem; border-left: 2px dashed var(--web-rule); background: color-mix(in srgb, var(--bg) 45%, transparent); }
.web-model-label { margin: 0 0 0.2rem; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.02em; color: var(--faint); } .web-model-label { margin: 0 0 0.2rem; font-family: var(--sans); font-size: 0.62rem; letter-spacing: 0.02em; color: var(--faint); }
.web-model-text { margin: 0; font-size: 0.95rem; line-height: 1.55; } .web-model-text { margin: 0; font-size: 0.95rem; line-height: 1.55; }
.web-arranged { margin: 0.6rem 0 0.2rem; } .web-arranged, .web-auto { margin: 0.6rem 0 0.2rem; }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
/* Most images are drawn for a light page: a light plate behind them. */ /* Most images are drawn for a light page: a light plate behind them. */
.wiki-text figure img { background: #f3efe6; } .wiki-text figure img { background: #f3efe6; }
+67 -11
View File
@@ -8,12 +8,14 @@
* ask the server's cache alone (summary &cached=1), which never reads the site. The page's HTML * ask the server's cache alone (summary &cached=1), which never reads the site. The page's HTML
* arrives sanitised and is cleaned again where it is drawn (wiki.ts articleText, with `web` set). * arrives sanitised and is cleaned again where it is drawn (wiki.ts articleText, with `web` set).
* Two actions the reader takes on a page replace what is kept here: Reload (read it again) and * Two actions the reader takes on a page replace what is kept here: Reload (read it again) and
* Arrange (a model's summary, and sections for a page divided only by length). * Arrange (a model's summary, and sections for a page divided only by length). So does a page
* divided by length that the server is arranging by itself: it comes with `auto: running`, is shown
* as it is meanwhile, and is replaced by the arranged page when the server has it (`follow`).
*/ */
import type { WebArticle, WebSection, WebSummary, WebUnusable } from "../../server/page"; import type { AutoArrange, WebArticle, WebSection, WebSummary, WebUnusable } from "../../server/page";
import { normUrl } from "../llm/web"; import { normUrl } from "../llm/web";
export type { WebArticle, WebSection, WebSummary, WebUnusable }; export type { AutoArrange, WebArticle, WebSection, WebSummary, WebUnusable };
/** Why a page is not shown: the server's reason and its words, with what it knew of the page. */ /** Why a page is not shown: the server's reason and its words, with what it knew of the page. */
export type WebProblem = Pick<WebUnusable, "message" | "title" | "description" | "site"> & { reason: WebUnusable["reason"] | "uncached" }; export type WebProblem = Pick<WebUnusable, "message" | "title" | "description" | "site"> & { reason: WebUnusable["reason"] | "uncached" };
@@ -33,9 +35,11 @@ export interface PagesConfig {
} }
let config: PagesConfig = { mode: "live" }; let config: PagesConfig = { mode: "live" };
let onChange: () => void = () => {}; /** Told when a page has arrived or changed; `arranged` when it is a page the server arranged by itself. */
type Changed = (what?: { arranged?: string }) => void;
let onChange: Changed = () => {};
export function configurePages(c: Partial<PagesConfig> | undefined, changed: () => void) { export function configurePages(c: Partial<PagesConfig> | undefined, changed: Changed) {
if (c) config = { ...config, ...c }; if (c) config = { ...config, ...c };
onChange = changed; onChange = changed;
} }
@@ -77,6 +81,7 @@ function load<T>(cache: Map<string, Loadable<T>>, key: string, path: string, fie
void get<T>(path, field).then((r) => { void get<T>(path, field).then((r) => {
cache.set(key, r.ok ? { state: "ready", value: r.value, cached: r.cached } : { state: "failed", at: Date.now(), ...stripOk(r) }); cache.set(key, r.ok ? { state: "ready", value: r.value, cached: r.cached } : { state: "failed", at: Date.now(), ...stripOk(r) });
onChange(); onChange();
if (r.ok && field === "article") follow(r.value as WebArticle);
}); });
return cache.get(key)!; return cache.get(key)!;
} }
@@ -131,6 +136,7 @@ async function post<X>(route: "reload" | "arrange", url: string): Promise<Acted<
if (res.ok && body.ok && body.article) { if (res.ok && body.ok && body.article) {
articles.set(normUrl(url), { state: "ready", value: body.article as WebArticle, cached: false }); articles.set(normUrl(url), { state: "ready", value: body.article as WebArticle, cached: false });
summaries.delete(normUrl(url)); summaries.delete(normUrl(url));
follow(body.article as WebArticle, url);
return body as unknown as Acted<X>; return body as unknown as Acted<X>;
} }
const reason = typeof body.reason === "string" ? body.reason : "error"; const reason = typeof body.reason === "string" ? body.reason : "error";
@@ -143,6 +149,42 @@ async function post<X>(route: "reload" | "arrange", url: string): Promise<Acted<
} }
} }
/** Pages whose arranging by itself is being waited for, by key. */
const following = new Set<string>();
/**
* A page the server is arranging by itself (`auto: running`): wait for it, by asking arrange with
* `auto`, which never starts a call of its own, and put what comes in place of the page kept here,
* the arranged page, or the same page with why it was not arranged. `url` is the address asked for,
* which is what the server keeps the page under.
*/
function follow(a: WebArticle, url = a.requested) {
const k = normUrl(url);
if (a.auto?.state !== "running" || following.has(k)) return;
following.add(k);
const settle = (next: WebArticle | null, auto?: AutoArrange) => {
const have = articles.get(k);
if (have?.state !== "ready" || have.value.hash !== a.hash) return; // read again since: that copy has its own state
if (next) {
articles.set(k, { state: "ready", value: next, cached: false });
summaries.delete(k);
return onChange({ arranged: url });
}
const { auto: _, ...rest } = have.value;
articles.set(k, { ...have, value: auto ? { ...rest, auto } : rest });
onChange();
};
void fetch("/api/page/arrange", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ url, auto: true }) })
.then(async (res) => {
const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
if (res.ok && body.ok && body.article) return settle(body.article as WebArticle);
const reason = typeof body.reason === "string" ? body.reason : "error";
settle(null, reason === "idle" ? undefined : { state: "skipped", reason, message: typeof body.message === "string" && body.message ? body.message : `The server answered ${res.status}.` });
})
.catch(() => settle(null, { state: "skipped", reason: "offline", message: "The local server could not be reached." }))
.finally(() => following.delete(k));
}
const strs = (body: Record<string, unknown>, ...ks: string[]) => Object.fromEntries(ks.filter((k) => typeof body[k] === "string" && body[k]).map((k) => [k, body[k] as string])); const strs = (body: Record<string, unknown>, ...ks: string[]) => Object.fromEntries(ks.filter((k) => typeof body[k] === "string" && body[k]).map((k) => [k, body[k] as string]));
/** Read a page again (R). `stale`: it no longer answers, and the last copy is kept (with why). */ /** Read a page again (R). `stale`: it no longer answers, and the last copy is kept (with why). */
@@ -160,18 +202,32 @@ const TITLE_WAIT_MS = 2500;
* none (only its host), cannot be read, or takes longer than `wait`. * none (only its host), cannot be read, or takes longer than `wait`.
*/ */
export async function pageTitle(url: string, wait = TITLE_WAIT_MS): Promise<string | null> { export async function pageTitle(url: string, wait = TITLE_WAIT_MS): Promise<string | null> {
if (config.mode === "off") return null; const r = await pageInfo(url, wait);
return r.title ?? null;
}
/**
* A page's own title, read now (and kept by the server, which arranges a page divided by length
* by itself meanwhile): for an address typed into a node's text. `title` is null when the page
* gives none but its host; a page that cannot be read says why (with the title it gave, if any).
*/
export async function pageInfo(url: string, wait = 20_000): Promise<{ ok: true; title: string | null } | { ok: false; message: string; title?: string | null }> {
if (config.mode === "off") return { ok: false, message: PLAIN.off };
const ac = new AbortController(); const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), wait); const timer = setTimeout(() => ac.abort(), wait);
try { try {
const res = await fetch(`/api/page/summary?url=${encodeURIComponent(url)}`, { signal: ac.signal }); const res = await fetch(`/api/page/summary?url=${encodeURIComponent(url)}`, { signal: ac.signal });
const body = (await res.json().catch(() => ({}))) as { summary?: { title?: unknown }; title?: unknown }; const body = (await res.json().catch(() => ({}))) as { summary?: { title?: unknown }; title?: unknown; message?: unknown; reason?: unknown };
const t = body.summary?.title ?? body.title; const t = body.summary?.title ?? body.title;
if (typeof t !== "string") return null; const words = typeof t === "string" ? t.replace(/\s+/g, " ").trim().slice(0, 300) : "";
const title = t.replace(/\s+/g, " ").trim().slice(0, 300); const title = words && words !== siteOf(url) ? words : null;
return title && title !== siteOf(url) ? title : null; if (!res.ok || !body.summary) {
const reason = typeof body.reason === "string" && body.reason in PLAIN ? (body.reason as WebProblem["reason"]) : "error";
return { ok: false, message: typeof body.message === "string" && body.message ? body.message : PLAIN[reason], title };
}
return { ok: true, title };
} catch { } catch {
return null; return { ok: false, message: ac.signal.aborted ? "The page took too long to answer." : "The local server could not be reached." };
} finally { } finally {
clearTimeout(timer); clearTimeout(timer);
} }
+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 { mockLLM } from "../src/llm/mock";
import type { ArrangeReply, JsonReq, LLM } from "../src/llm/types"; import type { ArrangeReply, JsonReq, LLM } from "../src/llm/types";
import { BY_MODEL, PageClient, SUMMARY_BY_MODEL, type WebArticle } from "../server/page"; 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 type { PageUnit } from "../server/pageHtml";
import { MOCK_PAGES, makeMockPageFetch } from "../server/pageMock"; import { MOCK_PAGES, makeMockPageFetch } from "../server/pageMock";
import { pageRoutes } from "../server/pageRoutes"; 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", () => { describe("POST /api/page/reload and /api/page/arrange", () => {
let server: Server; let server: Server;
let base: string; 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 () => { 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("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 }); 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((await post("arrange", { url: MOCK_PAGES.essay })).body).toMatchObject({ ok: true, called: false });
expect(llm.calls).toHaveLength(1); expect(llm.calls).toHaveLength(1);
const article = await (await fetch(`${base}/api/page/article?url=${encodeURIComponent(MOCK_PAGES.essay)}`)).json(); const article = await (await fetch(`${base}/api/page/article?url=${encodeURIComponent(MOCK_PAGES.essay)}`)).json();
expect(article.article.outline).toBe("model"); 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 () => { 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" } }); expect(await post("reload", { url: MOCK_PAGES.pdf })).toMatchObject({ status: 422, body: { ok: false, reason: "type" } });
}); });