From b78696fd381b49bab9a935e328605f8685359460 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:47:08 -0500 Subject: [PATCH 1/7] feat(prototype): edit and withdraw a sent note on the notes host A sent note could only be corrected or taken back by sending a second, contradicting note. Its row now has Edit and Withdraw. - POST /api/note/edit takes {"edit": seq, "text"} ($defs/edit): the text replaces the note's own in the log under the same seq, and the edit is logged as an event of its own naming the note, so the watcher wakes and the session reads it as that note edited, not a new note. - POST /api/note/withdraw takes {"withdraw": seq} ($defs/withdraw): the note stays in the log and that event alone marks it withdrawn. Storing a withdrawn flag on the note record would fail note.schema.json (additionalProperties false), which the host page's reload, relocation and import all re-check, and old logs carry no such event, so they load unchanged. - One is_note predicate replaces the "change" not in e checks, so an edit or withdraw event is never listed as a note. A withdrawn note, and the events changing it, leave status and the watcher's unhandled set; its withdraw stays. The bridge refuses an edit, move or second withdraw of a withdrawn note. record_change, record_edit and record_withdraw share one record_naming. - The note text limit moves to $defs/text so the note and the edit share it; x-version 8. - Host page: Edit opens the editor on the sent note (no Save draft, no composer reshape, which would demote or only reshape the copy), Send posts the edit; Withdraw lists the note as Withdrawn with no actions or marker and leaves it out of Copy all notes. sendDrafts closes the editor only when the entry it edits was in the batch. Closes #17956 Co-Authored-By: Claude Opus 5.5 --- ...-17956-edit-withdraw-sent-note-22d27f7e.md | 7 ++ docs/contracts/ui-feedback/README.md | 10 ++ lib/ui-feedback/fixtures/notes.json | 26 +++++ lib/ui-feedback/host.html | 7 +- lib/ui-feedback/host.mjs | 67 ++++++++---- lib/ui-feedback/note-model.test.mjs | 8 ++ lib/ui-feedback/note.schema.json | 25 ++++- lib/ui-feedback/notes_bridge.py | 80 +++++++++++--- lib/ui-feedback/test_notes_bridge.py | 101 +++++++++++++++++- plugins/prototype/notes-bridge/host.html | 7 +- plugins/prototype/notes-bridge/host.mjs | 67 ++++++++---- .../prototype/notes-bridge/note.schema.json | 25 ++++- .../prototype/notes-bridge/notes_bridge.py | 80 +++++++++++--- .../explore-directions/reference/feedback.md | 6 ++ .../scripts/notes-edit-browser-take.js | 56 ++++++++++ .../scripts/notes-edit-browser.test.sh | 44 ++++++++ 16 files changed, 538 insertions(+), 78 deletions(-) create mode 100644 .changes/prototype/fix-17956-edit-withdraw-sent-note-22d27f7e.md create mode 100644 plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js create mode 100755 plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh diff --git a/.changes/prototype/fix-17956-edit-withdraw-sent-note-22d27f7e.md b/.changes/prototype/fix-17956-edit-withdraw-sent-note-22d27f7e.md new file mode 100644 index 0000000000..8f19c8ec18 --- /dev/null +++ b/.changes/prototype/fix-17956-edit-withdraw-sent-note-22d27f7e.md @@ -0,0 +1,7 @@ +--- +bump: minor +--- + +### Added + +- A sent note on the notes host page now has Edit and Withdraw. An edit goes to the session as that note's new text under the same seq (`POST /api/note/edit`); a withdraw tells the session and lists the note as withdrawn, not pending, with no marker, and leaves it out of `status`, the watcher's unhandled notes and Copy all notes (`POST /api/note/withdraw`, `note.schema.json` x-version 8). diff --git a/docs/contracts/ui-feedback/README.md b/docs/contracts/ui-feedback/README.md index 430c0741e7..4a468d5d7a 100644 --- a/docs/contracts/ui-feedback/README.md +++ b/docs/contracts/ui-feedback/README.md @@ -75,6 +75,16 @@ current box. The bridge also logs the change as an event of its own, which wakes the session reads it as that note changed, not as a new note. The host page lists no row for a change. +A sent note can also be edited or withdrawn from its row. An edit goes to `POST /api/note/edit` as +`{"edit": , "text": ...}` (`$defs/edit`): the text replaces the note's own in the log, under +the same seq. A withdraw goes to `POST /api/note/withdraw` as `{"withdraw": }` +(`$defs/withdraw`): the note stays in the log, and that event alone marks it withdrawn, so a log +written before withdraws loads unchanged. Each is logged as an event of its own naming the note, +which wakes the watcher. The bridge refuses an edit, a change or a second withdraw of a withdrawn +note. A withdrawn note is not pending: `status` and the watcher leave it and the events changing it +out, and keep its withdraw; the host page lists it as withdrawn, draws no marker for it, and leaves +it out of Copy all notes. + A move arrow (`kind` `move`) says "move this element to there". The person picks the element to move, then where it should go: the element clicked, or a point alone when no element fits (Shift and a click). `anchor` and `rect` are the element to move. `to.point` is the destination in diff --git a/lib/ui-feedback/fixtures/notes.json b/lib/ui-feedback/fixtures/notes.json index 820bf69be4..d7f601d22f 100644 --- a/lib/ui-feedback/fixtures/notes.json +++ b/lib/ui-feedback/fixtures/notes.json @@ -1954,5 +1954,31 @@ } } ] + }, + "edits": { + "valid": [ + { "why": "a sent note's new text", "edit": { "edit": 1, "text": "Bolder parcel ids, and larger." } }, + { "why": "text at its 4000-character limit", "edit": { "edit": 500, "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } } + ], + "invalid": [ + { "why": "no note seq", "edit": { "text": "x" } }, + { "why": "a note seq of 0", "edit": { "edit": 0, "text": "x" } }, + { "why": "a note seq that is true", "edit": { "edit": true, "text": "x" } }, + { "why": "no text", "edit": { "edit": 1 } }, + { "why": "empty text", "edit": { "edit": 1, "text": "" } }, + { "why": "text over 4000 characters", "edit": { "edit": 1, "text": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" } }, + { "why": "a field an edit does not carry", "edit": { "edit": 1, "text": "x", "kind": "element" } } + ] + }, + "withdraws": { + "valid": [ + { "why": "a sent note's seq", "withdraw": { "withdraw": 1 } } + ], + "invalid": [ + { "why": "no note seq", "withdraw": {} }, + { "why": "a note seq of 0", "withdraw": { "withdraw": 0 } }, + { "why": "a note seq that is a string", "withdraw": { "withdraw": "1" } }, + { "why": "a field a withdraw does not carry", "withdraw": { "withdraw": 1, "text": "x" } } + ] } } diff --git a/lib/ui-feedback/host.html b/lib/ui-feedback/host.html index 7f4059682f..ab9db14001 100644 --- a/lib/ui-feedback/host.html +++ b/lib/ui-feedback/host.html @@ -15,7 +15,10 @@ run's token, never on the server, so a reload of the same run lists it again. The run's sent notes come back from /api/notes, the token in the request's header, each kept only as note.schema.json admits it. A region note, a draft or sent, can be moved or resized from the editor or its row; a sent one's - new anchor, rect and elements go to /api/note/change, which tells the session that note changed. Hovering a row draws its note's box in the frame, and clicking a row or its marker restores the + new anchor, rect and elements go to /api/note/change, which tells the session that note changed. A sent + note's Edit sends its new text to /api/note/edit and its Withdraw to /api/note/withdraw, each naming + the note's seq; a withdrawn note is listed as withdrawn, with no marker and no actions, and left out + of Copy all notes. Hovering a row draws its note's box in the frame, and clicking a row or its marker restores the note's view and keeps the box drawn; the frame gets keys, a path and a box, never note text. The Controls tab renders the framed page's controls manifest, kept only when controls.schema.json admits it, through the registry in controls.js, beside the content sets the page marks, and the Sample data menu lists the data @@ -161,6 +164,8 @@ .st { display: flex; flex-wrap: wrap; gap: 4px 12px; margin-block-start: 6px; font-size: 12px; color: var(--uif-ink-2); } .st .s-draft { color: var(--uif-draft); font-weight: 600; } .st .s-handled { color: var(--uif-ok); font-weight: 600; } + .st .s-withdrawn { color: var(--uif-ink-2); font-weight: 600; } + .note.withdrawn .text { color: var(--uif-ink-2); text-decoration: line-through; } .reply { margin-block: 8px 0; margin-inline: 0; padding-block: 6px; padding-inline: 10px; border-inline-start: 3px solid var(--uif-accent); background: var(--uif-sunk); border-radius: 0 var(--uif-r-s) var(--uif-r-s) 0; font-size: 13px; overflow-wrap: anywhere; diff --git a/lib/ui-feedback/host.mjs b/lib/ui-feedback/host.mjs index 45e3a5d686..fcf0b5cabc 100644 --- a/lib/ui-feedback/host.mjs +++ b/lib/ui-feedback/host.mjs @@ -233,6 +233,8 @@ function viewWords(n) { } /** A row's number, as its marker shows it: the seq once sent, D1, D2... for drafts, null for a note no marker shows. */ +/** Whether a sent note was withdrawn, here or, after a reload, as the bridge reports. */ +const gone = (m) => Boolean(m && (m.withdrawn || last.notes.some((n) => n.seq === m.seq && n.withdrawn))); const numberOf = (m) => m.seq ?? (m.draft ? `D${mine.filter((x) => x.draft).indexOf(m) + 1}` : null); /** What the frame needs to find a note's box and restore its view: contract keys, a path and a box, never its text. */ function noteTarget(m) { @@ -306,9 +308,11 @@ function openComposer(note, from, entry = null) { setPick(null); if ($("panel").hidden) setPanel(true); selectTab(tabs[0], false); - $("composer-label").textContent = entry ? `Edit draft ${numberOf(entry)}` : "New note"; + const sent = entry?.seq != null; + $("composer-label").textContent = entry ? `Edit ${sent ? "note" : "draft"} ${numberOf(entry)}` : "New note"; $("picked").textContent = `${{ element: "Picked", text: "Selected", region: "Marked", move: "Arrow" }[note.kind]}: ${where(note)}`; - $("reshape").hidden = note.kind !== "region"; + $("reshape").hidden = note.kind !== "region" || sent; + $("save").hidden = sent; composer.hidden = false; text.value = entry ? entry.note.text : ""; text.focus(); @@ -363,6 +367,7 @@ async function send() { if (!draft || sending) return; const note = written("sent"); if (!note) return; + if (editing?.seq != null) return edited(editing, note.text); const entry = editing || { id: ++ids }; Object.assign(entry, { note, where: where(note), seq: null, parts: null, asked: null }); const got = await deliver(entry); @@ -396,7 +401,7 @@ async function sendDrafts(list) { sent.push(entry.seq); } const refusal = got === "refused" ? ` ${$("status").textContent}` : ""; - if (editing && !editing.draft) closeComposer(); + if (editing && !editing.draft && list.includes(editing)) closeComposer(); render(); if (noSession) say(OFFLINE); else if (sent.length) say((sent.length === 1 ? `Note ${sent[0]} sent.` : `Notes ${sent.join(", ")} sent.`) + refusal); @@ -436,7 +441,7 @@ async function reshaped(note) { return; } toFrame({ type: "release" }); - if (target.seq !== null && (await deliverChange(target.seq, moved)) !== "sent") return; + if (target.seq !== null && (await deliverNaming("change", { change: target.seq, ...moved }, "moved", "keeps its region")) !== "sent") return; target.note = { ...target.note, ...moved }; target.where = where(target.note); target.parts = target.asked = null; @@ -445,27 +450,46 @@ async function reshaped(note) { document.querySelector(`[data-key="reshape-${target.id}"]`)?.focus(); say(target.seq !== null ? `Note ${target.seq}'s region moved; Claude is told.` : "The region moved."); } -/** Post a sent region note's new anchor, rect and elements; "sent" once the session's log has the change. */ -async function deliverChange(seq, moved) { +/** Post an event naming a sent note to /api/note/: a region's change, an edit or a withdraw; + * "sent" once the session's log has it. */ +async function deliverNaming(path, msg, verb, kept) { if (sending) return "busy"; sending = true; let r, body; try { - r = await fetch("/api/note/change", { + r = await fetch(`/api/note/${path}`, { method: "POST", headers: { "Content-Type": "application/json", "X-Notes-Token": token }, - body: JSON.stringify({ change: seq, ...moved }), + body: JSON.stringify(msg), }); body = await r.json(); } catch { - say(`Not moved: no session is answering, so note ${seq} keeps its region.`); + say(`Not ${verb}: no session is answering, so note ${msg[path]} ${kept}.`); return "offline"; } finally { sending = false; } - if (!r.ok) { say(`Not moved: ${body.error || r.status}.`); return "refused"; } + if (!r.ok) { say(`Not ${verb}: ${body.error || r.status}.`); return "refused"; } return "sent"; } +/** A sent note's new text replaces its own here and in the session's log, under the same seq. */ +async function edited(entry, words) { + if ((await deliverNaming("edit", { edit: entry.seq, text: words }, "edited", "keeps its text")) !== "sent") return; + entry.note = { ...entry.note, text: words }; + render(); + closeComposer(); + say(`Note ${entry.seq} edited; Claude is told.`); +} +/** Take a sent note back: the session is told, and the list shows it withdrawn, not pending. */ +async function withdraw(entry) { + if ((await deliverNaming("withdraw", { withdraw: entry.seq }, "withdrawn", "stays sent")) !== "sent") return; + entry.withdrawn = true; + if (editing === entry) closeComposer(); + if (chosen === entry) unchoose(true); + render(); + $("notes-title").focus(); + say(`Note ${entry.seq} withdrawn; Claude is told.`); +} /** Show or hide the notes popover over the mockup; the frame keeps its size. The Notes button stays, and gets the focus back when the popover closes. */ function setPanel(open) { @@ -514,7 +538,7 @@ function copyAll() { $("copy-button").focus(); if ($("panel").hidden) setPanel(true); selectTab(tabs[0], false); - const notes = mine.filter((m) => !m.draft); + const notes = mine.filter((m) => !m.draft && !gone(m)); if (!notes.length) return say("No notes on this page yet; a draft goes in once it is sent."); const body = JSON.stringify({ notes: notes.map((m) => m.note) }, null, 1).replace(/`/g, "\\u0060"); const block = "```prototype-notes\n" + body + "\n```\n"; @@ -536,12 +560,12 @@ function render() { const byseq = new Map(last.notes.map((n) => [n.seq, n])); const ours = new Map(mine.filter((m) => m.seq !== null).map((m) => [m.seq, m])); const seqs = [...new Set([...ours.keys(), ...byseq.keys()])].sort((a, b) => a - b); - const statusOf = (st) => (st.handled ? "Handled" : st.delivered ? "Claude has it" : "Sent") + (st.reply ? ", with a reply" : ""); + const statusOf = (st) => (st.withdrawn ? "Withdrawn" : st.handled ? "Handled" : st.delivered ? "Claude has it" : "Sent") + (st.reply ? ", with a reply" : ""); const changed = []; for (const seq of ours.keys()) { const st = byseq.get(seq); if (!st) continue; - const now = statusOf(st); + const now = statusOf({ ...st, withdrawn: gone(ours.get(seq)) }); if (shown.has(seq) && shown.get(seq) !== now) changed.push(`Note ${seq}: ${now}`); shown.set(seq, now); } @@ -595,13 +619,20 @@ function render() { n: numberOf(m), selector: "", rect: { x: m.note.rect?.x ?? 0, y: m.note.rect?.y ?? 0 }, ...(m.note.variant && { variant: m.note.variant.key }), ...(m.note.state && { state: m.note.state.key }), }); - toFrame({ type: "pins", pins: [...mine.filter((m) => m.seq !== null), ...drafts].map(pin) }); + toFrame({ type: "pins", pins: [...mine.filter((m) => m.seq !== null && !gone(m)), ...drafts].map(pin) }); askNames(); const sentRows = seqs.map((seq) => { const m = ours.get(seq); - const st = byseq.get(seq) || {}; - const status = [statusOf(st), st.handled ? "s-handled" : ""]; - return item(seq, m ? readerName(m.note, m.parts) : "Sent earlier", m ? m.note.text : "", status, m ? viewWords(m.note) : "", st.reply, reshapes(m), m); + const st = { ...byseq.get(seq), ...(gone(m) && { withdrawn: true }) }; + const status = [statusOf(st), st.withdrawn ? "s-withdrawn" : st.handled ? "s-handled" : ""]; + const acts = !m || st.withdrawn ? [] : [ + button("Edit", `edit-${m.id}`, () => openComposer(m.note, control(`edit-${m.id}`), m)), + button("Withdraw", `withdraw-${m.id}`, () => withdraw(m)), + ...reshapes(m), + ]; + const li = item(seq, m ? readerName(m.note, m.parts) : "Sent earlier", m ? m.note.text : "", status, m ? viewWords(m.note) : "", st.reply, acts, m); + li.classList.toggle("withdrawn", Boolean(st.withdrawn)); + return li; }); const unsent = mine.filter((m) => m.seq === null).map((m) => (m.draft ? item(numberOf(m), readerName(m.note, m.parts), m.note.text, ["Draft, not sent", "s-draft"], viewWords(m.note), null, [ @@ -620,7 +651,7 @@ function render() { $("notes").replaceChildren(...(filter === "draft" ? draftRows : filter === "sent" ? sentRows : [...sentRows, ...unsent])); $("empty").hidden = counts.all > 0; $("count").textContent = String(counts.all); - $("copy-count").textContent = String(counts.sent + unsent.length - drafts.length); + $("copy-count").textContent = String(counts.sent + unsent.length - drafts.length - mine.filter((m) => m.seq !== null && gone(m)).length); $("dock").setAttribute("aria-label", `Notes, ${counts.all}`); $("drafts").textContent = drafts.length ? `${drafts.length} draft${drafts.length > 1 ? "s" : ""} not sent.` : ""; $("sendall").hidden = !drafts.length; diff --git a/lib/ui-feedback/note-model.test.mjs b/lib/ui-feedback/note-model.test.mjs index 5f8e2ec0dc..6cc819edf4 100644 --- a/lib/ui-feedback/note-model.test.mjs +++ b/lib/ui-feedback/note-model.test.mjs @@ -23,6 +23,14 @@ for (const { why, change } of fixtures.changes.valid) { for (const { why, change } of fixtures.changes.invalid) { test(`refuses the change: ${why}`, () => assert.notDeepEqual(problems(change, schema, schema.$defs.change, "change"), [])); } +for (const kind of ["edit", "withdraw"]) { + for (const c of fixtures[`${kind}s`].valid) { + test(`accepts the ${kind}: ${c.why}`, () => assert.deepEqual(problems(c[kind], schema, schema.$defs[kind], kind), [])); + } + for (const c of fixtures[`${kind}s`].invalid) { + test(`refuses the ${kind}: ${c.why}`, () => assert.notDeepEqual(problems(c[kind], schema, schema.$defs[kind], kind), [])); + } +} for (const { why, manifest } of manifests.valid) { test(`accepts the manifest: ${why}`, () => assert.deepEqual(problems(manifest, controls), [])); } diff --git a/lib/ui-feedback/note.schema.json b/lib/ui-feedback/note.schema.json index b3fcc0704d..0e9e85044f 100644 --- a/lib/ui-feedback/note.schema.json +++ b/lib/ui-feedback/note.schema.json @@ -2,8 +2,8 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "note.schema.json", "title": "UI feedback note", - "description": "One note a person pins to a non-final UI. The only definition of a note's fields, enums and limits (docs/contracts/ui-feedback). x-version moves on any change; x-maxNotesPerRun caps the notes one bridge run stores, and an import counts toward it. Text is 1 to 4000 characters: long enough for a paragraph of review, short enough that a batch of notes stays readable in one session turn. kind says what the note is pinned to: an element, a text selection (anchor.textQuote holds it), a dragged region (rect is the region and elements lists the anchors of the test-id elements it intersects, or of the holding element's children it intersects when it intersects none; anchor is the element that holds it) or a move arrow (anchor and rect are the element to move, and to is where it should go: to.anchor the destination element when one fits, and to.point the place in percent of the page's scrollable box, that end's position-only last step). Each end of a move arrow runs its own anchor ladder. Every string the page supplies is an id, a key or an enum, except anchor.textQuote and the values in controls: text copied from a model-written page, allowed there only (docs/contracts/rendered-views, rule 9) and data wherever it goes. A quote's exact text is the selection with whitespace runs collapsed, and prefix and suffix are the visible text of the scope just before and after it, so it finds the text again where Seed and Clear move it. rect is a box in percent of the page's scrollable box when the note was taken: the position-only last step of the anchor ladder when no anchor finds the element. data.log is the data controls pressed since the page loaded, in order, so a re-locating script can replay it; a log longer than its limit is left out. viewport is the framed page's size, scroll, color scheme and reduced-motion setting. controls is each control of the page's manifest (controls.schema.json) with its value when the note was taken. A change ($defs/change) is a sent region note moved or resized: change is that note's seq, and anchor, rect and elements replace the note's own; the bridge logs it as an event of its own, which counts toward x-maxNotesPerRun.", - "x-version": 7, + "description": "One note a person pins to a non-final UI. The only definition of a note's fields, enums and limits (docs/contracts/ui-feedback). x-version moves on any change; x-maxNotesPerRun caps the notes one bridge run stores, and an import counts toward it. Text is 1 to 4000 characters: long enough for a paragraph of review, short enough that a batch of notes stays readable in one session turn. kind says what the note is pinned to: an element, a text selection (anchor.textQuote holds it), a dragged region (rect is the region and elements lists the anchors of the test-id elements it intersects, or of the holding element's children it intersects when it intersects none; anchor is the element that holds it) or a move arrow (anchor and rect are the element to move, and to is where it should go: to.anchor the destination element when one fits, and to.point the place in percent of the page's scrollable box, that end's position-only last step). Each end of a move arrow runs its own anchor ladder. Every string the page supplies is an id, a key or an enum, except anchor.textQuote and the values in controls: text copied from a model-written page, allowed there only (docs/contracts/rendered-views, rule 9) and data wherever it goes. A quote's exact text is the selection with whitespace runs collapsed, and prefix and suffix are the visible text of the scope just before and after it, so it finds the text again where Seed and Clear move it. rect is a box in percent of the page's scrollable box when the note was taken: the position-only last step of the anchor ladder when no anchor finds the element. data.log is the data controls pressed since the page loaded, in order, so a re-locating script can replay it; a log longer than its limit is left out. viewport is the framed page's size, scroll, color scheme and reduced-motion setting. controls is each control of the page's manifest (controls.schema.json) with its value when the note was taken. A change ($defs/change) is a sent region note moved or resized: change is that note's seq, and anchor, rect and elements replace the note's own; the bridge logs it as an event of its own, which counts toward x-maxNotesPerRun. An edit ($defs/edit) is a sent note's new text: edit is that note's seq, and text replaces its own. A withdraw ($defs/withdraw) takes a sent note back: withdraw is that note's seq, and the note stays in the log, marked withdrawn by that event alone. Each is logged as an event of its own, which counts toward x-maxNotesPerRun.", + "x-version": 8, "x-maxNotesPerRun": 500, "type": "object", "additionalProperties": false, @@ -56,7 +56,7 @@ } }, "controls": { "$ref": "controls.schema.json#/$defs/snapshot" }, - "text": { "type": "string", "minLength": 1, "maxLength": 4000 } + "text": { "$ref": "#/$defs/text" } }, "$defs": { "percent": { "type": "number", "minimum": 0, "maximum": 100 }, @@ -83,6 +83,25 @@ "elements": { "$ref": "#/$defs/elements" } } }, + "seq": { "type": "integer", "minimum": 1, "maximum": 1000000000 }, + "text": { "type": "string", "minLength": 1, "maxLength": 4000 }, + "edit": { + "type": "object", + "additionalProperties": false, + "required": ["edit", "text"], + "properties": { + "edit": { "$ref": "#/$defs/seq" }, + "text": { "$ref": "#/$defs/text" } + } + }, + "withdraw": { + "type": "object", + "additionalProperties": false, + "required": ["withdraw"], + "properties": { + "withdraw": { "$ref": "#/$defs/seq" } + } + }, "key": { "type": "string", "pattern": "^[A-Za-z0-9_-]{1,32}$" }, "keyed": { "type": "object", diff --git a/lib/ui-feedback/notes_bridge.py b/lib/ui-feedback/notes_bridge.py index 98d7fc9131..9d58bc8b9e 100644 --- a/lib/ui-feedback/notes_bridge.py +++ b/lib/ui-feedback/notes_bridge.py @@ -15,14 +15,16 @@ one runs on the data dir stop stop the server and its watcher lease [--release] show (or clear) the watcher lease - status list the unhandled notes; needs no server or watcher + status list the unhandled notes, less a withdrawn one; needs no server or + watcher The framed page is `/` (default page.html), a model-written page the session wrote. `/` serves host.html, the checked-in host page. It fetches the page at `/api/page`, with the mockup policy (PAGE_CSP) put first and the pin helper (proto-pin.js) appended, and frames it through `srcdoc` with sandbox="allow-scripts" and never allow-same-origin, so the page has an opaque origin, no storage, and no network. The host page alone holds the token and posts each -note to `POST /api/note`, which takes one note that note.schema.json accepts, and reads the +note to `POST /api/note`, which takes one note that note.schema.json accepts, a sent note's new +text to `POST /api/note/edit` and its withdrawal to `POST /api/note/withdraw`, and reads the run's sent notes back from `GET /api/notes` with the same token after a reload. Notes go into `actions.json`, the view app's event log, and the session's replies into `replies.json`, so this app reuses the view app's hub, token route, expiry and apply (lib/session-bridge/README.md, "The view app"). Nothing here acts on a note: the watcher @@ -147,6 +149,29 @@ def pin_helper(text, name="proto-pin.js"): ) +NAMING = ("change", "edit", "withdraw") + + +def is_note(e): + """Whether a log event is a note, not an event naming one.""" + return not any(k in e for k in NAMING) + + +def withdrawn(log): + return {e["withdraw"] for e in log.get("events", []) if "withdraw" in e} + + +def pending(events, handled): + """The unhandled events, less a withdrawn note and the events changing it; its withdraw stays.""" + gone = withdrawn({"events": events}) + return [ + e + for e in events + if e["seq"] not in handled + and (e["seq"] if is_note(e) else e.get("change", e.get("edit"))) not in gone + ] + + def is_number(v): return isinstance(v, (int, float)) and not isinstance(v, bool) @@ -265,15 +290,17 @@ def read_state(self): handled, replies = self.read_replies() except (OSError, ValueError): return None, True + gone = withdrawn(log) notes = [ { "seq": e["seq"], "delivered": bool(e.get("deliveredAt")), "handled": e["seq"] in handled, "reply": replies.get(str(e["seq"])), + **({"withdrawn": True} if e["seq"] in gone else {}), } for e in log.get("events", []) - if "change" not in e + if is_note(e) ] return { "instance": self.instance, @@ -281,6 +308,9 @@ def read_state(self): "notes": notes, }, False + def unhandled(self, log): + return pending(log.get("events", []), self.read_replies()[0]) + def record(self, msg): found = problems(msg) if found: @@ -297,26 +327,28 @@ def record(self, msg): self.cond.notify_all() return log["seq"] - def record_change(self, msg): - """A sent region note moved or resized: its anchor, rect and elements are replaced in the - log, and the change is appended as an event of its own naming the note, so the watcher - wakes and the session reads it as that note changed.""" - found = problems(msg, SCHEMA["$defs"]["change"], "change") + def record_naming(self, msg, field, kinds, keys): + """An event naming sent note msg[field], one of `kinds` and not withdrawn: its `keys` are + replaced in the log, and the event is appended as one of its own, so the watcher wakes and + the session reads it as that note changed, not as a new note.""" + found = problems(msg, SCHEMA["$defs"][field], field) if found: raise ValueError(found[0]) with self.cond: log = self.read_log() + seq = msg[field] note = next( - (e for e in log["events"] if e["seq"] == msg["change"] and "change" not in e), - None, + (e for e in log["events"] if e["seq"] == seq and is_note(e)), None ) - if note is None or note.get("kind") != "region": - raise ValueError(f"change: no region note {msg['change']} in this run") + if note is None or (kinds and note.get("kind") not in kinds): + raise ValueError(f"{field}: no {kinds[0] + ' ' if kinds else ''}note {seq} in this run") + if seq in withdrawn(log): + raise ValueError(f"{field}: note {seq} was withdrawn") if len(log["events"]) >= MAX_NOTES: raise ValueError( f"the page has sent {MAX_NOTES} notes; restart the server" ) - for k in ("anchor", "rect", "elements"): + for k in keys: note[k] = msg[k] log["seq"] += 1 log["events"].append({"seq": log["seq"], "at": bridge.now_iso(), **msg}) @@ -324,6 +356,18 @@ def record_change(self, msg): self.cond.notify_all() return log["seq"] + def record_change(self, msg): + """A sent region note moved or resized: its anchor, rect and elements.""" + return self.record_naming(msg, "change", ("region",), ("anchor", "rect", "elements")) + + def record_edit(self, msg): + """A sent note's new text.""" + return self.record_naming(msg, "edit", (), ("text",)) + + def record_withdraw(self, msg): + """A sent note taken back: the note stays in the log, and the withdraw event marks it.""" + return self.record_naming(msg, "withdraw", (), ()) + class NotesHandler(view.ViewHandler): """The host page, its two assets, the framed page and the notes; session_bridge serves the rest.""" @@ -368,7 +412,12 @@ def route_get(self, url, query): return self.send(404, {"error": "not found"}) def route_post(self, path, msg): - record = {"/api/note": self.hub.record, "/api/note/change": self.hub.record_change}.get(path) + record = { + "/api/note": self.hub.record, + "/api/note/change": self.hub.record_change, + "/api/note/edit": self.hub.record_edit, + "/api/note/withdraw": self.hub.record_withdraw, + }.get(path) if record is None: return self.send(404, {"error": "not found"}) try: @@ -388,8 +437,7 @@ def cmd_status(d, a): handled = set(view.load_json(d / "replies.json", {}).get("handled", [])) events = [ {k: v for k, v in e.items() if k != "deliveredAt"} - for e in log.get("events", []) - if e["seq"] not in handled + for e in pending(log.get("events", []), handled) ] print(bridge.dumps_line({"note": bridge.DATA_NOTE, "events": events})) diff --git a/lib/ui-feedback/test_notes_bridge.py b/lib/ui-feedback/test_notes_bridge.py index 126e3d00d0..127bf59e61 100644 --- a/lib/ui-feedback/test_notes_bridge.py +++ b/lib/ui-feedback/test_notes_bridge.py @@ -382,7 +382,7 @@ def test_an_unknown_field_is_a_400(self): self.assertIn("unknown field", body["error"]) def test_an_oversize_note_is_a_400_and_an_oversize_body_a_413(self): - limit = nb.SCHEMA["properties"]["text"]["maxLength"] + limit = nb.SCHEMA["$defs"]["text"]["maxLength"] self.assertEqual(self.note({**NOTE, "text": "a" * (limit + 1)})[0], 400) self.assertEqual(self.note({**NOTE, "text": "a" * limit})[0], 200) big = json.dumps( @@ -654,6 +654,103 @@ def test_a_change_without_the_token_is_refused(self): self.assertEqual(code, 403) +class TestEditAndWithdraw(NotesCase): + """POST /api/note/edit and /api/note/withdraw: a sent note corrected or taken back.""" + + def edit(self, msg, **kw): + return self.request("POST", "/api/note/edit", msg, **kw) + + def withdraw(self, msg, **kw): + return self.request("POST", "/api/note/withdraw", msg, **kw) + + def wait(self, after): + code, body = self.request( + "GET", + f"/api/wait?after={after}&timeout=5", + headers={"X-Notes-Token": self.hub.watch_token}, + token=False, + ) + self.assertEqual(code, 200) + return body + + def status(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + nb.cmd_status(self.dir, None) + return json.loads(out.getvalue())["events"] + + def test_every_fixture_edit_and_withdraw_is_judged_as_the_fixtures_say(self): + for kind in ("edit", "withdraw"): + node = nb.SCHEMA["$defs"][kind] + for case in FIXTURES[f"{kind}s"]["valid"]: + self.assertEqual(nb.problems(case[kind], node, kind), [], case["why"]) + for case in FIXTURES[f"{kind}s"]["invalid"]: + self.assertNotEqual(nb.problems(case[kind], node, kind), [], case["why"]) + + def test_an_edit_replaces_the_text_and_reaches_the_session_naming_the_note(self): + self.note() + self.assertEqual([e["seq"] for e in self.wait(0)["events"]], [1]) + code, body = self.edit({"edit": 1, "text": "Bolder, and larger."}) + self.assertEqual((code, body["seq"]), (200, 2)) + first, second = self.hub.read_log()["events"] + self.assertEqual((first["seq"], first["text"]), (1, "Bolder, and larger.")) + self.assertEqual({k: second[k] for k in ("seq", "edit", "text")}, {"seq": 2, "edit": 1, "text": "Bolder, and larger."}) + self.assertNotIn("kind", second) + events = self.wait(1)["events"] + self.assertEqual([(e["seq"], e["edit"], e["text"]) for e in events], [(2, 1, "Bolder, and larger.")]) + state, _ = self.hub.read_state() + self.assertEqual([n["seq"] for n in state["notes"]], [1]) + + def test_an_edited_note_reloads_as_a_note_the_contract_admits(self): + self.note() + self.edit({"edit": 1, "text": "Bolder, and larger."}) + _, body = self.request("GET", "/api/notes") + notes = [n for n in body["notes"] if not nb.problems({k: v for k, v in n.items() if k not in ("seq", "at")})] + self.assertEqual([(n["seq"], n["text"]) for n in notes], [(1, "Bolder, and larger.")]) + + def test_a_withdraw_marks_the_note_withdrawn_and_tells_the_session(self): + self.note() + self.note({**NOTE, "text": "Second."}) + code, body = self.withdraw({"withdraw": 1}) + self.assertEqual((code, body["seq"]), (200, 3)) + self.assertEqual(self.hub.read_log()["events"][2]["withdraw"], 1) + state, _ = self.hub.read_state() + self.assertEqual([(n["seq"], n.get("withdrawn")) for n in state["notes"]], [(1, True), (2, None)]) + self.assertEqual([e["seq"] for e in self.wait("handled")["events"]], [2, 3]) + self.assertEqual([e["seq"] for e in self.status()], [2, 3]) + + def test_a_withdrawn_note_is_not_edited_moved_or_withdrawn_again(self): + self.note(REGION) + self.withdraw({"withdraw": 1}) + self.assertEqual(self.edit({"edit": 1, "text": "x"})[0], 400) + self.assertEqual(self.withdraw({"withdraw": 1})[0], 400) + self.assertEqual(self.request("POST", "/api/note/change", {"change": 1, **MOVED})[0], 400) + self.assertEqual(len(self.hub.read_log()["events"]), 2) + + def test_an_edit_or_withdraw_is_refused_unless_it_names_a_sent_note(self): + self.note() + self.edit({"edit": 1, "text": "x"}) + for why, call, msg in ( + ("no such note", self.edit, {"edit": 9, "text": "x"}), + ("an edit, not a note", self.edit, {"edit": 2, "text": "x"}), + ("empty text", self.edit, {"edit": 1, "text": ""}), + ("no such note", self.withdraw, {"withdraw": 9}), + ("an edit, not a note", self.withdraw, {"withdraw": 2}), + ("a field a withdraw does not carry", self.withdraw, {"withdraw": 1, "text": "x"}), + ): + self.assertEqual(call(msg)[0], 400, why) + self.assertEqual(len(self.hub.read_log()["events"]), 2) + self.assertEqual(self.edit({"edit": 1, "text": "x"}, token=False)[0], 403) + self.assertEqual(self.withdraw({"withdraw": 1}, token=False)[0], 403) + + def test_a_log_written_before_edits_and_withdraws_still_loads(self): + old = {"seq": 1, "events": [{"seq": 1, "at": "2026-11-01T00:00:00Z", **NOTE}]} + (self.dir / "actions.json").write_text(json.dumps(old), encoding="utf-8") + state, _ = self.hub.read_state() + self.assertEqual([n["seq"] for n in state["notes"]], [1]) + self.assertEqual([e["text"] for e in self.status()], [NOTE["text"]]) + + class TestImport(unittest.TestCase): """import with no server: a copy-out block written to a file goes through the note contract.""" @@ -716,7 +813,7 @@ def test_an_unknown_field_refuses_the_whole_block(self): ) def test_an_oversize_note_refuses_the_whole_block(self): - limit = nb.SCHEMA["properties"]["text"]["maxLength"] + limit = nb.SCHEMA["$defs"]["text"]["maxLength"] self.assert_refused( block([NOTE, {**NOTE, "text": "a" * (limit + 1)}]), "longer than" ) diff --git a/plugins/prototype/notes-bridge/host.html b/plugins/prototype/notes-bridge/host.html index 90dfc82d74..d6db1e565b 100644 --- a/plugins/prototype/notes-bridge/host.html +++ b/plugins/prototype/notes-bridge/host.html @@ -17,7 +17,10 @@ run's token, never on the server, so a reload of the same run lists it again. The run's sent notes come back from /api/notes, the token in the request's header, each kept only as note.schema.json admits it. A region note, a draft or sent, can be moved or resized from the editor or its row; a sent one's - new anchor, rect and elements go to /api/note/change, which tells the session that note changed. Hovering a row draws its note's box in the frame, and clicking a row or its marker restores the + new anchor, rect and elements go to /api/note/change, which tells the session that note changed. A sent + note's Edit sends its new text to /api/note/edit and its Withdraw to /api/note/withdraw, each naming + the note's seq; a withdrawn note is listed as withdrawn, with no marker and no actions, and left out + of Copy all notes. Hovering a row draws its note's box in the frame, and clicking a row or its marker restores the note's view and keeps the box drawn; the frame gets keys, a path and a box, never note text. The Controls tab renders the framed page's controls manifest, kept only when controls.schema.json admits it, through the registry in controls.js, beside the content sets the page marks, and the Sample data menu lists the data @@ -163,6 +166,8 @@ .st { display: flex; flex-wrap: wrap; gap: 4px 12px; margin-block-start: 6px; font-size: 12px; color: var(--uif-ink-2); } .st .s-draft { color: var(--uif-draft); font-weight: 600; } .st .s-handled { color: var(--uif-ok); font-weight: 600; } + .st .s-withdrawn { color: var(--uif-ink-2); font-weight: 600; } + .note.withdrawn .text { color: var(--uif-ink-2); text-decoration: line-through; } .reply { margin-block: 8px 0; margin-inline: 0; padding-block: 6px; padding-inline: 10px; border-inline-start: 3px solid var(--uif-accent); background: var(--uif-sunk); border-radius: 0 var(--uif-r-s) var(--uif-r-s) 0; font-size: 13px; overflow-wrap: anywhere; diff --git a/plugins/prototype/notes-bridge/host.mjs b/plugins/prototype/notes-bridge/host.mjs index fb0511da39..2ae760c5e1 100644 --- a/plugins/prototype/notes-bridge/host.mjs +++ b/plugins/prototype/notes-bridge/host.mjs @@ -235,6 +235,8 @@ function viewWords(n) { } /** A row's number, as its marker shows it: the seq once sent, D1, D2... for drafts, null for a note no marker shows. */ +/** Whether a sent note was withdrawn, here or, after a reload, as the bridge reports. */ +const gone = (m) => Boolean(m && (m.withdrawn || last.notes.some((n) => n.seq === m.seq && n.withdrawn))); const numberOf = (m) => m.seq ?? (m.draft ? `D${mine.filter((x) => x.draft).indexOf(m) + 1}` : null); /** What the frame needs to find a note's box and restore its view: contract keys, a path and a box, never its text. */ function noteTarget(m) { @@ -308,9 +310,11 @@ function openComposer(note, from, entry = null) { setPick(null); if ($("panel").hidden) setPanel(true); selectTab(tabs[0], false); - $("composer-label").textContent = entry ? `Edit draft ${numberOf(entry)}` : "New note"; + const sent = entry?.seq != null; + $("composer-label").textContent = entry ? `Edit ${sent ? "note" : "draft"} ${numberOf(entry)}` : "New note"; $("picked").textContent = `${{ element: "Picked", text: "Selected", region: "Marked", move: "Arrow" }[note.kind]}: ${where(note)}`; - $("reshape").hidden = note.kind !== "region"; + $("reshape").hidden = note.kind !== "region" || sent; + $("save").hidden = sent; composer.hidden = false; text.value = entry ? entry.note.text : ""; text.focus(); @@ -365,6 +369,7 @@ async function send() { if (!draft || sending) return; const note = written("sent"); if (!note) return; + if (editing?.seq != null) return edited(editing, note.text); const entry = editing || { id: ++ids }; Object.assign(entry, { note, where: where(note), seq: null, parts: null, asked: null }); const got = await deliver(entry); @@ -398,7 +403,7 @@ async function sendDrafts(list) { sent.push(entry.seq); } const refusal = got === "refused" ? ` ${$("status").textContent}` : ""; - if (editing && !editing.draft) closeComposer(); + if (editing && !editing.draft && list.includes(editing)) closeComposer(); render(); if (noSession) say(OFFLINE); else if (sent.length) say((sent.length === 1 ? `Note ${sent[0]} sent.` : `Notes ${sent.join(", ")} sent.`) + refusal); @@ -438,7 +443,7 @@ async function reshaped(note) { return; } toFrame({ type: "release" }); - if (target.seq !== null && (await deliverChange(target.seq, moved)) !== "sent") return; + if (target.seq !== null && (await deliverNaming("change", { change: target.seq, ...moved }, "moved", "keeps its region")) !== "sent") return; target.note = { ...target.note, ...moved }; target.where = where(target.note); target.parts = target.asked = null; @@ -447,27 +452,46 @@ async function reshaped(note) { document.querySelector(`[data-key="reshape-${target.id}"]`)?.focus(); say(target.seq !== null ? `Note ${target.seq}'s region moved; Claude is told.` : "The region moved."); } -/** Post a sent region note's new anchor, rect and elements; "sent" once the session's log has the change. */ -async function deliverChange(seq, moved) { +/** Post an event naming a sent note to /api/note/: a region's change, an edit or a withdraw; + * "sent" once the session's log has it. */ +async function deliverNaming(path, msg, verb, kept) { if (sending) return "busy"; sending = true; let r, body; try { - r = await fetch("/api/note/change", { + r = await fetch(`/api/note/${path}`, { method: "POST", headers: { "Content-Type": "application/json", "X-Notes-Token": token }, - body: JSON.stringify({ change: seq, ...moved }), + body: JSON.stringify(msg), }); body = await r.json(); } catch { - say(`Not moved: no session is answering, so note ${seq} keeps its region.`); + say(`Not ${verb}: no session is answering, so note ${msg[path]} ${kept}.`); return "offline"; } finally { sending = false; } - if (!r.ok) { say(`Not moved: ${body.error || r.status}.`); return "refused"; } + if (!r.ok) { say(`Not ${verb}: ${body.error || r.status}.`); return "refused"; } return "sent"; } +/** A sent note's new text replaces its own here and in the session's log, under the same seq. */ +async function edited(entry, words) { + if ((await deliverNaming("edit", { edit: entry.seq, text: words }, "edited", "keeps its text")) !== "sent") return; + entry.note = { ...entry.note, text: words }; + render(); + closeComposer(); + say(`Note ${entry.seq} edited; Claude is told.`); +} +/** Take a sent note back: the session is told, and the list shows it withdrawn, not pending. */ +async function withdraw(entry) { + if ((await deliverNaming("withdraw", { withdraw: entry.seq }, "withdrawn", "stays sent")) !== "sent") return; + entry.withdrawn = true; + if (editing === entry) closeComposer(); + if (chosen === entry) unchoose(true); + render(); + $("notes-title").focus(); + say(`Note ${entry.seq} withdrawn; Claude is told.`); +} /** Show or hide the notes popover over the mockup; the frame keeps its size. The Notes button stays, and gets the focus back when the popover closes. */ function setPanel(open) { @@ -516,7 +540,7 @@ function copyAll() { $("copy-button").focus(); if ($("panel").hidden) setPanel(true); selectTab(tabs[0], false); - const notes = mine.filter((m) => !m.draft); + const notes = mine.filter((m) => !m.draft && !gone(m)); if (!notes.length) return say("No notes on this page yet; a draft goes in once it is sent."); const body = JSON.stringify({ notes: notes.map((m) => m.note) }, null, 1).replace(/`/g, "\\u0060"); const block = "```prototype-notes\n" + body + "\n```\n"; @@ -538,12 +562,12 @@ function render() { const byseq = new Map(last.notes.map((n) => [n.seq, n])); const ours = new Map(mine.filter((m) => m.seq !== null).map((m) => [m.seq, m])); const seqs = [...new Set([...ours.keys(), ...byseq.keys()])].sort((a, b) => a - b); - const statusOf = (st) => (st.handled ? "Handled" : st.delivered ? "Claude has it" : "Sent") + (st.reply ? ", with a reply" : ""); + const statusOf = (st) => (st.withdrawn ? "Withdrawn" : st.handled ? "Handled" : st.delivered ? "Claude has it" : "Sent") + (st.reply ? ", with a reply" : ""); const changed = []; for (const seq of ours.keys()) { const st = byseq.get(seq); if (!st) continue; - const now = statusOf(st); + const now = statusOf({ ...st, withdrawn: gone(ours.get(seq)) }); if (shown.has(seq) && shown.get(seq) !== now) changed.push(`Note ${seq}: ${now}`); shown.set(seq, now); } @@ -597,13 +621,20 @@ function render() { n: numberOf(m), selector: "", rect: { x: m.note.rect?.x ?? 0, y: m.note.rect?.y ?? 0 }, ...(m.note.variant && { variant: m.note.variant.key }), ...(m.note.state && { state: m.note.state.key }), }); - toFrame({ type: "pins", pins: [...mine.filter((m) => m.seq !== null), ...drafts].map(pin) }); + toFrame({ type: "pins", pins: [...mine.filter((m) => m.seq !== null && !gone(m)), ...drafts].map(pin) }); askNames(); const sentRows = seqs.map((seq) => { const m = ours.get(seq); - const st = byseq.get(seq) || {}; - const status = [statusOf(st), st.handled ? "s-handled" : ""]; - return item(seq, m ? readerName(m.note, m.parts) : "Sent earlier", m ? m.note.text : "", status, m ? viewWords(m.note) : "", st.reply, reshapes(m), m); + const st = { ...byseq.get(seq), ...(gone(m) && { withdrawn: true }) }; + const status = [statusOf(st), st.withdrawn ? "s-withdrawn" : st.handled ? "s-handled" : ""]; + const acts = !m || st.withdrawn ? [] : [ + button("Edit", `edit-${m.id}`, () => openComposer(m.note, control(`edit-${m.id}`), m)), + button("Withdraw", `withdraw-${m.id}`, () => withdraw(m)), + ...reshapes(m), + ]; + const li = item(seq, m ? readerName(m.note, m.parts) : "Sent earlier", m ? m.note.text : "", status, m ? viewWords(m.note) : "", st.reply, acts, m); + li.classList.toggle("withdrawn", Boolean(st.withdrawn)); + return li; }); const unsent = mine.filter((m) => m.seq === null).map((m) => (m.draft ? item(numberOf(m), readerName(m.note, m.parts), m.note.text, ["Draft, not sent", "s-draft"], viewWords(m.note), null, [ @@ -622,7 +653,7 @@ function render() { $("notes").replaceChildren(...(filter === "draft" ? draftRows : filter === "sent" ? sentRows : [...sentRows, ...unsent])); $("empty").hidden = counts.all > 0; $("count").textContent = String(counts.all); - $("copy-count").textContent = String(counts.sent + unsent.length - drafts.length); + $("copy-count").textContent = String(counts.sent + unsent.length - drafts.length - mine.filter((m) => m.seq !== null && gone(m)).length); $("dock").setAttribute("aria-label", `Notes, ${counts.all}`); $("drafts").textContent = drafts.length ? `${drafts.length} draft${drafts.length > 1 ? "s" : ""} not sent.` : ""; $("sendall").hidden = !drafts.length; diff --git a/plugins/prototype/notes-bridge/note.schema.json b/plugins/prototype/notes-bridge/note.schema.json index b3fcc0704d..0e9e85044f 100644 --- a/plugins/prototype/notes-bridge/note.schema.json +++ b/plugins/prototype/notes-bridge/note.schema.json @@ -2,8 +2,8 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "note.schema.json", "title": "UI feedback note", - "description": "One note a person pins to a non-final UI. The only definition of a note's fields, enums and limits (docs/contracts/ui-feedback). x-version moves on any change; x-maxNotesPerRun caps the notes one bridge run stores, and an import counts toward it. Text is 1 to 4000 characters: long enough for a paragraph of review, short enough that a batch of notes stays readable in one session turn. kind says what the note is pinned to: an element, a text selection (anchor.textQuote holds it), a dragged region (rect is the region and elements lists the anchors of the test-id elements it intersects, or of the holding element's children it intersects when it intersects none; anchor is the element that holds it) or a move arrow (anchor and rect are the element to move, and to is where it should go: to.anchor the destination element when one fits, and to.point the place in percent of the page's scrollable box, that end's position-only last step). Each end of a move arrow runs its own anchor ladder. Every string the page supplies is an id, a key or an enum, except anchor.textQuote and the values in controls: text copied from a model-written page, allowed there only (docs/contracts/rendered-views, rule 9) and data wherever it goes. A quote's exact text is the selection with whitespace runs collapsed, and prefix and suffix are the visible text of the scope just before and after it, so it finds the text again where Seed and Clear move it. rect is a box in percent of the page's scrollable box when the note was taken: the position-only last step of the anchor ladder when no anchor finds the element. data.log is the data controls pressed since the page loaded, in order, so a re-locating script can replay it; a log longer than its limit is left out. viewport is the framed page's size, scroll, color scheme and reduced-motion setting. controls is each control of the page's manifest (controls.schema.json) with its value when the note was taken. A change ($defs/change) is a sent region note moved or resized: change is that note's seq, and anchor, rect and elements replace the note's own; the bridge logs it as an event of its own, which counts toward x-maxNotesPerRun.", - "x-version": 7, + "description": "One note a person pins to a non-final UI. The only definition of a note's fields, enums and limits (docs/contracts/ui-feedback). x-version moves on any change; x-maxNotesPerRun caps the notes one bridge run stores, and an import counts toward it. Text is 1 to 4000 characters: long enough for a paragraph of review, short enough that a batch of notes stays readable in one session turn. kind says what the note is pinned to: an element, a text selection (anchor.textQuote holds it), a dragged region (rect is the region and elements lists the anchors of the test-id elements it intersects, or of the holding element's children it intersects when it intersects none; anchor is the element that holds it) or a move arrow (anchor and rect are the element to move, and to is where it should go: to.anchor the destination element when one fits, and to.point the place in percent of the page's scrollable box, that end's position-only last step). Each end of a move arrow runs its own anchor ladder. Every string the page supplies is an id, a key or an enum, except anchor.textQuote and the values in controls: text copied from a model-written page, allowed there only (docs/contracts/rendered-views, rule 9) and data wherever it goes. A quote's exact text is the selection with whitespace runs collapsed, and prefix and suffix are the visible text of the scope just before and after it, so it finds the text again where Seed and Clear move it. rect is a box in percent of the page's scrollable box when the note was taken: the position-only last step of the anchor ladder when no anchor finds the element. data.log is the data controls pressed since the page loaded, in order, so a re-locating script can replay it; a log longer than its limit is left out. viewport is the framed page's size, scroll, color scheme and reduced-motion setting. controls is each control of the page's manifest (controls.schema.json) with its value when the note was taken. A change ($defs/change) is a sent region note moved or resized: change is that note's seq, and anchor, rect and elements replace the note's own; the bridge logs it as an event of its own, which counts toward x-maxNotesPerRun. An edit ($defs/edit) is a sent note's new text: edit is that note's seq, and text replaces its own. A withdraw ($defs/withdraw) takes a sent note back: withdraw is that note's seq, and the note stays in the log, marked withdrawn by that event alone. Each is logged as an event of its own, which counts toward x-maxNotesPerRun.", + "x-version": 8, "x-maxNotesPerRun": 500, "type": "object", "additionalProperties": false, @@ -56,7 +56,7 @@ } }, "controls": { "$ref": "controls.schema.json#/$defs/snapshot" }, - "text": { "type": "string", "minLength": 1, "maxLength": 4000 } + "text": { "$ref": "#/$defs/text" } }, "$defs": { "percent": { "type": "number", "minimum": 0, "maximum": 100 }, @@ -83,6 +83,25 @@ "elements": { "$ref": "#/$defs/elements" } } }, + "seq": { "type": "integer", "minimum": 1, "maximum": 1000000000 }, + "text": { "type": "string", "minLength": 1, "maxLength": 4000 }, + "edit": { + "type": "object", + "additionalProperties": false, + "required": ["edit", "text"], + "properties": { + "edit": { "$ref": "#/$defs/seq" }, + "text": { "$ref": "#/$defs/text" } + } + }, + "withdraw": { + "type": "object", + "additionalProperties": false, + "required": ["withdraw"], + "properties": { + "withdraw": { "$ref": "#/$defs/seq" } + } + }, "key": { "type": "string", "pattern": "^[A-Za-z0-9_-]{1,32}$" }, "keyed": { "type": "object", diff --git a/plugins/prototype/notes-bridge/notes_bridge.py b/plugins/prototype/notes-bridge/notes_bridge.py index d81f1b671c..2f5fcb3d24 100644 --- a/plugins/prototype/notes-bridge/notes_bridge.py +++ b/plugins/prototype/notes-bridge/notes_bridge.py @@ -17,14 +17,16 @@ one runs on the data dir stop stop the server and its watcher lease [--release] show (or clear) the watcher lease - status list the unhandled notes; needs no server or watcher + status list the unhandled notes, less a withdrawn one; needs no server or + watcher The framed page is `/` (default page.html), a model-written page the session wrote. `/` serves host.html, the checked-in host page. It fetches the page at `/api/page`, with the mockup policy (PAGE_CSP) put first and the pin helper (proto-pin.js) appended, and frames it through `srcdoc` with sandbox="allow-scripts" and never allow-same-origin, so the page has an opaque origin, no storage, and no network. The host page alone holds the token and posts each -note to `POST /api/note`, which takes one note that note.schema.json accepts, and reads the +note to `POST /api/note`, which takes one note that note.schema.json accepts, a sent note's new +text to `POST /api/note/edit` and its withdrawal to `POST /api/note/withdraw`, and reads the run's sent notes back from `GET /api/notes` with the same token after a reload. Notes go into `actions.json`, the view app's event log, and the session's replies into `replies.json`, so this app reuses the view app's hub, token route, expiry and apply (lib/session-bridge/README.md, "The view app"). Nothing here acts on a note: the watcher @@ -149,6 +151,29 @@ def pin_helper(text, name="proto-pin.js"): ) +NAMING = ("change", "edit", "withdraw") + + +def is_note(e): + """Whether a log event is a note, not an event naming one.""" + return not any(k in e for k in NAMING) + + +def withdrawn(log): + return {e["withdraw"] for e in log.get("events", []) if "withdraw" in e} + + +def pending(events, handled): + """The unhandled events, less a withdrawn note and the events changing it; its withdraw stays.""" + gone = withdrawn({"events": events}) + return [ + e + for e in events + if e["seq"] not in handled + and (e["seq"] if is_note(e) else e.get("change", e.get("edit"))) not in gone + ] + + def is_number(v): return isinstance(v, (int, float)) and not isinstance(v, bool) @@ -267,15 +292,17 @@ def read_state(self): handled, replies = self.read_replies() except (OSError, ValueError): return None, True + gone = withdrawn(log) notes = [ { "seq": e["seq"], "delivered": bool(e.get("deliveredAt")), "handled": e["seq"] in handled, "reply": replies.get(str(e["seq"])), + **({"withdrawn": True} if e["seq"] in gone else {}), } for e in log.get("events", []) - if "change" not in e + if is_note(e) ] return { "instance": self.instance, @@ -283,6 +310,9 @@ def read_state(self): "notes": notes, }, False + def unhandled(self, log): + return pending(log.get("events", []), self.read_replies()[0]) + def record(self, msg): found = problems(msg) if found: @@ -299,26 +329,28 @@ def record(self, msg): self.cond.notify_all() return log["seq"] - def record_change(self, msg): - """A sent region note moved or resized: its anchor, rect and elements are replaced in the - log, and the change is appended as an event of its own naming the note, so the watcher - wakes and the session reads it as that note changed.""" - found = problems(msg, SCHEMA["$defs"]["change"], "change") + def record_naming(self, msg, field, kinds, keys): + """An event naming sent note msg[field], one of `kinds` and not withdrawn: its `keys` are + replaced in the log, and the event is appended as one of its own, so the watcher wakes and + the session reads it as that note changed, not as a new note.""" + found = problems(msg, SCHEMA["$defs"][field], field) if found: raise ValueError(found[0]) with self.cond: log = self.read_log() + seq = msg[field] note = next( - (e for e in log["events"] if e["seq"] == msg["change"] and "change" not in e), - None, + (e for e in log["events"] if e["seq"] == seq and is_note(e)), None ) - if note is None or note.get("kind") != "region": - raise ValueError(f"change: no region note {msg['change']} in this run") + if note is None or (kinds and note.get("kind") not in kinds): + raise ValueError(f"{field}: no {kinds[0] + ' ' if kinds else ''}note {seq} in this run") + if seq in withdrawn(log): + raise ValueError(f"{field}: note {seq} was withdrawn") if len(log["events"]) >= MAX_NOTES: raise ValueError( f"the page has sent {MAX_NOTES} notes; restart the server" ) - for k in ("anchor", "rect", "elements"): + for k in keys: note[k] = msg[k] log["seq"] += 1 log["events"].append({"seq": log["seq"], "at": bridge.now_iso(), **msg}) @@ -326,6 +358,18 @@ def record_change(self, msg): self.cond.notify_all() return log["seq"] + def record_change(self, msg): + """A sent region note moved or resized: its anchor, rect and elements.""" + return self.record_naming(msg, "change", ("region",), ("anchor", "rect", "elements")) + + def record_edit(self, msg): + """A sent note's new text.""" + return self.record_naming(msg, "edit", (), ("text",)) + + def record_withdraw(self, msg): + """A sent note taken back: the note stays in the log, and the withdraw event marks it.""" + return self.record_naming(msg, "withdraw", (), ()) + class NotesHandler(view.ViewHandler): """The host page, its two assets, the framed page and the notes; session_bridge serves the rest.""" @@ -370,7 +414,12 @@ def route_get(self, url, query): return self.send(404, {"error": "not found"}) def route_post(self, path, msg): - record = {"/api/note": self.hub.record, "/api/note/change": self.hub.record_change}.get(path) + record = { + "/api/note": self.hub.record, + "/api/note/change": self.hub.record_change, + "/api/note/edit": self.hub.record_edit, + "/api/note/withdraw": self.hub.record_withdraw, + }.get(path) if record is None: return self.send(404, {"error": "not found"}) try: @@ -390,8 +439,7 @@ def cmd_status(d, a): handled = set(view.load_json(d / "replies.json", {}).get("handled", [])) events = [ {k: v for k, v in e.items() if k != "deliveredAt"} - for e in log.get("events", []) - if e["seq"] not in handled + for e in pending(log.get("events", []), handled) ] print(bridge.dumps_line({"note": bridge.DATA_NOTE, "events": events})) diff --git a/plugins/prototype/skills/explore-directions/reference/feedback.md b/plugins/prototype/skills/explore-directions/reference/feedback.md index 4580d49607..44a4c8eb2c 100644 --- a/plugins/prototype/skills/explore-directions/reference/feedback.md +++ b/plugins/prototype/skills/explore-directions/reference/feedback.md @@ -120,6 +120,12 @@ carries the view a reload loses: - **The view.** `data.log` lists the data controls pressed since the page loaded, in order, and `viewport` the frame's size, scroll, color scheme and reduced-motion setting. +The person can edit or withdraw a sent note from its row. An event that carries `edit` is not a +new note but note `` edited: its `text` is the note's new text, which the log's note now +carries too. Restate that note with its new text and act on that. An event that carries `withdraw` +is note `` taken back: do not act on it, and undo an edit you already made for it. Put +both events' seqs in `handled`. + The host's keys P, R, A, M (markers) and N (notes popover) also work while focus is inside the mockup. A key the mockup handles itself, calling `preventDefault` as the switcher does, stays in the mockup: on a variant with motion, R inside the mockup still replays, as the switcher defines diff --git a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js new file mode 100644 index 0000000000..67df4741b9 --- /dev/null +++ b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js @@ -0,0 +1,56 @@ +async page => { + const R = [], ok = (name, pass, detail) => R.push((pass ? "PASS " : "FAIL ") + name + (detail !== undefined ? " [" + detail + "]" : "")); + try { + await page.setViewportSize({ width: 1280, height: 800 }); + await page.goto("http://127.0.0.1:__PORT__/"); + const loaded = async () => { + await page.waitForFunction(() => !document.getElementById("pick").disabled, null, { timeout: 10000 }); + return page.frames().find((f) => f !== page.mainFrame()); + }; + let frame = await loaded(); + const inFrame = page.frameLocator("#page"); + const ROW = '[data-variant="A"] [data-testid="shipments-parcel-row"]'; + const said = (re) => page.waitForFunction((re) => new RegExp(re).test(document.getElementById("status").textContent), re, { timeout: 5000 }); + const markers = () => frame.evaluate(() => [...(document.querySelector("[data-ui-feedback-layer]")?.children ?? [])].filter((e) => e.textContent).map((e) => e.textContent).join()); + const rows = page.locator("#notes li"); + for (const [i, words] of [[0, "Bolder parcel ids."], [1, "Dates first."]]) { + await page.click("#pick"); + await inFrame.locator(ROW).nth(i).click(); + await page.waitForSelector("#composer:not([hidden])", { timeout: 5000 }); + await page.keyboard.insertText(words); + await page.click("#send"); + await said(`Note ${i + 1} sent`); + } + + await page.click('[data-key^="edit-"]'); + await page.waitForSelector("#composer:not([hidden])", { timeout: 5000 }); + ok("Edit on sent note 1 opens the editor on its text, with no Save draft", + (await page.textContent("#composer-label")) === "Edit note 1" && (await page.inputValue("#text")) === "Bolder parcel ids." && await page.isHidden("#save")); + await page.fill("#text", "Bolder and larger parcel ids."); + await page.click("#send"); + await said("Note 1 edited"); + ok("the edited note keeps its number and shows its new text, with no second row", + (await rows.count()) === 2 && (await rows.nth(0).textContent()).startsWith("1") && (await rows.nth(0).locator(".text").textContent()) === "Bolder and larger parcel ids."); + + await page.reload(); + frame = await loaded(); + await page.waitForFunction(() => document.querySelectorAll("#notes li").length === 2, null, { timeout: 5000 }).catch(() => {}); + ok("after a reload note 1 is listed with its edited text", (await rows.nth(0).locator(".text").textContent()) === "Bolder and larger parcel ids."); + + await rows.nth(1).locator('[data-key^="withdraw-"]').click(); + await said("Note 2 withdrawn"); + ok("a withdrawn note is listed as withdrawn, not pending, with no actions", + (await rows.nth(1).locator(".state").textContent()) === "Withdrawn" && (await rows.nth(1).locator("button").count()) === 0); + ok("note 1 is still pending", (await rows.nth(0).locator(".state").textContent()) !== "Withdrawn"); + for (let i = 0; i < 50 && (await markers()) !== "1"; i++) await page.waitForTimeout(100); + ok("the withdrawn note draws no marker", (await markers()) === "1", await markers()); + + await page.reload(); + frame = await loaded(); + await page.waitForFunction(() => document.querySelectorAll("#notes li .state")[1]?.textContent === "Withdrawn", null, { timeout: 5000 }).catch(() => {}); + ok("after a reload note 2 is still withdrawn", (await rows.nth(1).locator(".state").textContent()) === "Withdrawn"); + } catch (err) { + R.push("ERROR " + String(err && err.message || err).slice(0, 300)); + } + return R.join("\n"); +} diff --git a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh new file mode 100755 index 0000000000..81754a8a04 --- /dev/null +++ b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# test-scope: plugins/prototype/notes-bridge/* plugins/prototype/skills/explore-directions/assets/variant-switcher.html plugins/prototype/skills/explore-directions/evals/fixtures/shipments-mockup.html plugins/prototype/lib/browser-test-helpers.sh plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js +set -euo pipefail + +here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +skill=$(cd "$here/.." && pwd) +bridge=$(cd "$skill/../../notes-bridge" && pwd) +# shellcheck source=../../../lib/browser-test-helpers.sh +source "$here/../../../lib/browser-test-helpers.sh" +browser_setup ed-notes-edit ede playwright-cli python3 curl + +marker='' +while IFS= read -r line; do + if [[ "$line" == "$marker" ]]; then cat "$skill/assets/variant-switcher.html"; else printf '%s\n' "$line"; fi +done <"$skill/evals/fixtures/shipments-mockup.html" >"$d/explore-directions.html" + +browser_serve + +pw open >/dev/null 2>&1 +sed "s/__PORT__/$port/" "$here/notes-edit-browser-take.js" >"$tmp/take.js" +out=$(code "$tmp/take.js") +n=0 +while IFS= read -r line; do + n=$((n + 1)) + case "$line" in + PASS\ *) ok "take: ${line#PASS }" ;; + *) bad "take: $line" ;; + esac +done < <(printf '%s\n' "$out" | result | tr -d '\r' | grep -E '^(PASS|FAIL|ERROR) ') +((n > 0)) || bad "take: no results ($(printf '%s' "$out" | head -c 1500))" + +log=$(cat "$d/actions.json") +check "the log holds both notes under seqs 1 and 2, note 1 with its edited text" \ + 'e = r["events"]; assert [(x["seq"], x["text"]) for x in e[:2]] == [(1, "Bolder and larger parcel ids."), (2, "Dates first.")], e' "$log" +check "the edit and the withdraw are logged as events naming their notes" \ + 'e = r["events"][2:]; assert [(x["seq"], x.get("edit"), x.get("withdraw")) for x in e] == [(3, 1, None), (4, None, 2)], e' "$log" +check "status lists note 1 and its edit, and the withdraw, but not the withdrawn note" \ + 'assert [x["seq"] for x in r["events"]] == [1, 3, 4], r' "$(bash "$bridge/notes-bridge.sh" --dir "$d" status)" + +if ((fails)); then + echo "notes-edit-browser: $fails failed" + exit 1 +fi +echo "notes-edit-browser: all passed" From 56e3e43d77624f2618c4587a319da6c29cc84d29 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:51:25 -0500 Subject: [PATCH 2/7] test(prototype): declare plugin.json in the new notes browser suite's test-scope The suite reads plugins/prototype/.claude-plugin/plugin.json through the browser test helpers, so a change to it must select the suite (scripts/affected-tests.sh R8). Co-Authored-By: Claude Opus 5.5 --- .../explore-directions/scripts/notes-edit-browser.test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh index 81754a8a04..a2d0b56560 100755 --- a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh +++ b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# test-scope: plugins/prototype/notes-bridge/* plugins/prototype/skills/explore-directions/assets/variant-switcher.html plugins/prototype/skills/explore-directions/evals/fixtures/shipments-mockup.html plugins/prototype/lib/browser-test-helpers.sh plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js +# test-scope: plugins/prototype/notes-bridge/* plugins/prototype/skills/explore-directions/assets/variant-switcher.html plugins/prototype/skills/explore-directions/evals/fixtures/shipments-mockup.html plugins/prototype/lib/browser-test-helpers.sh plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js plugins/prototype/.claude-plugin/plugin.json set -euo pipefail here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) From e2321ab0d05645207b13873a6056183d4453c130 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:02:27 -0500 Subject: [PATCH 3/7] fix(prototype): select the row before its Edit and Withdraw in the browser suite A row's actions show only on the selected row (host.html .note:not([aria-current="true"]) .acts { display: none }), so the take timed out clicking a hidden Edit. It now clicks the row's text first, as a person does. The suite's session prefix becomes edx, which typos accepts, and numberOf's doc comment moves back onto numberOf. Co-Authored-By: Claude Opus 5.5 --- lib/ui-feedback/host.mjs | 2 +- plugins/prototype/notes-bridge/host.mjs | 2 +- .../explore-directions/scripts/notes-edit-browser-take.js | 4 +++- .../explore-directions/scripts/notes-edit-browser.test.sh | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/ui-feedback/host.mjs b/lib/ui-feedback/host.mjs index fcf0b5cabc..525f0dffa9 100644 --- a/lib/ui-feedback/host.mjs +++ b/lib/ui-feedback/host.mjs @@ -232,9 +232,9 @@ function viewWords(n) { return `On ${v ? `${n.variant.key} ${v}` : `variant ${n.variant.key}`}${s ? `, ${s.toLowerCase()}` : ""}`; } -/** A row's number, as its marker shows it: the seq once sent, D1, D2... for drafts, null for a note no marker shows. */ /** Whether a sent note was withdrawn, here or, after a reload, as the bridge reports. */ const gone = (m) => Boolean(m && (m.withdrawn || last.notes.some((n) => n.seq === m.seq && n.withdrawn))); +/** A row's number, as its marker shows it: the seq once sent, D1, D2... for drafts, null for a note no marker shows. */ const numberOf = (m) => m.seq ?? (m.draft ? `D${mine.filter((x) => x.draft).indexOf(m) + 1}` : null); /** What the frame needs to find a note's box and restore its view: contract keys, a path and a box, never its text. */ function noteTarget(m) { diff --git a/plugins/prototype/notes-bridge/host.mjs b/plugins/prototype/notes-bridge/host.mjs index 2ae760c5e1..4f7997b56c 100644 --- a/plugins/prototype/notes-bridge/host.mjs +++ b/plugins/prototype/notes-bridge/host.mjs @@ -234,9 +234,9 @@ function viewWords(n) { return `On ${v ? `${n.variant.key} ${v}` : `variant ${n.variant.key}`}${s ? `, ${s.toLowerCase()}` : ""}`; } -/** A row's number, as its marker shows it: the seq once sent, D1, D2... for drafts, null for a note no marker shows. */ /** Whether a sent note was withdrawn, here or, after a reload, as the bridge reports. */ const gone = (m) => Boolean(m && (m.withdrawn || last.notes.some((n) => n.seq === m.seq && n.withdrawn))); +/** A row's number, as its marker shows it: the seq once sent, D1, D2... for drafts, null for a note no marker shows. */ const numberOf = (m) => m.seq ?? (m.draft ? `D${mine.filter((x) => x.draft).indexOf(m) + 1}` : null); /** What the frame needs to find a note's box and restore its view: contract keys, a path and a box, never its text. */ function noteTarget(m) { diff --git a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js index 67df4741b9..b060114b76 100644 --- a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js +++ b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser-take.js @@ -22,7 +22,8 @@ async page => { await said(`Note ${i + 1} sent`); } - await page.click('[data-key^="edit-"]'); + await rows.nth(0).locator(".text").click(); + await rows.nth(0).locator('[data-key^="edit-"]').click(); await page.waitForSelector("#composer:not([hidden])", { timeout: 5000 }); ok("Edit on sent note 1 opens the editor on its text, with no Save draft", (await page.textContent("#composer-label")) === "Edit note 1" && (await page.inputValue("#text")) === "Bolder parcel ids." && await page.isHidden("#save")); @@ -37,6 +38,7 @@ async page => { await page.waitForFunction(() => document.querySelectorAll("#notes li").length === 2, null, { timeout: 5000 }).catch(() => {}); ok("after a reload note 1 is listed with its edited text", (await rows.nth(0).locator(".text").textContent()) === "Bolder and larger parcel ids."); + await rows.nth(1).locator(".text").click(); await rows.nth(1).locator('[data-key^="withdraw-"]').click(); await said("Note 2 withdrawn"); ok("a withdrawn note is listed as withdrawn, not pending, with no actions", diff --git a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh index a2d0b56560..566b331f67 100755 --- a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh +++ b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh @@ -7,7 +7,7 @@ skill=$(cd "$here/.." && pwd) bridge=$(cd "$skill/../../notes-bridge" && pwd) # shellcheck source=../../../lib/browser-test-helpers.sh source "$here/../../../lib/browser-test-helpers.sh" -browser_setup ed-notes-edit ede playwright-cli python3 curl +browser_setup ed-notes-edit edxplaywright-cli python3 curl marker='' while IFS= read -r line; do From 9468ec562ad6e11752ffdca5925501c1ab306406 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:07:31 -0500 Subject: [PATCH 4/7] fix(prototype): restore the space after the notes-edit session prefix The prefix rename joined edx and playwright-cli into one argument, so browser_setup took edxplaywright-cli as the session prefix and never checked for playwright-cli. Co-Authored-By: Claude Opus 5.5 --- .../explore-directions/scripts/notes-edit-browser.test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh index 566b331f67..7cef64c00b 100755 --- a/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh +++ b/plugins/prototype/skills/explore-directions/scripts/notes-edit-browser.test.sh @@ -7,7 +7,7 @@ skill=$(cd "$here/.." && pwd) bridge=$(cd "$skill/../../notes-bridge" && pwd) # shellcheck source=../../../lib/browser-test-helpers.sh source "$here/../../../lib/browser-test-helpers.sh" -browser_setup ed-notes-edit edxplaywright-cli python3 curl +browser_setup ed-notes-edit edx playwright-cli python3 curl marker='' while IFS= read -r line; do From 5ef94650cbd635d53bd7eb4cbda502bdc4050f50 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:36:03 -0500 Subject: [PATCH 5/7] test(ui-feedback): move the edit and withdraw bridge tests to their own file TestEditAndWithdraw pushed test_notes_bridge.py across the 1000-line size reference. It is one concern, editing and withdrawing a sent note, so it moves whole to test_notes_edit.py and imports the shared case and fixtures. Co-Authored-By: Claude Opus 5.5 --- lib/ui-feedback/test_notes_bridge.py | 97 ----------------------- lib/ui-feedback/test_notes_edit.py | 113 +++++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 97 deletions(-) create mode 100644 lib/ui-feedback/test_notes_edit.py diff --git a/lib/ui-feedback/test_notes_bridge.py b/lib/ui-feedback/test_notes_bridge.py index 234027e2d6..105807e12a 100644 --- a/lib/ui-feedback/test_notes_bridge.py +++ b/lib/ui-feedback/test_notes_bridge.py @@ -654,103 +654,6 @@ def test_a_change_without_the_token_is_refused(self): self.assertEqual(code, 403) -class TestEditAndWithdraw(NotesCase): - """POST /api/note/edit and /api/note/withdraw: a sent note corrected or taken back.""" - - def edit(self, msg, **kw): - return self.request("POST", "/api/note/edit", msg, **kw) - - def withdraw(self, msg, **kw): - return self.request("POST", "/api/note/withdraw", msg, **kw) - - def wait(self, after): - code, body = self.request( - "GET", - f"/api/wait?after={after}&timeout=5", - headers={"X-Notes-Token": self.hub.watch_token}, - token=False, - ) - self.assertEqual(code, 200) - return body - - def status(self): - out = io.StringIO() - with contextlib.redirect_stdout(out): - nb.cmd_status(self.dir, None) - return json.loads(out.getvalue())["events"] - - def test_every_fixture_edit_and_withdraw_is_judged_as_the_fixtures_say(self): - for kind in ("edit", "withdraw"): - node = nb.SCHEMA["$defs"][kind] - for case in FIXTURES[f"{kind}s"]["valid"]: - self.assertEqual(nb.problems(case[kind], node, kind), [], case["why"]) - for case in FIXTURES[f"{kind}s"]["invalid"]: - self.assertNotEqual(nb.problems(case[kind], node, kind), [], case["why"]) - - def test_an_edit_replaces_the_text_and_reaches_the_session_naming_the_note(self): - self.note() - self.assertEqual([e["seq"] for e in self.wait(0)["events"]], [1]) - code, body = self.edit({"edit": 1, "text": "Bolder, and larger."}) - self.assertEqual((code, body["seq"]), (200, 2)) - first, second = self.hub.read_log()["events"] - self.assertEqual((first["seq"], first["text"]), (1, "Bolder, and larger.")) - self.assertEqual({k: second[k] for k in ("seq", "edit", "text")}, {"seq": 2, "edit": 1, "text": "Bolder, and larger."}) - self.assertNotIn("kind", second) - events = self.wait(1)["events"] - self.assertEqual([(e["seq"], e["edit"], e["text"]) for e in events], [(2, 1, "Bolder, and larger.")]) - state, _ = self.hub.read_state() - self.assertEqual([n["seq"] for n in state["notes"]], [1]) - - def test_an_edited_note_reloads_as_a_note_the_contract_admits(self): - self.note() - self.edit({"edit": 1, "text": "Bolder, and larger."}) - _, body = self.request("GET", "/api/notes") - notes = [n for n in body["notes"] if not nb.problems({k: v for k, v in n.items() if k not in ("seq", "at")})] - self.assertEqual([(n["seq"], n["text"]) for n in notes], [(1, "Bolder, and larger.")]) - - def test_a_withdraw_marks_the_note_withdrawn_and_tells_the_session(self): - self.note() - self.note({**NOTE, "text": "Second."}) - code, body = self.withdraw({"withdraw": 1}) - self.assertEqual((code, body["seq"]), (200, 3)) - self.assertEqual(self.hub.read_log()["events"][2]["withdraw"], 1) - state, _ = self.hub.read_state() - self.assertEqual([(n["seq"], n.get("withdrawn")) for n in state["notes"]], [(1, True), (2, None)]) - self.assertEqual([e["seq"] for e in self.wait("handled")["events"]], [2, 3]) - self.assertEqual([e["seq"] for e in self.status()], [2, 3]) - - def test_a_withdrawn_note_is_not_edited_moved_or_withdrawn_again(self): - self.note(REGION) - self.withdraw({"withdraw": 1}) - self.assertEqual(self.edit({"edit": 1, "text": "x"})[0], 400) - self.assertEqual(self.withdraw({"withdraw": 1})[0], 400) - self.assertEqual(self.request("POST", "/api/note/change", {"change": 1, **MOVED})[0], 400) - self.assertEqual(len(self.hub.read_log()["events"]), 2) - - def test_an_edit_or_withdraw_is_refused_unless_it_names_a_sent_note(self): - self.note() - self.edit({"edit": 1, "text": "x"}) - for why, call, msg in ( - ("no such note", self.edit, {"edit": 9, "text": "x"}), - ("an edit, not a note", self.edit, {"edit": 2, "text": "x"}), - ("empty text", self.edit, {"edit": 1, "text": ""}), - ("no such note", self.withdraw, {"withdraw": 9}), - ("an edit, not a note", self.withdraw, {"withdraw": 2}), - ("a field a withdraw does not carry", self.withdraw, {"withdraw": 1, "text": "x"}), - ): - self.assertEqual(call(msg)[0], 400, why) - self.assertEqual(len(self.hub.read_log()["events"]), 2) - self.assertEqual(self.edit({"edit": 1, "text": "x"}, token=False)[0], 403) - self.assertEqual(self.withdraw({"withdraw": 1}, token=False)[0], 403) - - def test_a_log_written_before_edits_and_withdraws_still_loads(self): - old = {"seq": 1, "events": [{"seq": 1, "at": "2026-11-01T00:00:00Z", **NOTE}]} - (self.dir / "actions.json").write_text(json.dumps(old), encoding="utf-8") - state, _ = self.hub.read_state() - self.assertEqual([n["seq"] for n in state["notes"]], [1]) - self.assertEqual([e["text"] for e in self.status()], [NOTE["text"]]) - - class TestImport(unittest.TestCase): """import with no server: a copy-out block written to a file goes through the note contract.""" diff --git a/lib/ui-feedback/test_notes_edit.py b/lib/ui-feedback/test_notes_edit.py new file mode 100644 index 0000000000..2df0166dda --- /dev/null +++ b/lib/ui-feedback/test_notes_edit.py @@ -0,0 +1,113 @@ +"""Tests for editing and withdrawing a sent note through notes-bridge: an edit keeps the note's seq, +a withdraw is logged as its own event, and status and the watcher drop a withdrawn note. + + python3 -m unittest test_notes_edit (from lib/ui-feedback/) +""" + +import contextlib +import io +import json +import unittest + +from test_notes_bridge import FIXTURES, MOVED, NOTE, REGION, NotesCase, nb + + +class TestEditAndWithdraw(NotesCase): + """POST /api/note/edit and /api/note/withdraw: a sent note corrected or taken back.""" + + def edit(self, msg, **kw): + return self.request("POST", "/api/note/edit", msg, **kw) + + def withdraw(self, msg, **kw): + return self.request("POST", "/api/note/withdraw", msg, **kw) + + def wait(self, after): + code, body = self.request( + "GET", + f"/api/wait?after={after}&timeout=5", + headers={"X-Notes-Token": self.hub.watch_token}, + token=False, + ) + self.assertEqual(code, 200) + return body + + def status(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + nb.cmd_status(self.dir, None) + return json.loads(out.getvalue())["events"] + + def test_every_fixture_edit_and_withdraw_is_judged_as_the_fixtures_say(self): + for kind in ("edit", "withdraw"): + node = nb.SCHEMA["$defs"][kind] + for case in FIXTURES[f"{kind}s"]["valid"]: + self.assertEqual(nb.problems(case[kind], node, kind), [], case["why"]) + for case in FIXTURES[f"{kind}s"]["invalid"]: + self.assertNotEqual(nb.problems(case[kind], node, kind), [], case["why"]) + + def test_an_edit_replaces_the_text_and_reaches_the_session_naming_the_note(self): + self.note() + self.assertEqual([e["seq"] for e in self.wait(0)["events"]], [1]) + code, body = self.edit({"edit": 1, "text": "Bolder, and larger."}) + self.assertEqual((code, body["seq"]), (200, 2)) + first, second = self.hub.read_log()["events"] + self.assertEqual((first["seq"], first["text"]), (1, "Bolder, and larger.")) + self.assertEqual({k: second[k] for k in ("seq", "edit", "text")}, {"seq": 2, "edit": 1, "text": "Bolder, and larger."}) + self.assertNotIn("kind", second) + events = self.wait(1)["events"] + self.assertEqual([(e["seq"], e["edit"], e["text"]) for e in events], [(2, 1, "Bolder, and larger.")]) + state, _ = self.hub.read_state() + self.assertEqual([n["seq"] for n in state["notes"]], [1]) + + def test_an_edited_note_reloads_as_a_note_the_contract_admits(self): + self.note() + self.edit({"edit": 1, "text": "Bolder, and larger."}) + _, body = self.request("GET", "/api/notes") + notes = [n for n in body["notes"] if not nb.problems({k: v for k, v in n.items() if k not in ("seq", "at")})] + self.assertEqual([(n["seq"], n["text"]) for n in notes], [(1, "Bolder, and larger.")]) + + def test_a_withdraw_marks_the_note_withdrawn_and_tells_the_session(self): + self.note() + self.note({**NOTE, "text": "Second."}) + code, body = self.withdraw({"withdraw": 1}) + self.assertEqual((code, body["seq"]), (200, 3)) + self.assertEqual(self.hub.read_log()["events"][2]["withdraw"], 1) + state, _ = self.hub.read_state() + self.assertEqual([(n["seq"], n.get("withdrawn")) for n in state["notes"]], [(1, True), (2, None)]) + self.assertEqual([e["seq"] for e in self.wait("handled")["events"]], [2, 3]) + self.assertEqual([e["seq"] for e in self.status()], [2, 3]) + + def test_a_withdrawn_note_is_not_edited_moved_or_withdrawn_again(self): + self.note(REGION) + self.withdraw({"withdraw": 1}) + self.assertEqual(self.edit({"edit": 1, "text": "x"})[0], 400) + self.assertEqual(self.withdraw({"withdraw": 1})[0], 400) + self.assertEqual(self.request("POST", "/api/note/change", {"change": 1, **MOVED})[0], 400) + self.assertEqual(len(self.hub.read_log()["events"]), 2) + + def test_an_edit_or_withdraw_is_refused_unless_it_names_a_sent_note(self): + self.note() + self.edit({"edit": 1, "text": "x"}) + for why, call, msg in ( + ("no such note", self.edit, {"edit": 9, "text": "x"}), + ("an edit, not a note", self.edit, {"edit": 2, "text": "x"}), + ("empty text", self.edit, {"edit": 1, "text": ""}), + ("no such note", self.withdraw, {"withdraw": 9}), + ("an edit, not a note", self.withdraw, {"withdraw": 2}), + ("a field a withdraw does not carry", self.withdraw, {"withdraw": 1, "text": "x"}), + ): + self.assertEqual(call(msg)[0], 400, why) + self.assertEqual(len(self.hub.read_log()["events"]), 2) + self.assertEqual(self.edit({"edit": 1, "text": "x"}, token=False)[0], 403) + self.assertEqual(self.withdraw({"withdraw": 1}, token=False)[0], 403) + + def test_a_log_written_before_edits_and_withdraws_still_loads(self): + old = {"seq": 1, "events": [{"seq": 1, "at": "2026-11-01T00:00:00Z", **NOTE}]} + (self.dir / "actions.json").write_text(json.dumps(old), encoding="utf-8") + state, _ = self.hub.read_state() + self.assertEqual([n["seq"] for n in state["notes"]], [1]) + self.assertEqual([e["text"] for e in self.status()], [NOTE["text"]]) + + +if __name__ == "__main__": + unittest.main() From cd5413e217de9549e14104b443e2ef0767ad5af8 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:43:54 -0500 Subject: [PATCH 6/7] test(ui-feedback): declare what test_notes_edit.py reads through its import It imports test_notes_bridge, so it reads the session bridge, the controls and notes fixtures and schemas, and proto-pin.js; a change to any of them must select it (scripts/affected-tests.sh R8). Co-Authored-By: Claude Opus 5.5 --- lib/ui-feedback/test_notes_edit.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/ui-feedback/test_notes_edit.py b/lib/ui-feedback/test_notes_edit.py index 2df0166dda..8351819fc8 100644 --- a/lib/ui-feedback/test_notes_edit.py +++ b/lib/ui-feedback/test_notes_edit.py @@ -1,3 +1,6 @@ +# test-scope: lib/ui-feedback/test_notes_bridge.py lib/session-bridge/session_bridge.py lib/session-bridge/view_bridge.py +# test-scope: lib/ui-feedback/controls.js lib/ui-feedback/controls.schema.json lib/ui-feedback/fixtures/controls.json +# test-scope: lib/ui-feedback/fixtures/notes.json lib/ui-feedback/note.schema.json lib/ui-feedback/proto-pin.js """Tests for editing and withdrawing a sent note through notes-bridge: an edit keeps the note's seq, a withdraw is logged as its own event, and status and the watcher drop a withdrawn note. From b13106953bdb232f6c5cb5393e0bafc0421015f1 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:50:52 -0500 Subject: [PATCH 7/7] test(prototype): wait for the copy-out status line before checking it The host writes "Copied the chosen design" only once the clipboard write resolves, so reading the status right after the copied text appears raced it and failed on a slower runner. Also declare notes_bridge.py in test_notes_edit.py's scope (scripts/affected-tests.sh R8). Co-Authored-By: Claude Opus 5.5 --- lib/ui-feedback/test_notes_edit.py | 2 +- .../explore-directions/scripts/notes-copyout-browser-take.js | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/ui-feedback/test_notes_edit.py b/lib/ui-feedback/test_notes_edit.py index 8351819fc8..e27bd6e9c1 100644 --- a/lib/ui-feedback/test_notes_edit.py +++ b/lib/ui-feedback/test_notes_edit.py @@ -1,4 +1,4 @@ -# test-scope: lib/ui-feedback/test_notes_bridge.py lib/session-bridge/session_bridge.py lib/session-bridge/view_bridge.py +# test-scope: lib/ui-feedback/test_notes_bridge.py lib/ui-feedback/notes_bridge.py lib/session-bridge/session_bridge.py lib/session-bridge/view_bridge.py # test-scope: lib/ui-feedback/controls.js lib/ui-feedback/controls.schema.json lib/ui-feedback/fixtures/controls.json # test-scope: lib/ui-feedback/fixtures/notes.json lib/ui-feedback/note.schema.json lib/ui-feedback/proto-pin.js """Tests for editing and withdrawing a sent note through notes-bridge: an edit keeps the note's seq, diff --git a/plugins/prototype/skills/explore-directions/scripts/notes-copyout-browser-take.js b/plugins/prototype/skills/explore-directions/scripts/notes-copyout-browser-take.js index a02fce506a..305cf46750 100644 --- a/plugins/prototype/skills/explore-directions/scripts/notes-copyout-browser-take.js +++ b/plugins/prototype/skills/explore-directions/scripts/notes-copyout-browser-take.js @@ -28,6 +28,7 @@ async page => { await settle(block, A); ok("Copy chosen design copies the shown variant's copy-out text", (await block()) === A, await block()); ok("it is the text the page's own copy-out gives", (await block()) === (await frame.evaluate(() => window.uiFeedbackCopyOut()))); + await settle(async () => /Copied the chosen design/.test(await status()), true); ok("the copy is said in the status line", /Copied the chosen design/.test(await status()), await status()); await page.click("#vnext");