Review mode in the page: the reviewer's links as its own commit, the links list, removing a link for good
/autolink review, the default with a model, sends each scan's new candidates to the reviewer and makes the approved links at once as one commit by "reviewer" (tag review; u takes it back). Rejected ones are kept, not drawn. Without a model, on a failed call or at a job's cap, everything stays a suggestion and the status line says why. A browser still on the old default, suggest, moves to review once; a mode chosen with /autolink is kept. S now opens the links list beside the text: every link found or made, rejected and pending, with who decided and the reviewer's reason; 1 2 3 (or a click) toggle linked · rejected · pending, rejected hidden at first. y links a row (also one the reviewer rejected), n declines one or removes a link, Y links all pending shown, Enter goes to the words. Declines kept without a target show the phrase. D on a link, Remove the link in its menu and /unlink now also decline its words in the node, in the same commit, so the scanner and the reviewer do not put it back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014yB6q4BHMwptTX3YFtkRab
This commit is contained in:
1 parent
46b48d3497
commit
825f9beb65
10 files changed
+779
-132
No files matched your search
+15
-8
@@ -53,7 +53,8 @@ test.afterEach(async ({ page }) => {
|
||||
|
||||
test("with /autolink on, the sure links are made at once after an edit, as their own commit, and u removes them", async ({ page }) => {
|
||||
await column(page);
|
||||
expect(await state(page, (s) => s.settings.autolink)).toBe("suggest");
|
||||
// With a model, review is the default (e2e/reviewer.spec.ts); on links the scanner's sure ones unreviewed.
|
||||
expect(await state(page, (s) => s.settings.autolink)).toBe("review");
|
||||
await command(page, "/autolink on");
|
||||
await newDoc(page, "Autolink one", "The cephalopod met Fred Hoyle, who taught it the lambda calculus.");
|
||||
await idle(page);
|
||||
@@ -68,7 +69,7 @@ test("with /autolink on, the sure links are made at once after an edit, as their
|
||||
expect(await body(page)).toContain("Fred Hoyle");
|
||||
});
|
||||
|
||||
test("suggestions are drawn in the text; Tab reaches them, y links one, n declines one for good; S reviews the rest", async ({ page }) => {
|
||||
test("suggestions are drawn in the text; Tab reaches them, y links one, n declines one for good; S lists the rest", async ({ page }) => {
|
||||
await column(page);
|
||||
await command(page, "/autolink suggest");
|
||||
await newDoc(page, "Suggested links", "The cephalopod met Fred Hoyle.\n\nHe spoke of the Hoyle state of carbon-12 and of the lambda calculus.");
|
||||
@@ -93,18 +94,24 @@ test("suggestions are drawn in the text; Tab reaches them, y links one, n declin
|
||||
await keys(page, "Escape");
|
||||
await idle(page);
|
||||
expect(await suggestions(page)).not.toContain("Fred Hoyle");
|
||||
// Review: step through what is left; s skips, n declines, Y links all that remain.
|
||||
// The list: the link made, and the three waiting (the declined one is behind the rejected filter);
|
||||
// the first waiting is selected in the text. s skips, n declines, Y links all the waiting shown.
|
||||
await keys(page, "S");
|
||||
await expect(page.locator(".status .message")).toContainText("review 1/3");
|
||||
const panel = page.locator("[data-links-panel]");
|
||||
await expect(panel.locator(".lrow")).toHaveCount(4);
|
||||
await expect(panel.locator(".lfilter[data-filter=rejected]")).toHaveClass(/off/);
|
||||
await expect(panel.locator(".lfilter[data-filter=rejected] .n")).toHaveText("1");
|
||||
expect(await selected(page)).toBe("Hoyle state");
|
||||
await keys(page, "s");
|
||||
expect(await selected(page)).toBe("carbon-12");
|
||||
await keys(page, "n");
|
||||
expect(await selected(page)).toBe("lambda calculus");
|
||||
await keys(page, "Y");
|
||||
expect(await linksHere(page)).toEqual({ cephalopod: "Cephalopod", "Hoyle state": "Hoyle state", "lambda calculus": "Lambda calculus" });
|
||||
expect(await suggestions(page)).toEqual([]);
|
||||
await expect(panel.locator(".lfilter[data-filter=linked] .n")).toHaveText("3");
|
||||
await keys(page, "Escape");
|
||||
expect(await state(page, (s) => s.mode)).toBe("normal");
|
||||
expect(await linksHere(page)).toEqual({ cephalopod: "Cephalopod", "lambda calculus": "Lambda calculus" });
|
||||
expect(await suggestions(page)).toEqual(["Hoyle state"]);
|
||||
});
|
||||
|
||||
test("typing [[ in the editor completes from library titles first, then Wikipedia; the choice is linked on save", async ({ page }) => {
|
||||
@@ -203,7 +210,7 @@ test("/linkdoc and /linkall look for links in the background, with progress in t
|
||||
return s.links.under(Object.keys(s.snap.nodes), s.snap).length > 0;
|
||||
});
|
||||
await keys(page, "S");
|
||||
await expect(page.locator(".status .message")).toContainText("review 1/");
|
||||
await expect(page.locator("[data-links-panel] .lrow.pending").first()).toBeVisible();
|
||||
await keys(page, "Escape");
|
||||
});
|
||||
|
||||
@@ -232,6 +239,7 @@ test("/autolink off looks for nothing, suggest only suggests, on links", async (
|
||||
|
||||
test("Tab then Enter on an article that is still loading go to its first link once it arrives", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 1920, height: 1080 });
|
||||
await autoLayout(page);
|
||||
await page.goto("/");
|
||||
await page.waitForFunction(() => (globalThis as any).__ie?.ready);
|
||||
await newDoc(page, "Slow article link", "About the [[Hoyle state]].");
|
||||
@@ -239,7 +247,6 @@ test("Tab then Enter on an article that is still loading go to its first link on
|
||||
expect(await linksHere(page)).toEqual({ "Hoyle state": "Hoyle state" });
|
||||
// The article takes a while to come (a slow network); the reader does not wait for it.
|
||||
await page.route(/\/api\/wiki\/article\?title=Hoyle/, async (r) => {
|
||||
await autoLayout(page);
|
||||
await new Promise((done) => setTimeout(done, 1500));
|
||||
await r.continue();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* The link reviewer, keyboard and mouse: in review mode (the default with a model) what a scan
|
||||
* finds is judged by the model and the approved links are made as one commit by "reviewer" (u
|
||||
* undoes it); what it rejected waits behind the links list's filter, with its reason; a person
|
||||
* reverses either; a link removed in the text (by D or the right-click menu) is declined and not
|
||||
* made again; a failed review leaves everything as suggestions and says so; a background job is
|
||||
* reviewed as it goes and can be stopped. Against the mock model, whose reviewer links a name or a
|
||||
* term of several words and not a single lower-case word, and fails on a sentence that says
|
||||
* "mockfail" (src/llm/mock.ts).
|
||||
*
|
||||
* IE_SHOTS=<dir> also saves the links list with each filter, light and dark, into that directory.
|
||||
*/
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { command, idle, keys, selected, settle, state } from "./helpers";
|
||||
|
||||
const SHOTS = process.env.IE_SHOTS;
|
||||
|
||||
/** The links on the focused node: quote → target title. */
|
||||
const linksHere = (page: Page) =>
|
||||
state(page, (s) => {
|
||||
const snap = s.snap;
|
||||
const out: Record<string, string> = {};
|
||||
for (const c of snap.nodes[s.focus.node].children) {
|
||||
const n = snap.nodes[c];
|
||||
if (n.kind === "note" && n.ref) out[n.anchors[0].text] = n.ref.kind === "wiki" ? n.ref.title : n.ref.kind === "node" ? `node:${snap.nodes[n.ref.id]?.title}` : n.ref.url;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
const nolink = (page: Page) => state(page, (s) => (s.snap.nodes[s.focus.node].nolink ?? []) as string[]);
|
||||
const panel = (page: Page) => page.locator("[data-links-panel]");
|
||||
const count = (page: Page, status: string) => panel(page).locator(`.lfilter[data-filter=${status}] .n`);
|
||||
const row = (page: Page, quote: string) => panel(page).locator(".lrow", { has: page.locator(`.lq:text-is("“${quote}”")`) });
|
||||
|
||||
async function column(page: Page) {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await page.goto("/");
|
||||
await page.waitForFunction(() => (globalThis as any).__ie?.ready);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
}
|
||||
|
||||
/** A new document with this text, typed from the keyboard; the focus is on it afterwards. */
|
||||
async function newDoc(page: Page, title: string, text: string) {
|
||||
await command(page, `/new ${title}`);
|
||||
await expect(page.locator("h1", { hasText: title })).toBeVisible();
|
||||
await keys(page, "c");
|
||||
await page.keyboard.type(text);
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
test.beforeEach(async ({ context }) => {
|
||||
await context.route(/wikipedia\.org|wikimedia\.org/, (r) => r.abort());
|
||||
});
|
||||
|
||||
test.afterEach(async ({ page }) => {
|
||||
await settle(page);
|
||||
});
|
||||
|
||||
test("review mode: the approved links are made as one commit by the reviewer, the rejected wait behind a filter with the reason, and u undoes", async ({ page }) => {
|
||||
await column(page);
|
||||
expect(await state(page, (s) => s.settings.autolink)).toBe("review");
|
||||
await newDoc(page, "Reviewed links", "The cephalopod met Fred Hoyle, who taught it the lambda calculus.");
|
||||
await idle(page);
|
||||
expect(await linksHere(page)).toEqual({ "Fred Hoyle": "Fred Hoyle", "lambda calculus": "Lambda calculus" });
|
||||
const top = await state(page, (s) => s.commits()[0]);
|
||||
expect(top).toMatchObject({ by: "reviewer", tag: "review" });
|
||||
await expect(page.locator(".status .message")).toContainText("Linked");
|
||||
await expect(page.locator(".status .message")).toContainText("1 rejected");
|
||||
// The rejected one is not drawn as a suggestion.
|
||||
await expect(page.locator("article .sugg")).toHaveCount(0);
|
||||
|
||||
// The list: two linked, one rejected (hidden at first), none pending; each with who and why.
|
||||
await keys(page, "S");
|
||||
await expect(panel(page)).toBeVisible();
|
||||
await expect(count(page, "linked")).toHaveText("2");
|
||||
await expect(count(page, "rejected")).toHaveText("1");
|
||||
await expect(count(page, "pending")).toHaveText("0");
|
||||
await expect(panel(page).locator(".lrow")).toHaveCount(2);
|
||||
await expect(row(page, "Fred Hoyle")).toContainText("linked by the reviewer: mock: a name or a term");
|
||||
await expect(row(page, "cephalopod")).toHaveCount(0);
|
||||
if (SHOTS) await shots(page, "linked");
|
||||
// 2 shows the rejected, with the reviewer's reason; a click on the toggle does the same as the key.
|
||||
await keys(page, "2");
|
||||
await expect(row(page, "cephalopod")).toContainText("rejected by the reviewer: mock: one ordinary word needs no link");
|
||||
if (SHOTS) await shots(page, "linked-rejected");
|
||||
await keys(page, "1");
|
||||
await expect(panel(page).locator(".lrow")).toHaveCount(1);
|
||||
if (SHOTS) await shots(page, "rejected");
|
||||
await panel(page).locator(".lfilter[data-filter=linked]").click();
|
||||
await expect(panel(page).locator(".lrow")).toHaveCount(3);
|
||||
await keys(page, "Escape");
|
||||
|
||||
// u takes the reviewer's links back; they are then offered as suggestions.
|
||||
await keys(page, "u");
|
||||
await expect(page.locator("article .lnk")).toHaveCount(0);
|
||||
expect(await state(page, (s) => s.snap.nodes[s.focus.node].body)).toContain("Fred Hoyle");
|
||||
await expect(page.locator("article .sugg")).toHaveCount(2);
|
||||
});
|
||||
|
||||
test("in the list a person reverses the reviewer either way: links one it rejected, removes one it linked for good", async ({ page }) => {
|
||||
await column(page);
|
||||
await newDoc(page, "Reversed links", "The cephalopod met Fred Hoyle, who taught it the lambda calculus.");
|
||||
await idle(page);
|
||||
await keys(page, "S 2");
|
||||
// Select the rejected row with a click: its words are selected in the text.
|
||||
await row(page, "cephalopod").click();
|
||||
expect(await selected(page)).toBe("cephalopod");
|
||||
await keys(page, "y");
|
||||
await expect(row(page, "cephalopod")).toContainText("linked by tester · the reviewer said no");
|
||||
await expect(page.locator(".status .message")).toContainText("over the reviewer's no");
|
||||
expect(await linksHere(page)).toMatchObject({ cephalopod: "Cephalopod" });
|
||||
// The person's link is their own commit.
|
||||
expect(await state(page, (s) => s.commits()[0].by)).toBe("tester");
|
||||
await expect(count(page, "linked")).toHaveText("3");
|
||||
// n on a linked row removes the link and declines its words.
|
||||
await row(page, "Fred Hoyle").click();
|
||||
await keys(page, "n");
|
||||
await expect(row(page, "Fred Hoyle")).toContainText("declined by tester · the reviewer said yes");
|
||||
expect(await linksHere(page)).toEqual({ cephalopod: "Cephalopod", "lambda calculus": "Lambda calculus" });
|
||||
expect(await nolink(page)).toEqual(["fred hoyle"]);
|
||||
await keys(page, "Escape");
|
||||
// An edit (a rescan) brings neither decision back.
|
||||
await keys(page, "Escape Escape c End");
|
||||
await page.keyboard.type(" Indeed.");
|
||||
await keys(page, "Escape");
|
||||
await idle(page);
|
||||
expect(await linksHere(page)).toEqual({ cephalopod: "Cephalopod", "lambda calculus": "Lambda calculus" });
|
||||
await expect(page.locator("article .sugg")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("a link removed in the text, by D or by the right-click menu, is declined and not made again on a rescan", async ({ page }) => {
|
||||
await column(page);
|
||||
await newDoc(page, "Removed links", "Fred Hoyle wrote about the lambda calculus and the Hoyle state.");
|
||||
await idle(page);
|
||||
expect(Object.keys(await linksHere(page)).sort()).toEqual(["Fred Hoyle", "Hoyle state", "lambda calculus"]);
|
||||
// By key: Tab to the first link, D.
|
||||
await keys(page, "Tab");
|
||||
expect(await selected(page)).toBe("Fred Hoyle");
|
||||
await keys(page, "D");
|
||||
await expect(page.locator(".status .message")).toContainText("Removed the link on “Fred Hoyle”");
|
||||
expect(await nolink(page)).toEqual(["fred hoyle"]);
|
||||
// By the menu: right-click a library or Wikipedia link, Remove the link.
|
||||
await keys(page, "Escape Escape");
|
||||
await page.locator("article .lnk", { hasText: "lambda calculus" }).first().click({ button: "right" });
|
||||
const item = page.locator(".menu .mi", { has: page.locator('.lbl:text-is("Remove the link")') });
|
||||
await expect(item).toContainText("D");
|
||||
await item.click();
|
||||
expect(Object.keys(await linksHere(page))).toEqual(["Hoyle state"]);
|
||||
expect(await nolink(page)).toEqual(["fred hoyle", "lambda calculus"]);
|
||||
// An edit rescans the node; /linkdoc rescans the document: neither puts them back.
|
||||
await keys(page, "Escape Escape c End");
|
||||
await page.keyboard.type(" Again.");
|
||||
await keys(page, "Escape");
|
||||
await idle(page);
|
||||
await command(page, "/linkdoc");
|
||||
await page.waitForFunction(() => (globalThis as any).__ie.links.job?.state === "done", undefined, { timeout: 30_000 });
|
||||
await idle(page);
|
||||
expect(Object.keys(await linksHere(page))).toEqual(["Hoyle state"]);
|
||||
await expect(page.locator("article .sugg")).toHaveCount(0);
|
||||
// The help lists the key.
|
||||
await keys(page, "?");
|
||||
await expect(page.locator(".help")).toContainText("decline its words in that node so it is not made again");
|
||||
await keys(page, "Escape");
|
||||
});
|
||||
|
||||
test("when the model fails, nothing is linked unreviewed: everything is suggested, and the status line says so", async ({ page }) => {
|
||||
await column(page);
|
||||
await newDoc(page, "Failed review", "Fred Hoyle left mockfail notes on the lambda calculus.");
|
||||
await idle(page);
|
||||
await expect(page.locator("article .lnk")).toHaveCount(0);
|
||||
await expect(page.locator("article .sugg")).toHaveCount(2);
|
||||
await expect(page.locator(".status .message")).toContainText("Not reviewed (the reviewer failed: mock reviewer: the call failed)");
|
||||
await keys(page, "S");
|
||||
await expect(count(page, "pending")).toHaveText("2");
|
||||
await expect(panel(page).locator(".lrow.pending").first()).toContainText("not reviewed");
|
||||
await keys(page, "1");
|
||||
await expect(panel(page).locator(".lrow")).toHaveCount(2);
|
||||
if (SHOTS) await shots(page, "pending");
|
||||
await keys(page, "Escape");
|
||||
// Without a model, review is suggest, and the page says so when asked for it.
|
||||
await state(page, (s) => (s.llm = { ...s.llm, kind: "off" }));
|
||||
await command(page, "/autolink review");
|
||||
await expect(page.locator(".status .message")).toContainText("no model on this server, so for now links are only suggested");
|
||||
expect(await state(page, (s) => s.links.effective())).toBe("suggest");
|
||||
});
|
||||
|
||||
test("a background job is reviewed as it goes, with the model's calls counted, and can be stopped; a finished one links what was approved", async ({ page }) => {
|
||||
await column(page);
|
||||
await page.goto("/doc/tides");
|
||||
await page.waitForFunction(() => (globalThis as any).__ie?.ready);
|
||||
await command(page, "/linkall");
|
||||
await page.waitForFunction(() => (globalThis as any).__ie.links.job?.state === "running" && (globalThis as any).__ie.links.job.done > 0);
|
||||
expect(await state(page, (s) => s.links.job.review)).toMatchObject({ max: 50 });
|
||||
await expect(page.locator(".status .message")).toContainText("reviewer");
|
||||
await command(page, "/linkcancel");
|
||||
await page.waitForFunction(() => (globalThis as any).__ie.links.job?.state === "cancelled");
|
||||
await expect(page.locator(".status .message")).toContainText("Stopped looking for links in the library");
|
||||
// A document's job runs to the end: its approved links are made as one commit by the reviewer.
|
||||
const before = await state(page, (s) => s.commits()[0].id);
|
||||
await command(page, "/linkdoc");
|
||||
await page.waitForFunction(() => (globalThis as any).__ie.links.job?.state === "done", undefined, { timeout: 30_000 });
|
||||
await expect(page.locator(".status .message")).toContainText("linked by the reviewer");
|
||||
const job = await state(page, (s) => s.links.job);
|
||||
expect(job.review.calls).toBeGreaterThan(0);
|
||||
expect(job.review.calls).toBeLessThan(job.auto + job.suggest);
|
||||
await page.waitForFunction((id) => (globalThis as any).__ie.commits()[0].id !== id, before);
|
||||
expect(await state(page, (s) => s.commits()[0])).toMatchObject({ by: "reviewer", tag: "review" });
|
||||
});
|
||||
|
||||
/** The links list as it stands, light and dark. */
|
||||
async function shots(page: Page, name: string) {
|
||||
for (const scheme of ["light", "dark"] as const) {
|
||||
await page.emulateMedia({ colorScheme: scheme });
|
||||
await page.waitForTimeout(100);
|
||||
await page.screenshot({ path: `${SHOTS}/list-${name}-${scheme}.png` });
|
||||
}
|
||||
await page.emulateMedia({ colorScheme: "light" });
|
||||
}
|
||||
+10
-4
@@ -6,7 +6,7 @@ import { hostOf } from "../core/ref";
|
||||
import { nodeRef } from "../core/links";
|
||||
import { HELP, handleKey } from "./keys";
|
||||
import { DocBar, DocsPanel } from "./Menu";
|
||||
import { LinkCard, LinkPicker, NodeBacklinks, NodeRelated, TargetRow } from "./Links";
|
||||
import { LinkCard, LinkPicker, LinksPanel, NodeBacklinks, NodeRelated, TargetRow } from "./Links";
|
||||
import { NodeBody, Outline, PendingSections, TopMatter } from "./Node";
|
||||
import { Panes } from "./Panes";
|
||||
import { PANES_MIN_WIDTH, store, type Aux, type WRow } from "./store";
|
||||
@@ -376,9 +376,14 @@ function StatusLine() {
|
||||
const sugg = selecting && store.focusedSuggestion();
|
||||
const commentary = selecting && store.commentaryAt(f.range);
|
||||
const noteHere = selecting && store.noteAt(f.range);
|
||||
// Reviewing suggestions: where the review is, and its keys as buttons.
|
||||
// The links list: where it is, and its keys as buttons (unless something has just been said).
|
||||
const row = store.mode === "review" && !store.status ? store.reviewRow() : undefined;
|
||||
const reviewing: Hint | null =
|
||||
store.mode === "review" && store.status.startsWith("review ") ? [store.status.split(" · y link")[0], ["y", "link"], ["n", "decline"], ["s", "skip"], ["Y", "link all"], ["Escape", "stop"]] : null;
|
||||
store.mode === "review" && !store.status
|
||||
? row
|
||||
? [`${store.reviewRows().findIndex((x) => x.key === row.key) + 1}/${store.reviewRows().length} ${row.status}`, ...(row.status !== "linked" ? [["y", "link"] as [string, string]] : []), ...(row.status !== "rejected" ? [["n", row.status === "linked" ? "remove" : "decline"] as [string, string]] : []), ["j", "next"], ["Enter", "go"], ["Escape", "close"]]
|
||||
: ["links list", ["1", "linked"], ["2", "rejected"], ["3", "pending"], ["Escape", "close"]]
|
||||
: null;
|
||||
const hint: Hint = store.aux
|
||||
? store.aux.kind === "wiki"
|
||||
? store.inArticleText
|
||||
@@ -691,7 +696,7 @@ export function App() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "docs" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
|
||||
<div class={`app mode-${store.mode}${store.mode === "history" || store.mode === "docs" || store.mode === "review" ? " with-panel" : ""}${panes ? " view-panes" : ""}`} onMouseOver={onOver} onContextMenu={onContext}>
|
||||
<main
|
||||
class="page"
|
||||
onClick={onClick}
|
||||
@@ -709,6 +714,7 @@ export function App() {
|
||||
</main>
|
||||
{store.mode === "history" && <HistoryPanel verdict={verdict} />}
|
||||
{store.mode === "docs" && <DocsPanel />}
|
||||
{store.mode === "review" && <LinksPanel />}
|
||||
{store.mode === "help" && <Help />}
|
||||
{store.mode === "jump" && <Jump />}
|
||||
{store.mode === "command" && <CommandBar prefill={prefill} />}
|
||||
|
||||
+82
-3
@@ -10,8 +10,9 @@ import { docOf, isLink, label, type NodeId } from "../core/model";
|
||||
import { describeTarget, hostOf, parseTarget, validateRef, wikiTitle, type Ref } from "../core/ref";
|
||||
import { clip, plain } from "../core/text";
|
||||
import { kidClass, sameAux, store, type Aux } from "./store";
|
||||
import type { Sugg } from "./linker";
|
||||
import type { LinkRow, Status, Sugg } from "./linker";
|
||||
import { Hints } from "./Mouse";
|
||||
import { press } from "./press";
|
||||
import { suggest, summary, wikiConfig, type Attribution as Attr, type Suggestion } from "./wiki";
|
||||
|
||||
const MARK: Record<Ref["kind"], string> = { wiki: "W", node: "§", url: "↗" };
|
||||
@@ -195,10 +196,10 @@ export function SuggestionCard({ sg }: { sg: Sugg }) {
|
||||
return (
|
||||
<span class={`inset lpreview suggestion l-${sg.target.kind}`} data-suggestion={sg.id}>
|
||||
<span class="meta">
|
||||
<Hints hint={[`suggested link${sg.tier === "auto" ? " (sure)" : ""}`, ["y", "links"], ["n", "declines"], store.review ? ["s", "skips"] : ["S", "reviews them all"]]} />
|
||||
<Hints hint={[`suggested link${sg.tier === "auto" ? " (sure)" : ""}`, ["y", "links"], ["n", "declines"], store.review ? ["j", "next"] : ["S", "lists them all"]]} />
|
||||
</span>
|
||||
<LinkCard r={sg.target} compact />
|
||||
<span class="meta why">{sg.why}</span>
|
||||
<span class="meta why">{sg.review ? `reviewer: ${sg.review.link ? "yes" : "no"}, ${sg.review.reason}` : sg.why}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -373,3 +374,81 @@ export function LinkPicker() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---- the links list (S) ----
|
||||
|
||||
const FILTERS: [key: string, status: Status, label: string][] = [
|
||||
["1", "linked", "linked"],
|
||||
["2", "rejected", "rejected"],
|
||||
["3", "pending", "pending"],
|
||||
];
|
||||
|
||||
/** Who decided a row, and why, in a line. */
|
||||
function verdictLine(r: LinkRow): string {
|
||||
const why = r.reason ? `: ${r.reason}` : "";
|
||||
const said = r.verdict === null || !r.reason ? "" : ` · the reviewer said ${r.verdict ? "yes" : "no"}${why}`;
|
||||
if (r.status === "linked") return r.by === "reviewer" ? `linked by the reviewer${why}` : r.by ? `linked by ${r.by}${said}` : `linked${said}`;
|
||||
if (r.status === "rejected") {
|
||||
if (r.by === "reviewer") return `rejected by the reviewer${why}`;
|
||||
return `${r.by ? `declined by ${r.by}` : "declined"}${said}${r.target ? "" : " · its target was not kept"}`;
|
||||
}
|
||||
if (r.verdict === true) return `approved by the reviewer but not linked (undone?)${why}`;
|
||||
return `not reviewed${r.sugg ? ` · the scanner was ${r.sugg.tier === "auto" ? "sure" : "unsure"}` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The links list (S): every link found or made in the current document, as it stands, with who
|
||||
* decided and the reviewer's reason. Quiet toggles filter it by status; the selected row's words
|
||||
* are selected in the text, and every key it takes is a button in its head.
|
||||
*/
|
||||
export function LinksPanel() {
|
||||
const r = store.review;
|
||||
const ref = useRef<HTMLElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
ref.current?.querySelector(".lrow.selected")?.scrollIntoView({ block: "nearest" });
|
||||
});
|
||||
if (!r) return null;
|
||||
const all = store.reviewAll();
|
||||
const rows = all.filter((x) => r.show[x.status]);
|
||||
const sel = store.reviewRow();
|
||||
const s = store.snap;
|
||||
const doc = store.currentDoc;
|
||||
const count = (st: Status) => all.filter((x) => x.status === st).length;
|
||||
return (
|
||||
<aside class="panel links" ref={ref} data-links-panel>
|
||||
<div class="panel-head">
|
||||
<span>Links{doc ? ` · ${clip(s.nodes[doc]?.title ?? "", 30)}` : ""}</span>
|
||||
<span class="keys">
|
||||
<Hints hint={["j k", ...(sel?.status !== "linked" ? [["y", "link"] as [string, string]] : []), ...(sel?.status !== "rejected" ? [["n", sel?.status === "linked" ? "remove" : "decline"] as [string, string]] : []), ["Y", "link all"], ["Enter", "go"], ["Escape", "close"]]} />
|
||||
</span>
|
||||
</div>
|
||||
<div class="lfilters">
|
||||
{FILTERS.map(([k, st, name], i) => (
|
||||
<Fragment key={st}>
|
||||
{i > 0 && <span class="hsep"> · </span>}
|
||||
<button type="button" class={`lfilter ${r.show[st] ? "on" : "off"}`} data-filter={st} title={`${k}: ${r.show[st] ? "hide" : "show"} what is ${name}`} onMouseDown={(e) => e.preventDefault()} onClick={(e) => (e.stopPropagation(), press(k))}>
|
||||
<kbd>{k}</kbd> {name} <span class="n">{count(st)}</span>
|
||||
</button>
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
{!rows.length && <p class="lempty">{all.length ? "Nothing shown: 1 2 3 show more." : "Nothing linked or found here yet. :/linkdoc looks for links in this document."}</p>}
|
||||
{rows.map((x) => (
|
||||
<div key={x.key} class={`item lrow ${x.status}${x.key === sel?.key ? " selected" : ""}`} data-row={x.status} onClick={() => store.reviewSelect(x.key)}>
|
||||
<div class="line">
|
||||
<span class="lq">“{clip(x.quote, 48)}”</span>
|
||||
{x.target && (
|
||||
<span class="lt">
|
||||
→ {clip(x.title, 48)}
|
||||
<span class={`lmark l-${x.target.kind}`}>{MARK[x.target.kind]}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div class="sub">
|
||||
<span class="lwhere">{clip(label(s, x.node), 36)}</span> · {verdictLine(x)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
+5
-4
@@ -118,7 +118,8 @@ export function selectionEntries(c: SelCtx, act: Act): Entry[] {
|
||||
c.suggestion && key(act, `Link to ${c.suggestion}`, "y", { sub: "a suggested link" }),
|
||||
c.suggestion && key(act, "Decline the suggestion", "n"),
|
||||
(c.link || c.note) && !c.article && key(act, c.link ? "Retarget…" : "Link it…", "w"),
|
||||
(c.link || c.note) && key(act, c.link && !c.note ? "Remove the link" : "Delete the note", "D"),
|
||||
(c.link || c.note) && key(act, c.link && !c.note ? "Remove the link" : "Delete the note", "D", c.link && !c.note ? { sub: "and do not link these words again here" } : {}),
|
||||
c.link && c.note && !c.article && { t: "item", label: "Remove the link, keep the note", keyText: "/unlink", run: () => act.command("/unlink") },
|
||||
SEP,
|
||||
...lenses(act),
|
||||
SEP,
|
||||
@@ -225,7 +226,7 @@ export function articleRowEntries(title: string, panes: boolean, act: Act): Entr
|
||||
|
||||
export interface TopCtx {
|
||||
view: "auto" | "column" | "panes";
|
||||
autolink: "suggest" | "on" | "off";
|
||||
autolink: "review" | "suggest" | "on" | "off";
|
||||
auto: boolean;
|
||||
speculate: boolean;
|
||||
curves: boolean;
|
||||
@@ -249,11 +250,11 @@ export function topEntries(c: TopCtx, act: Act): Entry[] {
|
||||
key(act, "Undo", "u"),
|
||||
key(act, "Redo", "U", { disabled: !c.canRedo }),
|
||||
SEP,
|
||||
c.doc && key(act, "Review suggested links", "S"),
|
||||
c.doc && key(act, "Links found: review and reverse", "S"),
|
||||
c.doc && { t: "item", label: "Find links in this document", keyText: "/linkdoc", run: () => act.command("/linkdoc") },
|
||||
SEP,
|
||||
{ t: "choices", label: "Layout", options: [view("auto"), view("column"), view("panes")] },
|
||||
{ t: "choices", label: "Links found", options: [auto("suggest", "suggest"), auto("on", "link sure"), auto("off", "off")] },
|
||||
{ t: "choices", label: "Links found", options: [auto("review", "review"), auto("suggest", "suggest"), auto("on", "link sure"), auto("off", "off")] },
|
||||
setting("Reconcile after edits", "auto", c.auto),
|
||||
setting("Write ahead while reading", "speculate", c.speculate),
|
||||
c.panes && setting("Curves between panes", "curves", c.curves),
|
||||
|
||||
+20
-9
@@ -38,9 +38,9 @@ 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"],
|
||||
["L", "on a node: open its own target"],
|
||||
["W", "open the focused article on wikipedia.org, in a new tab"],
|
||||
["D", "on a link: remove it (u undoes)"],
|
||||
["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)"],
|
||||
["S", "review the suggested links of this document one by one: y link · n decline · s skip · Y link all the rest · Esc stop"],
|
||||
["S", "the links list of this document: every link found or made, with who decided and the reviewer's reason. 1 2 3 show or hide linked · rejected · pending (rejected is hidden at first); j k move (the words are selected in the text); y links (also a rejected one: you overrule); n declines, or on a link removes it for good; Y links all the pending shown; Enter goes to the words; Esc closes"],
|
||||
["1–5", "the node's Related list (sections of other documents close in meaning, numbered under its text): with words selected, link them to that one; on the node, go there"],
|
||||
["l h j k", "in an article: sections are rows, as in a node; l opens one, h goes back"],
|
||||
["i e d y x c :", "in an article: select words of its text as in a node, and write a note on them; the note belongs to the article and shows wherever it is opened (one whose words are gone from a newer revision is listed as detached)"],
|
||||
@@ -133,11 +133,11 @@ export const HELP: [string, [string, string][]][] = [
|
||||
["/import", "open a .md file as a new document"],
|
||||
["/recover", "save edits this browser made before the library existed, and never sent, as .md files"],
|
||||
["/link target", "link the selection (or the node): w:Title, /document/Section, an address, or a Wikipedia title"],
|
||||
["/unlink", "remove the link on the selection, or the node's own target"],
|
||||
["/autolink suggest|on|off", "after an edit: suggest what was found (suggest, the default), also link the surest at once (on, u undoes), or look for nothing (off)"],
|
||||
["/linkdoc", "look for links in the whole document, in the background; progress in the status line"],
|
||||
["/unlink", "remove the link on the selection (for good: its words are declined; a note that also links keeps its text), or the node's own target"],
|
||||
["/autolink review|suggest|on|off", "after an edit: the model reviews what was found and links what it approves (review, the default with a model; u undoes, S lists every decision), suggest everything for you to decide (suggest; what review does without a model, or when the model fails or its limit is reached), link the scanner's sure ones unreviewed (on), or look for nothing (off)"],
|
||||
["/linkdoc", "look for links in the whole document, in the background (reviewed, in review mode); progress and the reviewer's model calls in the status line"],
|
||||
["/linkall", "look for links in the whole library, in the background"],
|
||||
["/linkcancel", "stop looking (what was found is kept)"],
|
||||
["/linkcancel", "stop looking (what was found and reviewed is kept, and what was approved is linked)"],
|
||||
["/research question", "the editor searches the web, reads a few pages and writes what it finds into the focused node, each claim linked to its page (within the server's limits, by default 5 searches and 5 pages read per request; Esc stops)"],
|
||||
["", "an ordinary request to the editor may use the web too when it says so: \"look up…\", \"find sources for…\", \"search the web…\", \"cite sources\", \"fact-check\""],
|
||||
],
|
||||
@@ -311,27 +311,38 @@ export function handleKey(e: KeyboardEvent, hooks: KeyHooks) {
|
||||
if (store.mode === "review") {
|
||||
switch (k) {
|
||||
case "y":
|
||||
store.acceptSuggestion();
|
||||
store.reviewAccept();
|
||||
break;
|
||||
case "n":
|
||||
store.rejectSuggestion();
|
||||
case "D":
|
||||
store.reviewReject();
|
||||
break;
|
||||
case "s":
|
||||
case "j":
|
||||
case "ArrowDown":
|
||||
case "Tab":
|
||||
case " ":
|
||||
store.reviewStep(e.shiftKey ? -1 : 1);
|
||||
break;
|
||||
case "k":
|
||||
case "ArrowUp":
|
||||
store.reviewStep(-1);
|
||||
break;
|
||||
case "1":
|
||||
case "2":
|
||||
case "3":
|
||||
store.reviewFilter((["linked", "rejected", "pending"] as const)[+k - 1]);
|
||||
break;
|
||||
case "Y":
|
||||
store.reviewAcceptAll();
|
||||
break;
|
||||
case "Enter":
|
||||
store.reviewGo();
|
||||
break;
|
||||
case "Escape":
|
||||
case "q":
|
||||
case "S":
|
||||
store.endReview("Review stopped.");
|
||||
store.endReview();
|
||||
break;
|
||||
case "u":
|
||||
store.undoLast();
|
||||
|
||||
+216
-50
@@ -1,29 +1,62 @@
|
||||
/**
|
||||
* Link discovery as the browser sees it: asking the server to scan a node (server/links) after it
|
||||
* is written, applying the `auto` tier at once as its own commit (so `u` takes it back), keeping
|
||||
* the rest as suggestions drawn in the text, accepting and declining them, the Related list, the
|
||||
* background job's progress, and the "nearby" list a model is given before it writes.
|
||||
* is written; in `review` mode, having the model reviewer judge what was found there and making
|
||||
* the links it approved at once, as their own commit by "reviewer" (so `u` takes them back); with
|
||||
* `on`, making the scanner's `auto` tier the same way; keeping the rest as suggestions drawn in the
|
||||
* text; accepting and declining them, and removing a link for good; every determination as a row of
|
||||
* the links list (S); the Related list, the background job's progress, and the "nearby" list a
|
||||
* model is given before it writes.
|
||||
*
|
||||
* Nothing here runs on a keystroke: scans are queued after a write is saved and run one at a time.
|
||||
*/
|
||||
import type { JobState } from "../../server/links/jobs";
|
||||
import type { ReviewReport } from "../../server/links/review";
|
||||
import type { Related as RelatedRow, Suggestion as Sugg } from "../../server/links/scan";
|
||||
import { inArticles } from "../core/article";
|
||||
import { applyLinks, nodeRef } from "../core/links";
|
||||
import { applyLinks, nodeRef, phraseKey } from "../core/links";
|
||||
import type { Mark } from "../core/marks";
|
||||
import { ancestors, docOf, notesOf, type Doc, type NodeId, type Snap } from "../core/model";
|
||||
import { describeTarget, sameTarget } from "../core/ref";
|
||||
import { ancestors, docOf, isLink, label, notesOf, type Doc, type NodeId, type Op, type Snap } from "../core/model";
|
||||
import { describeTarget, sameTarget, type Ref } from "../core/ref";
|
||||
import { clip, overlaps, type Range } from "../core/text";
|
||||
import type { Nearby } from "../llm/prompts";
|
||||
|
||||
export type { JobState, Sugg };
|
||||
export type AutoMode = "on" | "suggest" | "off";
|
||||
export type { JobState, ReviewReport, Sugg };
|
||||
/** After an edit: the model reviews what was found and links what it approves (review), the sure tier is linked (on), all is suggested (suggest), nothing is looked for (off). */
|
||||
export type AutoMode = "review" | "on" | "suggest" | "off";
|
||||
|
||||
/** Where a candidate link stands: made, turned down (by the reviewer or a person), or waiting. */
|
||||
export type Status = "linked" | "rejected" | "pending";
|
||||
|
||||
/** A row of the links list: a stored suggestion, a link in the text, or a declined phrase, as it stands now. */
|
||||
export interface LinkRow {
|
||||
key: string;
|
||||
node: NodeId;
|
||||
/** Where the words are now; null for a declined phrase whose words are not known. */
|
||||
range: Range | null;
|
||||
quote: string;
|
||||
target: Ref | null;
|
||||
/** The target's title. */
|
||||
title: string;
|
||||
status: Status;
|
||||
/** Who decided: "reviewer", a person's name, or null when it is not known (a link made by hand, an old decline). */
|
||||
by: string | null;
|
||||
/** The reviewer's one-line reason, when it gave one. */
|
||||
reason: string | null;
|
||||
/** What the reviewer said, when it said something different from how things stand (a person overruled it). */
|
||||
verdict: boolean | null;
|
||||
at: number | null;
|
||||
sugg?: Sugg;
|
||||
/** The link's own note, when it is linked. */
|
||||
note?: NodeId;
|
||||
}
|
||||
|
||||
/** What the linker needs from the page's store. */
|
||||
interface Host {
|
||||
doc(): Doc;
|
||||
user(): string;
|
||||
mode(): AutoMode;
|
||||
/** Whether the server has a model (without one, review falls back to suggesting). */
|
||||
generating(): boolean;
|
||||
say(text: string): void;
|
||||
emit(...ids: NodeId[]): void;
|
||||
/** Whether a node is drawn now (its Related list is fetched only then). */
|
||||
@@ -45,10 +78,13 @@ const idle = (fn: () => void) => (typeof requestIdleCallback === "function" ? re
|
||||
const post = (path: string, body: unknown, signal?: AbortSignal) =>
|
||||
fetch(`/api/links/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal });
|
||||
|
||||
/** A suggestion as it applies to a node's text now: its words where they are, or null if they are gone or taken. */
|
||||
function place(snap: Snap, s: Sugg): Sugg | null {
|
||||
/** Turned down: declined by a person, or rejected by the reviewer and not linked by a person since. */
|
||||
const turnedDown = (snap: Snap, s: Sugg) => !!snap.nodes[s.node]?.nolink?.includes(s.key) || s.decided?.link === false || (s.review?.link === false && !s.decided?.link);
|
||||
|
||||
/** A suggestion as it applies to a node's text now: its words where they are, or null if they are gone, taken or turned down. */
|
||||
function place(snap: Snap, s: Sugg, overrule = false): Sugg | null {
|
||||
const n = snap.nodes[s.node];
|
||||
if (!n || n.nolink?.includes(s.key)) return null;
|
||||
if (!n || (!overrule && turnedDown(snap, s))) return null;
|
||||
let range = s.range;
|
||||
if (n.body.slice(range[0], range[1]) !== s.quote) {
|
||||
const at = n.body.indexOf(s.quote);
|
||||
@@ -67,8 +103,43 @@ function place(snap: Snap, s: Sugg): Sugg | null {
|
||||
return range === s.range ? s : { ...s, range };
|
||||
}
|
||||
|
||||
/** Where a stored suggestion's words are now, or null if they are gone. */
|
||||
function locate(body: string, s: Sugg): Range | null {
|
||||
if (body.slice(s.range[0], s.range[1]) === s.quote) return s.range;
|
||||
const at = body.indexOf(s.quote);
|
||||
return at < 0 ? null : [at, at + s.quote.length];
|
||||
}
|
||||
|
||||
/** A target's title, for a row. */
|
||||
function titleOf(snap: Snap, r: Ref): string {
|
||||
if (r.kind === "node") return r.id && snap.nodes[r.id] ? label(snap, r.id) : (r.path ?? []).join(" › ") || "a note";
|
||||
return r.kind === "wiki" ? r.title : (r.title ?? r.url);
|
||||
}
|
||||
|
||||
/** A stored suggestion as a row, as things stand in the text now; null if its words are gone or carry another link. */
|
||||
function rowOf(snap: Snap, s: Sugg): LinkRow | null {
|
||||
const n = snap.nodes[s.node];
|
||||
if (!n) return null;
|
||||
const range = locate(n.body, s);
|
||||
if (!range) return null;
|
||||
const base = { key: s.id, node: s.node, range, quote: s.quote, target: s.target, title: s.title, reason: s.review?.reason ?? null, sugg: s };
|
||||
for (const c of notesOf(snap, s.node)) {
|
||||
const note = snap.nodes[c];
|
||||
if (!note.ref || !note.anchors.some((a) => overlaps([a.start, a.end], range))) continue;
|
||||
if (!sameTarget(note.ref, s.target)) return null;
|
||||
const by = s.decided?.link ? s.decided.by : s.review?.link ? "reviewer" : null;
|
||||
return { ...base, status: "linked", by, verdict: s.review && by !== "reviewer" ? s.review.link : null, at: s.decided?.at ?? s.review?.at ?? null, note: c };
|
||||
}
|
||||
if (n.nolink?.includes(s.key) || s.decided?.link === false) {
|
||||
const by = s.decided?.link === false ? s.decided.by : null;
|
||||
return { ...base, status: "rejected", by, verdict: s.review ? s.review.link : null, at: s.decided?.at ?? null };
|
||||
}
|
||||
if (s.review?.link === false && !s.decided?.link) return { ...base, status: "rejected", by: "reviewer", verdict: null, at: s.review.at };
|
||||
return { ...base, status: "pending", by: null, verdict: s.review ? s.review.link : null, at: s.review?.at ?? null };
|
||||
}
|
||||
|
||||
export class Linker {
|
||||
/** Pending suggestions by node, as the scanner gave them (placed again whenever read). */
|
||||
/** Suggestions by node, as the server stores them, with what was decided about each (placed again whenever read). */
|
||||
private byNode = new Map<NodeId, Sugg[]>();
|
||||
private related = new Map<NodeId, { body: string; rows: RelatedRow[] | null; done: boolean }>();
|
||||
private queue: Task[] = [];
|
||||
@@ -106,6 +177,43 @@ export class Linker {
|
||||
return ids.flatMap((id) => this.forNode(id, snap));
|
||||
}
|
||||
|
||||
/**
|
||||
* The links list: under these nodes (in reading order), every stored suggestion as it stands, every
|
||||
* link in the text that no suggestion accounts for (made by hand, or before determinations were
|
||||
* kept), and every declined phrase no suggestion accounts for (its target was not kept).
|
||||
*/
|
||||
rows(ids: NodeId[], snap: Snap): LinkRow[] {
|
||||
const out: LinkRow[] = [];
|
||||
for (const id of ids) {
|
||||
const n = snap.nodes[id];
|
||||
if (!n) continue;
|
||||
const mine: LinkRow[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const s of this.byNode.get(id) ?? []) {
|
||||
const r = rowOf(snap, s);
|
||||
if (!r) continue;
|
||||
if (r.note && mine.some((x) => x.note === r.note)) continue;
|
||||
if (r.status === "pending" && mine.some((x) => x.status === "pending" && x.range && overlaps(x.range, r.range!))) continue;
|
||||
mine.push(r);
|
||||
seen.add(r.quote ? phraseKey(r.quote) : "");
|
||||
}
|
||||
for (const c of notesOf(snap, id)) {
|
||||
const note = snap.nodes[c];
|
||||
const a = note.anchors[0];
|
||||
if (!note.ref || !a || mine.some((x) => x.note === c)) continue;
|
||||
const quote = n.body.slice(a.start, a.end);
|
||||
mine.push({ key: `note:${c}`, node: id, range: [a.start, a.end], quote, target: note.ref, title: titleOf(snap, note.ref), status: "linked", by: null, reason: null, verdict: null, at: null, note: c });
|
||||
seen.add(phraseKey(quote));
|
||||
}
|
||||
for (const k of n.nolink ?? []) {
|
||||
if (seen.has(k) || (this.byNode.get(id) ?? []).some((s) => s.key === k)) continue;
|
||||
mine.push({ key: `nolink:${id}:${k}`, node: id, range: null, quote: k, target: null, title: "", status: "rejected", by: null, reason: null, verdict: null, at: null });
|
||||
}
|
||||
out.push(...mine.sort((a, b) => (a.range?.[0] ?? 1e9) - (b.range?.[0] ?? 1e9)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- scanning ----
|
||||
|
||||
/** Queue a scan of a node that was just written. Off the keystroke: it runs after the write is saved. */
|
||||
@@ -161,84 +269,115 @@ export class Linker {
|
||||
};
|
||||
}
|
||||
|
||||
/** The mode in effect: review needs a model, and without one is suggest. */
|
||||
effective(): AutoMode {
|
||||
const m = this.host.mode();
|
||||
return m === "review" && !this.host.generating() ? "suggest" : m;
|
||||
}
|
||||
|
||||
private async run(t: Task) {
|
||||
const doc = this.host.doc();
|
||||
const snap = doc.snap();
|
||||
if (!snap.nodes[t.node]) return;
|
||||
const res = await post("scan", this.request(snap, t.node, t.forced));
|
||||
const review = this.effective() === "review" ? (t.origin === "human" ? "unmarked" : "all") : undefined;
|
||||
const res = await post("scan", { ...this.request(snap, t.node, t.forced), ...(review ? { review } : {}) });
|
||||
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error ?? `the server answered ${res.status}`);
|
||||
const r = (await res.json()) as { suggestions: Sugg[]; unresolved: string[]; degraded: string[] };
|
||||
this.take(doc, t.node, r.suggestions, t.origin, r.unresolved, r.degraded);
|
||||
const r = (await res.json()) as { suggestions: Sugg[]; entries?: Sugg[]; apply?: Sugg[]; review?: ReviewReport; unresolved: string[]; degraded: string[] };
|
||||
this.take(doc, t.node, r, t.origin);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a scan found, applied as the mode says: with `on`, the auto tier (and verified marks) at
|
||||
* once, as one commit by "linker"; everything else waits, drawn in the text.
|
||||
* What a scan found, applied as the mode says: with `review`, the links the reviewer approved, as
|
||||
* one commit by "reviewer"; with `on`, the auto tier, as one commit by "linker"; a person's own
|
||||
* [[marks]] always, by "linker". Everything still pending waits, drawn in the text; what the
|
||||
* reviewer rejected waits behind the links list's filter.
|
||||
*/
|
||||
private take(doc: Doc, node: NodeId, list: Sugg[], origin: Origin, unresolved: string[], degraded: string[]) {
|
||||
const mode = this.host.mode();
|
||||
const snap = doc.snap();
|
||||
private take(doc: Doc, node: NodeId, r: { suggestions: Sugg[]; entries?: Sugg[]; apply?: Sugg[]; review?: ReviewReport; unresolved: string[]; degraded: string[] }, origin: Origin) {
|
||||
const mode = this.effective();
|
||||
const marked = (s: Sugg) => s.kind === "forced";
|
||||
const list = r.suggestions;
|
||||
const now = list.filter((s) => (marked(s) && (origin === "human" || mode === "on")) || (s.tier === "auto" && mode === "on"));
|
||||
const later = list.filter((s) => !now.includes(s) && !(marked(s) && mode === "off"));
|
||||
// Marks are offered only while something is looked for.
|
||||
const stored = (r.entries ?? list).filter((s) => !(marked(s) && mode === "off") && !now.some((x) => x.id === s.id));
|
||||
this.byNode.set(node, stored);
|
||||
const placed = this.applyAuto(now, doc);
|
||||
this.byNode.set(node, later);
|
||||
if (unresolved.length && origin === "human") this.host.say(`Found nothing to link for ${unresolved.map((u) => `“${clip(u, 40)}”`).join(", ")}; the brackets were taken out.`);
|
||||
else if (!placed.length && later.length && origin !== "import") this.host.say(`${later.length} link suggestion${later.length > 1 ? "s" : ""}: Tab reaches ${later.length > 1 ? "them" : "it"}, y links, n declines${degraded.length ? ` (${degraded[0]})` : ""}`);
|
||||
const approved = this.applyAuto(r.apply ?? [], doc, "reviewer");
|
||||
const later = this.forNode(node, doc.snap());
|
||||
const rep = r.review;
|
||||
const rejected = rep?.rejected ?? 0;
|
||||
if (r.unresolved.length && origin === "human") this.host.say(`Found nothing to link for ${r.unresolved.map((u) => `“${clip(u, 40)}”`).join(", ")}; the brackets were taken out.`);
|
||||
else if (approved.length) this.host.say(`${this.linkedText(approved)} · u undoes${rejected ? ` · ${rejected} rejected` : ""}${later.length ? ` · ${later.length} to review` : ""} · S lists them`);
|
||||
else if (rep?.fallback && later.length) this.host.say(`${this.fallbackText(rep.fallback)}: ${later.length} link suggestion${later.length > 1 ? "s" : ""} for you · Tab reaches ${later.length > 1 ? "them" : "it"}, y links, n declines`);
|
||||
else if (rejected && !placed.length) this.host.say(`The reviewer rejected ${rejected} link${rejected > 1 ? "s" : ""} here${later.length ? `; ${later.length} left to review` : ""} · S lists them`);
|
||||
else if (!placed.length && later.length && origin !== "import") this.host.say(`${later.length} link suggestion${later.length > 1 ? "s" : ""}: Tab reaches ${later.length > 1 ? "them" : "it"}, y links, n declines${r.degraded.length ? ` (${r.degraded[0]})` : ""}`);
|
||||
this.host.emit(node);
|
||||
}
|
||||
|
||||
/** Apply suggestions without asking, as one commit by "linker" (an ordinary commit: `u` takes it back). */
|
||||
applyAuto(list: Sugg[], doc = this.host.doc()): Sugg[] {
|
||||
/** "Reviewer unavailable (why)", for the status line. */
|
||||
fallbackText(why: string): string {
|
||||
return `Not reviewed (${why})`;
|
||||
}
|
||||
|
||||
private linkedText(placed: Sugg[]): string {
|
||||
return `Linked ${placed.map((s) => `“${clip(s.quote, 30)}” → ${clip(s.title, 40)}`).slice(0, 3).join(", ")}${placed.length > 3 ? ` and ${placed.length - 3} more` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make links without asking, as one commit (an ordinary commit: `u` takes it back): by "linker"
|
||||
* for the scanner's sure tier and a person's marks, by "reviewer" for what the reviewer approved.
|
||||
*/
|
||||
applyAuto(list: Sugg[], doc = this.host.doc(), by: "linker" | "reviewer" = "linker"): Sugg[] {
|
||||
const snap = doc.snap();
|
||||
const placed = list.map((s) => place(snap, s)).filter((s): s is Sugg => !!s);
|
||||
if (!placed.length) return [];
|
||||
const one = placed.length === 1 ? `“${clip(placed[0].quote, 40)}”` : `${placed.length} phrases`;
|
||||
const r = applyLinks(doc, placed.map((s) => ({ node: s.node, range: s.range, target: s.target })), {
|
||||
author: "linker",
|
||||
author: by,
|
||||
actor: "llm",
|
||||
tag: "autolink",
|
||||
message: `Link ${placed.length === 1 ? `“${clip(placed[0].quote, 40)}”` : `${placed.length} phrases`} automatically`,
|
||||
tag: by === "reviewer" ? "review" : "autolink",
|
||||
message: by === "reviewer" ? `Link ${one} (approved by the reviewer)` : `Link ${one} automatically`,
|
||||
});
|
||||
if (r.created.length + r.merged.length) {
|
||||
this.host.say(`Linked ${placed.map((s) => `“${clip(s.quote, 30)}” → ${clip(s.title, 40)}`).slice(0, 3).join(", ")}${placed.length > 3 ? ` and ${placed.length - 3} more` : ""} · u undoes`);
|
||||
}
|
||||
this.forget(placed);
|
||||
if (by === "linker" && r.created.length + r.merged.length) this.host.say(`${this.linkedText(placed)} · u undoes`);
|
||||
return placed;
|
||||
}
|
||||
|
||||
/** The pending list of a document from the server (what a background job found), once per page load or on demand. */
|
||||
async loadDoc(docId: NodeId, force = false): Promise<Sugg[]> {
|
||||
if (!force && this.fetched.has(docId)) return [];
|
||||
/**
|
||||
* A document's stored suggestions from the server, with what was decided about each (what a
|
||||
* background job found, and the reviewer's verdicts), once per page load or on demand. With
|
||||
* `claim`, also the links the reviewer approved that no page has made yet, handed to this one.
|
||||
*/
|
||||
async loadDoc(docId: NodeId, force = false, claim = false): Promise<{ found: Sugg[]; apply: Sugg[] }> {
|
||||
if (!force && this.fetched.has(docId)) return { found: [], apply: [] };
|
||||
this.fetched.add(docId);
|
||||
try {
|
||||
const res = await fetch(`/api/links/pending?doc=${encodeURIComponent(docId)}`);
|
||||
if (!res.ok) return [];
|
||||
const r = (await res.json()) as { suggestions: Sugg[] };
|
||||
const res = await fetch(`/api/links/pending?doc=${encodeURIComponent(docId)}&all=1${claim ? "&claim=1" : ""}`);
|
||||
if (!res.ok) return { found: [], apply: [] };
|
||||
const r = (await res.json()) as { suggestions: Sugg[]; apply?: Sugg[] };
|
||||
const by = new Map<NodeId, Sugg[]>();
|
||||
for (const s of r.suggestions) by.set(s.node, [...(by.get(s.node) ?? []), s]);
|
||||
for (const [id, list] of by) this.byNode.set(id, list);
|
||||
// Nothing to draw, nothing to redraw: a document opened is not repainted for an empty list.
|
||||
if (by.size) this.host.emit(...by.keys());
|
||||
return r.suggestions;
|
||||
return { found: r.suggestions, apply: r.apply ?? [] };
|
||||
} catch {
|
||||
return [];
|
||||
return { found: [], apply: [] };
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the writer's decisions ----
|
||||
|
||||
/** y: link these suggestions, as the writer's own commit. */
|
||||
accept(list: Sugg[]): number {
|
||||
/** y: link these suggestions, as the writer's own commit. `overrule`: even ones turned down (by the reviewer, or a person earlier). */
|
||||
accept(list: Sugg[], overrule = false): number {
|
||||
const doc = this.host.doc();
|
||||
const snap = doc.snap();
|
||||
const placed = list.map((s) => place(snap, s)).filter((s): s is Sugg => !!s);
|
||||
const placed = list.map((s) => place(snap, s, overrule)).filter((s): s is Sugg => !!s);
|
||||
if (!placed.length) return 0;
|
||||
const r = applyLinks(doc, placed.map((s) => ({ node: s.node, range: s.range, target: s.target })), {
|
||||
author: this.host.user(),
|
||||
actor: "human",
|
||||
message: placed.length === 1 ? `Link “${clip(placed[0].quote, 40)}” to ${clip(describeTarget(placed[0].target), 50)}` : `Link ${placed.length} suggested phrases`,
|
||||
});
|
||||
this.forget(placed);
|
||||
this.decide(placed, true);
|
||||
return r.created.length + r.merged.length;
|
||||
}
|
||||
|
||||
@@ -250,13 +389,40 @@ export class Linker {
|
||||
if (!byNode.size) return 0;
|
||||
const ops = [...byNode].map(([id, keys]) => ({ op: "update" as const, id, nolink: [...keys] }));
|
||||
doc.as(this.host.user(), () => doc.apply(ops, list.length === 1 ? `Decline linking “${clip(list[0].quote, 40)}”` : `Decline ${list.length} link suggestions`, { tag: "nolink" }));
|
||||
this.forget(list);
|
||||
this.decide(list, false);
|
||||
return list.length;
|
||||
}
|
||||
|
||||
private forget(list: Sugg[]) {
|
||||
const gone = new Set(list.map((s) => s.id));
|
||||
for (const [id, l] of this.byNode) this.byNode.set(id, l.filter((s) => !gone.has(s.id) && !list.some((x) => x.node === s.node && x.key === s.key)));
|
||||
/**
|
||||
* Remove a link for good: the link goes (a note that also links keeps its text and loses its
|
||||
* target), and its words' phrase is declined in its node, in one commit, so neither the scanner nor
|
||||
* the reviewer makes it again. Returns the phrase declined, or null if this is not a link.
|
||||
*/
|
||||
removeLink(note: NodeId): string | null {
|
||||
const doc = this.host.doc();
|
||||
const snap = doc.snap();
|
||||
const n = snap.nodes[note];
|
||||
const parent = n?.parent ? snap.nodes[n.parent] : undefined;
|
||||
const a = n?.anchors[0];
|
||||
if (!n?.ref || n.kind !== "note" || !parent || !a) return null;
|
||||
const quote = parent.body.slice(a.start, a.end);
|
||||
const key = phraseKey(quote);
|
||||
const ops: Op[] = [isLink(n) ? { op: "delete", id: note } : { op: "update", id: note, ref: null }];
|
||||
if (key) ops.push({ op: "update", id: parent.id, nolink: [key] });
|
||||
doc.as(this.host.user(), () => doc.apply(ops, `Remove the link on “${clip(quote, 40)}” (not to be made again here)`, { tag: "nolink" }));
|
||||
const ref = n.ref;
|
||||
this.decide((this.byNode.get(parent.id) ?? []).filter((s) => s.key === key && sameTarget(s.target, ref)), false);
|
||||
return key || quote;
|
||||
}
|
||||
|
||||
/** Record a person's decision here and on the server, so the list says who decided and the reviewer never judges it again. */
|
||||
private decide(list: Sugg[], link: boolean) {
|
||||
if (!list.length) return;
|
||||
const by = this.host.user();
|
||||
const at = Date.now();
|
||||
const ids = new Set(list.map((s) => s.id));
|
||||
for (const [, l] of this.byNode) for (const s of l) if (ids.has(s.id)) s.decided = { link, by, at };
|
||||
void post("decide", { ids: [...ids], link, by }).catch(() => {});
|
||||
this.host.emit(...new Set(list.map((s) => s.node)));
|
||||
}
|
||||
|
||||
@@ -319,7 +485,7 @@ export class Linker {
|
||||
// ---- background jobs ----
|
||||
|
||||
async startJob(scope: "doc" | "library", doc?: NodeId): Promise<JobState | string> {
|
||||
const res = await post("jobs", { scope, doc });
|
||||
const res = await post("jobs", { scope, doc, review: this.effective() === "review" });
|
||||
const r = await res.json().catch(() => ({}));
|
||||
if (!res.ok) return r.error ?? `the server answered ${res.status}`;
|
||||
this.job = r.job;
|
||||
|
||||
+190
-53
@@ -9,7 +9,7 @@
|
||||
*/
|
||||
import { UndoManager } from "loro-crdt";
|
||||
import {
|
||||
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, docOf, documents, freeSlug, isLibraryRoot, isStale, label, notesOf, sections,
|
||||
Doc, OpError, SYSTEM_ORIGIN, ancestors, descendants, docOf, documents, freeSlug, isLibraryRoot, isLink, isStale, label, notesOf, sections,
|
||||
staleness, type NodeId, type Op, type Snap,
|
||||
} from "../core/model";
|
||||
import { FormatError, serializeDoc } from "../core/format";
|
||||
@@ -35,7 +35,7 @@ import { idbGet, idbKeys, idbSet } from "./idb";
|
||||
import { remoteLLM } from "./remote";
|
||||
import { Session } from "./session";
|
||||
import { refreshAfterCalls } from "./usage";
|
||||
import { Linker, type AutoMode, type JobState, type Sugg } from "./linker";
|
||||
import { Linker, type AutoMode, type JobState, type LinkRow, type Status, type Sugg } from "./linker";
|
||||
import { all, besideInColumn, close as closeIn, columns as columnsOf, reorder, focus as focusIn, focused, open as openIn, path, pin as pinIn, prune, restore as restoreForest, rooted, save as saveTree, updateIn, withBranch, type Forest, type Placed, type Tree } from "./forks";
|
||||
import { stripMarks, type Mark } from "../core/marks";
|
||||
import { SEED_SLUG } from "../core/seed";
|
||||
@@ -184,6 +184,17 @@ const lsSet = (k: string, v: unknown) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The settings this browser stored. `review` is now the default for links found after an edit; a
|
||||
* browser that stored the old default, `suggest`, without choosing it (every setting is stored
|
||||
* together) moves to it. A mode chosen with /autolink since is kept.
|
||||
*/
|
||||
function storedSettings(): Partial<Store["settings"]> {
|
||||
const s = lsGet<Partial<Store["settings"]>>("ie:settings", {});
|
||||
if (s.autolink === "suggest" && !lsGet("ie:autolink-chosen", false)) delete s.autolink;
|
||||
return s;
|
||||
}
|
||||
|
||||
/** Article text an aux focus is in (Store.auxSpot). */
|
||||
export interface Spot {
|
||||
at: ArticleText;
|
||||
@@ -234,18 +245,22 @@ class Store {
|
||||
branchFrom: Commit | null = null;
|
||||
/** A note being previewed on hover, and where to draw it. */
|
||||
popup: { note: NodeId; x: number; top: number; bottom: number } | null = null;
|
||||
settings: { auto: boolean; speculate: boolean; view: View; autolink: AutoMode; curves: boolean; colors: Colors } = { auto: true, speculate: false, view: "auto", autolink: "suggest", curves: true, colors: "line", ...lsGet("ie:settings", {}) };
|
||||
settings: { auto: boolean; speculate: boolean; view: View; autolink: AutoMode; curves: boolean; colors: Colors } = { auto: true, speculate: false, view: "auto", autolink: "review", curves: true, colors: "line", ...storedSettings() };
|
||||
/** Link discovery: scans after writes, suggestions, Related, the background job. */
|
||||
links = new Linker({
|
||||
doc: () => this.doc,
|
||||
user: () => this.user,
|
||||
mode: () => this.settings.autolink,
|
||||
generating: () => this.generating,
|
||||
say: (t) => this.say(t),
|
||||
emit: (...ids) => this.emit(...ids),
|
||||
rendered: (id) => this.rendered(id),
|
||||
});
|
||||
/** Review mode (S): the suggestions being stepped through, and which one is on screen. */
|
||||
review: { items: Sugg[]; i: number } | null = null;
|
||||
/**
|
||||
* The links list (S): every link found or made in the current document, as it stands, under
|
||||
* filters by status; the selected row's words are focused in the text.
|
||||
*/
|
||||
review: { ids: NodeId[]; show: Record<Status, boolean>; key: string | null } | null = null;
|
||||
|
||||
/** Whether the window is wide enough for `auto` to mean panes. Kept current by the page. */
|
||||
wide = typeof window !== "undefined" && window.innerWidth >= PANES_MIN_WIDTH;
|
||||
@@ -1867,9 +1882,10 @@ class Store {
|
||||
return this.say("Note deleted. u to undo.");
|
||||
}
|
||||
if (this.focus.grain !== "node") {
|
||||
// On a selection, D removes the note anchored there.
|
||||
// On a selection, D removes the note anchored there; a link goes for good (its words are declined).
|
||||
const note = this.noteAt(this.focus.range);
|
||||
if (!note) return this.say("No note on this selection to delete. Esc to the node first to delete the node.");
|
||||
if (isLink(s.nodes[note])) return this.removeLink(note);
|
||||
this.apply([{ op: "delete", id: note }], `Delete note on “${clip(label(s, note), 40)}”`);
|
||||
this.open.delete(note);
|
||||
return this.say("Note deleted. u to undo.");
|
||||
@@ -2747,7 +2763,7 @@ class Store {
|
||||
this.applyTarget(spot, ref);
|
||||
}
|
||||
|
||||
/** /unlink: a link on the selection goes; a note there, or the node itself, loses its target and keeps its text. */
|
||||
/** /unlink: a link on the selection goes (for good: its words are declined); a note there, or the node itself, loses its target and keeps its text. */
|
||||
unlink() {
|
||||
if (!this.writable()) return;
|
||||
const spot = this.linkSpot();
|
||||
@@ -2755,10 +2771,9 @@ class Store {
|
||||
const id = spot?.range ? spot.existing : spot?.node;
|
||||
const n = id ? s.nodes[id] : undefined;
|
||||
if (!id || !n?.ref) return this.say("Nothing here links anywhere.");
|
||||
if (n.kind === "note" && !n.body.trim()) {
|
||||
this.apply([{ op: "delete", id }], `Unlink “${clip(label(s, id), 40)}”`);
|
||||
this.open.delete(id);
|
||||
} else this.apply([{ op: "update", id, ref: null }], `Remove the target of “${clip(label(s, id), 40)}”`);
|
||||
// A link on words (or a note that also links) goes for good: its words are declined in the node.
|
||||
if (n.kind === "note") return this.removeLink(id);
|
||||
this.apply([{ op: "update", id, ref: null }], `Remove the target of “${clip(label(s, id), 40)}”`);
|
||||
this.say("Unlinked. u to undo.");
|
||||
}
|
||||
|
||||
@@ -2866,7 +2881,7 @@ class Store {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
// ---- link suggestions ----
|
||||
// ---- link suggestions, and the links list ----
|
||||
|
||||
/** The suggestion the focus is on (its words exactly), if any. */
|
||||
focusedSuggestion(): Sugg | undefined {
|
||||
@@ -2875,13 +2890,12 @@ class Store {
|
||||
return this.links.at(f.node, f.range, this.snap);
|
||||
}
|
||||
|
||||
/** y on a suggestion: link it. In review, on to the next. */
|
||||
/** y on a suggestion: link it. */
|
||||
acceptSuggestion(sg = this.focusedSuggestion()) {
|
||||
if (!sg || !this.writable()) return;
|
||||
this.agentUndo = null;
|
||||
const made = this.links.accept([sg]);
|
||||
this.say(made ? `Linked “${clip(sg.quote, 40)}” to ${clip(describeTarget(sg.target), 50)} · u undoes` : "Those words could not be linked any more.");
|
||||
if (this.review) this.reviewStep(0);
|
||||
}
|
||||
|
||||
/** n on a suggestion: decline it, remembered in the node (and so on every replica). */
|
||||
@@ -2890,52 +2904,156 @@ class Store {
|
||||
this.agentUndo = null;
|
||||
this.links.reject([sg]);
|
||||
this.say(`Declined “${clip(sg.quote, 40)}”: it will not be suggested here again · u undoes`);
|
||||
if (this.review) this.reviewStep(0);
|
||||
}
|
||||
|
||||
/** S: step through the pending suggestions of the current document (or, on the library, of the focused node). */
|
||||
/** D on a link (or /unlink): remove it, and decline its words in the node so it is not made again. */
|
||||
removeLink(note: NodeId) {
|
||||
if (!this.writable()) return;
|
||||
this.agentUndo = null;
|
||||
const s = this.snap;
|
||||
const quote = s.nodes[note]?.parent ? s.nodes[s.nodes[note].parent!].body.slice(s.nodes[note].anchors[0]?.start ?? 0, s.nodes[note].anchors[0]?.end ?? 0) : "";
|
||||
const deleted = isLink(s.nodes[note]);
|
||||
if (!this.links.removeLink(note)) return this.say("Nothing here links anywhere.");
|
||||
if (deleted) this.open.delete(note);
|
||||
this.say(`Removed the link on “${clip(quote, 40)}”; it will not be made again here · u undoes`);
|
||||
}
|
||||
|
||||
/** S: the links list of the current document (or, on the library, of the focused node). It opens at once; what the server has is fetched fresh behind it. */
|
||||
startReview() {
|
||||
if (!this.writable()) return;
|
||||
const s = this.snap;
|
||||
const d = this.currentDoc;
|
||||
const ids = d ? [d, ...descendants(s, d)] : [this.focus.node];
|
||||
const items = this.links.under(ids, s);
|
||||
if (!items.length) return this.say(d ? "No link suggestions are waiting in this document. :/linkdoc looks for some." : "No link suggestions here.");
|
||||
this.review = { items, i: 0 };
|
||||
const review = { ids, show: { linked: true, pending: true, rejected: false } as Record<Status, boolean>, key: null as string | null };
|
||||
this.review = review;
|
||||
this.mode = "review";
|
||||
// The first row waiting for a decision, else the first shown.
|
||||
const first = () => {
|
||||
if (this.review !== review || review.key) return;
|
||||
const rows = this.reviewRows();
|
||||
review.key = (rows.find((r) => r.status === "pending") ?? rows[0])?.key ?? null;
|
||||
if (review.key) this.reviewShow();
|
||||
};
|
||||
first();
|
||||
this.emit();
|
||||
if (d) void this.links.loadDoc(d, true).then(() => (first(), this.emit()));
|
||||
}
|
||||
|
||||
/** Every row of the links list, whatever the filters. */
|
||||
reviewAll(): LinkRow[] {
|
||||
const r = this.review;
|
||||
return r ? this.links.rows(r.ids, this.snap) : [];
|
||||
}
|
||||
|
||||
/** The rows the filters show. */
|
||||
reviewRows(): LinkRow[] {
|
||||
const r = this.review;
|
||||
return r ? this.reviewAll().filter((x) => r.show[x.status]) : [];
|
||||
}
|
||||
|
||||
/** The selected row, if it is still shown. */
|
||||
reviewRow(): LinkRow | undefined {
|
||||
const r = this.review;
|
||||
return r ? this.reviewRows().find((x) => x.key === r.key) : undefined;
|
||||
}
|
||||
|
||||
/** Select a row (a click on it). */
|
||||
reviewSelect(key: string) {
|
||||
if (!this.review) return;
|
||||
this.review.key = key;
|
||||
this.reviewShow();
|
||||
}
|
||||
|
||||
/** Move through the review: 0 stays on the same place (after the one there was taken), ±1 skips. */
|
||||
/** j k s Tab: move through the shown rows. */
|
||||
reviewStep(delta: number) {
|
||||
const r = this.review;
|
||||
if (!r) return;
|
||||
const s = this.snap;
|
||||
// What is still pending, in order; the cursor keeps its place in the list.
|
||||
const live = r.items.map((x) => this.links.forNode(x.node, s).find((y) => y.id === x.id)).filter((x): x is Sugg => !!x);
|
||||
const current = r.items[r.i];
|
||||
const at = live.findIndex((x) => x.id === current?.id);
|
||||
r.items = live;
|
||||
r.i = at >= 0 ? at + delta : r.i;
|
||||
if (!live.length || r.i >= live.length) return this.endReview(live.length ? "End of the suggestions." : "No suggestions left.");
|
||||
r.i = Math.max(0, r.i);
|
||||
const rows = this.reviewRows();
|
||||
if (!rows.length) return this.reviewShow();
|
||||
const at = rows.findIndex((x) => x.key === r.key);
|
||||
r.key = rows[Math.max(0, Math.min(rows.length - 1, at < 0 ? 0 : at + delta))].key;
|
||||
this.reviewShow();
|
||||
}
|
||||
|
||||
private reviewShow() {
|
||||
const r = this.review!;
|
||||
const sg = r.items[r.i];
|
||||
this.go(sg.node, "word", sg.range);
|
||||
this.status = `review ${r.i + 1}/${r.items.length}: “${clip(sg.quote, 40)}” → ${clip(sg.title, 50)} · y link · n decline · s skip · Y link all · Esc stop`;
|
||||
this.emit();
|
||||
/** 1 2 3: show or hide the linked, the turned down, the waiting. */
|
||||
reviewFilter(status: Status) {
|
||||
const r = this.review;
|
||||
if (!r) return;
|
||||
const keep = this.reviewRow();
|
||||
r.show = { ...r.show, [status]: !r.show[status] };
|
||||
const rows = this.reviewRows();
|
||||
r.key = (keep && r.show[keep.status] ? keep : rows[0])?.key ?? null;
|
||||
this.reviewShow();
|
||||
}
|
||||
|
||||
/** Y in review: link every suggestion still in the review, as one commit. */
|
||||
reviewAcceptAll() {
|
||||
/** After a row was decided: it may have left the filter; keep the place in the list. */
|
||||
private reviewAfter(before: LinkRow[], key: string | null) {
|
||||
const r = this.review;
|
||||
if (!r || !this.writable()) return;
|
||||
const made = this.links.accept(r.items.slice(r.i));
|
||||
this.endReview(`Linked ${made} phrase${made === 1 ? "" : "s"} · u undoes`);
|
||||
if (!r) return;
|
||||
const rows = this.reviewRows();
|
||||
if (!rows.some((x) => x.key === key)) {
|
||||
const at = before.findIndex((x) => x.key === key);
|
||||
const next = before.slice(at + 1).find((x) => rows.some((y) => y.key === x.key)) ?? rows[rows.length - 1];
|
||||
r.key = next?.key ?? null;
|
||||
}
|
||||
this.reviewShow(false);
|
||||
}
|
||||
|
||||
/** y in the list: link the selected row (waiting, or turned down: a person overrules). */
|
||||
reviewAccept() {
|
||||
const row = this.reviewRow();
|
||||
if (!row || !this.writable()) return;
|
||||
if (row.status === "linked") return this.say("That is linked already. n removes it.");
|
||||
if (!row.sugg) return this.say(`No target was kept for “${clip(row.quote, 40)}”, declined before targets were kept: Enter goes to it, and w links it by hand.`);
|
||||
const before = this.reviewRows();
|
||||
this.agentUndo = null;
|
||||
const made = this.links.accept([row.sugg], row.status === "rejected");
|
||||
this.say(made ? `Linked “${clip(row.quote, 40)}” to ${clip(row.title, 50)}${row.status === "rejected" ? `, over the ${row.by === "reviewer" ? "reviewer's" : "earlier"} no` : ""} · u undoes` : "Those words could not be linked any more.");
|
||||
this.reviewAfter(before, row.key);
|
||||
}
|
||||
|
||||
/** n (or D) in the list: decline the selected row if it waits; remove its link, for good, if it is linked. */
|
||||
reviewReject() {
|
||||
const row = this.reviewRow();
|
||||
if (!row || !this.writable()) return;
|
||||
if (row.status === "rejected") return this.say("That is rejected already. y links it.");
|
||||
const before = this.reviewRows();
|
||||
this.agentUndo = null;
|
||||
if (row.status === "linked" && row.note) this.removeLink(row.note);
|
||||
else if (row.sugg) {
|
||||
this.links.reject([row.sugg]);
|
||||
this.say(`Declined “${clip(row.quote, 40)}”: it will not be suggested here again · u undoes`);
|
||||
}
|
||||
this.reviewAfter(before, row.key);
|
||||
}
|
||||
|
||||
/** Y in the list: link every waiting row it shows, as one commit. */
|
||||
reviewAcceptAll() {
|
||||
if (!this.review || !this.writable()) return;
|
||||
const list = this.reviewRows().flatMap((x) => (x.status === "pending" && x.sugg ? [x.sugg] : []));
|
||||
if (!list.length) return this.say("Nothing shown is waiting to be linked.");
|
||||
const before = this.reviewRows();
|
||||
const key = this.review.key;
|
||||
const made = this.links.accept(list);
|
||||
this.say(`Linked ${made} phrase${made === 1 ? "" : "s"} · u undoes`);
|
||||
this.reviewAfter(before, key);
|
||||
}
|
||||
|
||||
/** Enter in the list: put it away and stay at the selected row's words. */
|
||||
reviewGo() {
|
||||
const row = this.reviewRow();
|
||||
this.endReview();
|
||||
if (row && !row.range) this.go(row.node, "node");
|
||||
}
|
||||
|
||||
/** Focus the selected row's words in the text, and say where the list is. */
|
||||
private reviewShow(clear = true) {
|
||||
const row = this.reviewRow();
|
||||
if (row?.range && this.snap.nodes[row.node]) this.go(row.node, "word", row.range);
|
||||
else if (row && this.snap.nodes[row.node]) this.go(row.node, "node");
|
||||
// Moving clears what was said; after a decision, what was said stays.
|
||||
if (clear) this.status = "";
|
||||
this.emit();
|
||||
}
|
||||
|
||||
endReview(message = "") {
|
||||
@@ -2962,10 +3080,16 @@ class Store {
|
||||
}
|
||||
|
||||
setAutolink(arg: string) {
|
||||
if (!["on", "suggest", "off"].includes(arg)) return this.say(`/autolink on|suggest|off (now ${this.settings.autolink}): on links the sure ones at once, suggest leaves all to you, off looks for nothing`);
|
||||
if (!["review", "on", "suggest", "off"].includes(arg)) return this.say(`/autolink review|suggest|on|off (now ${this.settings.autolink}): review has the model judge what is found and links what it approves, suggest leaves all to you, on links the scanner's sure ones unreviewed, off looks for nothing`);
|
||||
this.settings = { ...this.settings, autolink: arg as AutoMode };
|
||||
lsSet("ie:settings", this.settings);
|
||||
this.say(arg === "on" ? "autolink on: sure links are made at once (u undoes); the rest are suggested" : arg === "suggest" ? "autolink suggest: links are only suggested; y takes one, S reviews them" : "autolink off: nothing is scanned automatically");
|
||||
lsSet("ie:autolink-chosen", true);
|
||||
this.say(
|
||||
arg === "review" ? `autolink review: the model judges what is found and links what it approves (u undoes); S lists every decision${this.generating ? "" : " · no model on this server, so for now links are only suggested"}`
|
||||
: arg === "on" ? "autolink on: the scanner's sure links are made at once, unreviewed (u undoes); the rest are suggested"
|
||||
: arg === "suggest" ? "autolink suggest: links are only suggested; y takes one, S lists them"
|
||||
: "autolink off: nothing is scanned automatically",
|
||||
);
|
||||
}
|
||||
|
||||
/** /colors: where each fork's colour shows in the panes view. */
|
||||
@@ -2986,20 +3110,30 @@ class Store {
|
||||
|
||||
async cancelLinkJob() {
|
||||
const ok = await this.links.cancelJob();
|
||||
this.say(ok ? "Stopped looking for links. What was found so far is kept: S reviews it." : "No link search is running.");
|
||||
this.say(ok ? "Stopped looking for links. What was found and reviewed so far is kept: S lists it." : "No link search is running.");
|
||||
}
|
||||
|
||||
/** The status line's account of a job. */
|
||||
jobText(j: JobState): string {
|
||||
/** The status line's account of a job; `made`, once it is over, the links the reviewer approved that this page made. */
|
||||
jobText(j: JobState, made?: number): string {
|
||||
const eta = j.etaSec ? ` · about ${j.etaSec < 90 ? `${j.etaSec} s` : `${Math.round(j.etaSec / 60)} min`} left` : "";
|
||||
const slow = j.slow && j.state === "running" ? " · Wikipedia is asked once every 6.5 s without a contact: start the server with IE_WIKI_CONTACT (an email, https:// URL or User:Name) for about 6× faster" : "";
|
||||
if (j.state === "running") return `looking for links in ${clip(j.title, 40)}: ${j.done}/${j.total}${eta} · :/linkcancel stops${slow}`;
|
||||
if (j.state === "done") return `Looked for links in ${clip(j.title, 40)}: ${j.auto} sure, ${j.suggest} to review · S reviews them`;
|
||||
if (j.state === "cancelled") return `Stopped looking for links in ${clip(j.title, 40)} at ${j.done}/${j.total}.`;
|
||||
const r = j.review;
|
||||
const fell = r?.fallback ? ` · ${this.links.fallbackText(r.fallback)}: ${r.left} left for you` : "";
|
||||
if (j.state === "running") {
|
||||
const rev = r ? ` · reviewer ${r.calls}/${r.max} calls, ${r.approved} approved, ${r.rejected} rejected` : "";
|
||||
return `looking for links in ${clip(j.title, 40)}: ${j.done}/${j.total}${eta}${rev}${fell} · :/linkcancel stops${slow}`;
|
||||
}
|
||||
const verdicts = r ? `${made ?? r.approved} linked by the reviewer, ${r.rejected} rejected${r.left ? `, ${r.left} to review` : ""} · ${r.calls} model call${r.calls === 1 ? "" : "s"}${r.fallback ? ` · ${this.links.fallbackText(r.fallback)}` : ""}${made ? " · u undoes" : ""}` : "";
|
||||
if (j.state === "done") return `Looked for links in ${clip(j.title, 40)}: ${r ? verdicts : `${j.auto} sure, ${j.suggest} to review`} · S lists them`;
|
||||
if (j.state === "cancelled") return `Stopped looking for links in ${clip(j.title, 40)} at ${j.done}/${j.total}${r ? `: ${verdicts}` : "."}`;
|
||||
return `Looking for links failed: ${j.message ?? "unknown error"}`;
|
||||
}
|
||||
|
||||
/** A job's progress, from the server's notices. When it ends, what it found is fetched; with autolink on, the sure ones are applied (u undoes). */
|
||||
/**
|
||||
* A job's progress, from the server's notices. When it ends (or is stopped), what it found is
|
||||
* fetched; in review mode the links the reviewer approved are made, as one commit by "reviewer";
|
||||
* with autolink on, the sure ones, by "linker" (u undoes either).
|
||||
*/
|
||||
jobUpdate(j: JobState) {
|
||||
const before = this.links.job;
|
||||
this.links.job = j;
|
||||
@@ -3010,12 +3144,15 @@ class Store {
|
||||
if (before?.id === j.id && before.state !== "running") return;
|
||||
void (async () => {
|
||||
const docs = j.doc ? [j.doc] : documents(this.doc.snap());
|
||||
const found = (await Promise.all(docs.map((d) => this.links.loadDoc(d, true)))).flat();
|
||||
if (j.state === "done" && this.settings.autolink === "on") {
|
||||
const sure = found.filter((x) => x.tier === "auto");
|
||||
const claim = !!j.review && this.links.effective() === "review";
|
||||
const got = await Promise.all(docs.map((d) => this.links.loadDoc(d, true, claim)));
|
||||
let made: number | undefined;
|
||||
if (claim) made = this.links.applyAuto(got.flatMap((g) => g.apply), this.doc, "reviewer").length;
|
||||
else if (j.state === "done" && this.settings.autolink === "on") {
|
||||
const sure = got.flatMap((g) => g.found).filter((x) => x.tier === "auto" && !x.review && !x.decided);
|
||||
if (sure.length) this.links.applyAuto(sure);
|
||||
}
|
||||
this.say(this.jobText(j));
|
||||
this.say(this.jobText(j, made));
|
||||
})();
|
||||
}
|
||||
|
||||
|
||||
@@ -222,6 +222,19 @@ article.preview { opacity: 0.92; }
|
||||
.item .line { display: flex; gap: 0.6em; align-items: baseline; }
|
||||
.item .msg { flex: 1; }
|
||||
.item .sub { color: var(--faint); font-size: 0.64rem; }
|
||||
/* The links list (S): quiet toggles, then a row per link found or made. */
|
||||
.lfilters { padding: 0.45rem 0 0.35rem; font-size: 0.66rem; color: var(--faint); border-bottom: 1px solid var(--hair); margin-bottom: 0.3rem; }
|
||||
.lfilter { font: inherit; background: none; border: 0; padding: 0; cursor: pointer; color: var(--fg); }
|
||||
.lfilter kbd { font-family: var(--mono); font-size: 0.58rem; color: var(--faint); margin-right: 0.15em; }
|
||||
.lfilter .n { color: var(--dim); font-variant-numeric: tabular-nums; }
|
||||
.lfilter.off { color: var(--faint); text-decoration: line-through; text-decoration-color: var(--rule); }
|
||||
.lrow .lq { font-family: var(--serif); }
|
||||
.lrow .lt { color: var(--dim); }
|
||||
.lrow .lmark { font-size: 0.56rem; vertical-align: super; margin-left: 0.15em; color: var(--faint); }
|
||||
.lrow.rejected .lq, .lrow.rejected .lt { color: var(--faint); }
|
||||
.lrow .sub { overflow-wrap: anywhere; }
|
||||
.lrow .lwhere { color: var(--dim); }
|
||||
.lempty { color: var(--faint); margin: 0.8rem 0.45rem; }
|
||||
.hash { font-family: var(--mono); font-size: 0.62rem; color: var(--faint); flex: none; }
|
||||
/* The documents a commit touched. */
|
||||
.item .docs { color: var(--dim); font-size: 0.62rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
@@ -83,6 +83,13 @@ describe("actions", () => {
|
||||
expect(labels(link).slice(1, 8)).toEqual(["Copy", "--", "Open the link beside", "Open it in place", "Open on wikipedia.org", "Retarget…", "Remove the link"]);
|
||||
expect(find(link, "Open it in place")).toMatchObject({ key: "Enter", shift: true, keyText: "⇧⏎" });
|
||||
expect(labels(link)).not.toContain("Link to…");
|
||||
// Removing a link is D, and says it is for good; a library link the same; a note that also links can lose only its target.
|
||||
expect(find(link, "Remove the link")).toMatchObject({ key: "D", sub: "and do not link these words again here" });
|
||||
expect(find(selectionEntries(sel({ link: "node" }), act), "Remove the link")).toMatchObject({ key: "D" });
|
||||
const both = selectionEntries(sel({ link: "wiki", note: true }), act);
|
||||
expect(find(both, "Delete the note")).toMatchObject({ key: "D" });
|
||||
find(both, "Remove the link, keep the note").run();
|
||||
expect(calls).toContain("command /unlink");
|
||||
// In an article: no linking by hand, no Related.
|
||||
const art = selectionEntries(sel({ article: true, related: [{ title: "Nodes" }] }), act);
|
||||
expect(labels(art)).not.toContain("Link to…");
|
||||
@@ -138,7 +145,8 @@ describe("actions", () => {
|
||||
expect(colors.options.map((o) => `${o.label}${o.on ? "*" : ""}`)).toEqual(["line*", "top", "edge", "off"]);
|
||||
colors.options[3].run();
|
||||
expect(calls.at(-1)).toBe("command /colors off");
|
||||
expect(labels(topEntries(top({ doc: false }), act))).not.toContain("Review suggested links");
|
||||
expect(labels(topEntries(top({ doc: false }), act))).not.toContain("Links found: review and reverse");
|
||||
expect(labels(topEntries(top(), act))).toContain("Links found: review and reverse");
|
||||
});
|
||||
|
||||
it("tidy leaves no separator at an end or next to another", () => {
|
||||
|
||||
Reference in new issue
Block a user