diff --git a/scripts/test-web-console-logic.mjs b/scripts/test-web-console-logic.mjs index cb4b362..7a9e051 100644 --- a/scripts/test-web-console-logic.mjs +++ b/scripts/test-web-console-logic.mjs @@ -62,6 +62,9 @@ import { MAX_NOTE_IMAGES, noteAction, noteReplyLines, + pruneStaged, + suggestAction, + suggestReplyLines, progressTotal, quietLimitMs, resumeCommand, @@ -515,6 +518,69 @@ test("a note with documents splits them into files, keeps attach order in its li ]); }); +test("a request for suggestions reads apart from a note, with its note and attachments", () => { + assert.deepEqual(suggestReplyLines("Export format", "Which suits Excel?", []), ["Suggestions wanted on Export format: Which suits Excel?"]); + assert.deepEqual(suggestReplyLines("Export format", "", []), ["Suggestions wanted on Export format: (no note)"]); + assert.deepEqual(suggestReplyLines("Export format", "", undefined), ["Suggestions wanted on Export format: (no note)"]); + assert.deepEqual(suggestReplyLines("Export format", "Line one\nLine two", []), [ + "Suggestions wanted on Export format: Line one\n Line two", + ]); + const atts = [ + { key: "k1", path: "C:\\x\\a.jpg", name: "shot.png", status: "ready" }, + { key: "k2", kind: "file", path: "C:\\x\\b.pdf", name: "spec.pdf", status: "ready" }, + ]; + assert.deepEqual(suggestReplyLines("Export format", "See these", atts), [ + "Suggestions wanted on Export format: See these", + " Image: C:\\x\\a.jpg (shot.png)", + " File: C:\\x\\b.pdf (spec.pdf)", + ]); + assert.deepEqual(suggestAction("q1", "See these", atts), { + i: "q1", + type: "comment", + text: "See these", + images: [{ path: "C:\\x\\a.jpg", name: "shot.png" }], + files: [{ path: "C:\\x\\b.pdf", name: "spec.pdf" }], + suggest: true, + }); + assert.deepEqual(suggestAction("q1", "", []), { i: "q1", type: "comment", text: "", suggest: true }); +}); + +test("pruneStaged drops only the picks a re-posted card no longer offers, without touching its inputs", () => { + const opts = (...ks) => ks.map((k) => ({ k, text: k })); + const items = [ + { id: "c1", kind: "choice", options: opts("A", "B") }, + { id: "c2", kind: "choice", options: opts("A") }, + { id: "m1", kind: "multi", options: opts("1", "3") }, + { id: "m2", kind: "multi", options: opts("1") }, + { id: "f1", kind: "confirm" }, + { id: "u1", kind: "choice", options: opts("A", "B") }, + ]; + const staged = { + c1: { type: "answer", kind: "choice", k: "C" }, + c2: { type: "answer", kind: "choice", k: "B", text: "or something else" }, + m1: { type: "answer", kind: "multi", ks: ["1", "2", "3"] }, + m2: { type: "answer", kind: "multi", ks: ["2"] }, + f1: { type: "answer", kind: "confirm", yes: true }, + u1: { type: "answer", kind: "choice", k: "B" }, + gone: { type: "answer", kind: "choice", k: "Z" }, + }; + const before = structuredClone(staged); + const itemsBefore = structuredClone(items); + const out = pruneStaged(items, staged); + assert.deepEqual(out.dropped.sort(), ["c1", "c2", "m1", "m2"]); + assert.equal("c1" in out.staged, false, "a choice left with nothing goes"); + assert.deepEqual(out.staged.c2, { type: "answer", kind: "choice", text: "or something else" }, "typed text keeps the entry"); + assert.deepEqual(out.staged.m1.ks, ["1", "3"], "a multi keeps the keys still offered"); + assert.equal("m2" in out.staged, false, "a multi left empty goes"); + assert.equal(out.staged.f1, staged.f1, "a confirm is left alone"); + assert.equal(out.staged.u1, staged.u1, "an unchanged card is left alone"); + assert.equal(out.staged.gone, staged.gone, "an id not among the items is left alone"); + assert.notEqual(out.staged, staged, "a new object comes back"); + assert.deepEqual(staged, before, "staged is not changed"); + assert.deepEqual(items, itemsBefore, "items are not changed"); + assert.deepEqual(pruneStaged(items, { u1: staged.u1 }), { staged: { u1: staged.u1 }, dropped: [] }); +}); + test("document helpers: the extension allow-list, the picker's accept, sizes, and the kind of an old entry", () => { assert.equal(MAX_ATTACHMENTS, 5); assert.equal(MAX_DOC_BYTES, 10 * 1024 * 1024); diff --git a/scripts/test-web-console-send-state.mjs b/scripts/test-web-console-send-state.mjs index 10a6188..934c9cc 100644 --- a/scripts/test-web-console-send-state.mjs +++ b/scripts/test-web-console-send-state.mjs @@ -8,7 +8,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { page, fresh } from "../src/web-console/public/state.js"; import { WORKING_GRACE_MS } from "../src/web-console/public/selectors.js"; -import { sendState } from "../src/web-console/public/send-state.js"; +import { sendState, suggestState } from "../src/web-console/public/send-state.js"; const MIN = 60 * 1000; const ago = (ms) => new Date(Date.now() - ms).toISOString(); @@ -151,3 +151,36 @@ test("send state: a note waits while its picture uploads, and goes once it is re page.local.images.q1 = [{ key: "a", status: "ready", url: "/uploads/a.jpg" }]; assert.deepEqual(sendState(), { disabled: false, why: "" }); }); + +test("send state: told there is something to send, an idle page enables it with nothing staged", () => { + setup(); + assert.deepEqual(sendState(), { disabled: true, why: "" }, "left out, it reads what is staged"); + assert.deepEqual(sendState(true), { disabled: false, why: "" }); + assert.deepEqual(sendState(false), { disabled: true, why: "" }); +}); + +test("suggest state: the chip follows Send, and waits while its own request does", () => { + const ready = { disabled: false, why: "Ask Plan2Code what it would pick here, and why." }; + setup(); + assert.deepEqual(suggestState(question()), ready, "nothing staged is needed: the request is the payload"); + + setup({ finish: { headline: "Phase 3 is done" } }); + assert.deepEqual(suggestState(question()), { disabled: true, why: "This session is finished." }); + + setup(); + page.pendingResult = true; + assert.deepEqual(suggestState(question()), { disabled: true, why: "Your last answers are on their way. One moment." }); + + const at = ago(MIN); + const asked = question("q1", { sentNote: { at, text: "", suggest: true }, thread: [{ who: "user", at, text: "", suggest: true }] }); + setup({ items: [asked] }); + assert.deepEqual(suggestState(asked), { disabled: true, why: "Plan2Code has your request for suggestions on this one." }); + + const plain = question("q1", { sentNote: { at, text: "Hm" }, thread: [{ who: "user", at, text: "Hm" }] }); + setup({ items: [plain] }); + assert.deepEqual(suggestState(plain), ready, "a plain note waiting does not hold the chip"); + + const replied = { ...asked, thread: [...asked.thread, { who: "agent", at: ago(0), text: "I would pick CSV." }] }; + setup({ items: [replied] }); + assert.deepEqual(suggestState(replied), ready, "the agent's reply frees it"); +}); diff --git a/scripts/test-web-console-session.mjs b/scripts/test-web-console-session.mjs index 4ec1e9b..3fe5e50 100644 --- a/scripts/test-web-console-session.mjs +++ b/scripts/test-web-console-session.mjs @@ -1281,6 +1281,30 @@ test("a send records its note and attachments on the item, so the page can show assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0); }); +test("a request for suggestions is recorded with its flag and threaded even with no note; a non-boolean flag is dropped", async () => { + const readState = () => JSON.parse(fs.readFileSync(path.join(HOME, "sessions", sid, "state.json"), "utf8")); + const userCount = () => readState().items.find((i) => i.id === "q1").thread.filter((m) => m.who === "user").length; + + let before = userCount(); + const ok = await post("/submit", { actions: [{ i: "q1", type: "comment", text: "", suggest: true }], reply: "Suggestions wanted on q1: (no note)" }); + assert.equal(ok.status, 200); + let q1 = readState().items.find((i) => i.id === "q1"); + assert.equal(q1.sentNote.suggest, true); + const mine = q1.thread.filter((m) => m.who === "user").at(-1); + assert.equal(userCount(), before + 1, "an empty request still goes into the thread"); + assert.equal(mine.who, "user"); + assert.equal(mine.suggest, true); + assert.equal(mine.at, q1.sentNote.at); + assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0); + + before = userCount(); + assert.equal((await post("/submit", { actions: [{ i: "q1", type: "comment", text: "", suggest: "yes" }], reply: "z" })).status, 200); + q1 = readState().items.find((i) => i.id === "q1"); + assert.equal("suggest" in q1.sentNote, false, "only true is kept"); + assert.equal(userCount(), before, "a plain empty comment still adds no thread entry"); + assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0); +}); + test("what the person attached is not scanned for markers either", () => { const statePath = path.join(HOME, "sessions", sid, "state.json"); const state = JSON.parse(fs.readFileSync(statePath, "utf8")); diff --git a/src/web-console/public/answers.js b/src/web-console/public/answers.js index 77fbac6..94a1314 100644 --- a/src/web-console/public/answers.js +++ b/src/web-console/public/answers.js @@ -1022,6 +1022,61 @@ export function noteReplyLines(title, text, attachments) { ]; } +// A request for suggestions on a card: a note's action flagged `suggest`, so +// the server records it as one and the page can tell it from a plain note. +export function suggestAction(id, text, attachments) { + return { ...noteAction(id, text, attachments), suggest: true }; +} + +// The same request as `reply` lines. Its lead differs from `Note on` on +// purpose: that is how the agent tells a request for suggestions from a note. +export function suggestReplyLines(title, text, attachments) { + const list = attachments || []; + return [ + `Suggestions wanted on ${title}: ${indentReply(text || "(no note)")}`, + ...list.map((a) => ` ${attachmentKind(a) === "file" ? "File" : "Image"}: ${a.path} (${a.name})`), + ]; +} + +/* --------------------------------------------------------- stale picks */ + +/** + * Staged picks that a re-posted card no longer offers, dropped. A `choice` + * loses a `k` its options no longer carry; a `multi` keeps only the `ks` + * still there. An entry left with nothing meaningful goes. Every other kind, + * and any id not among `items`, stays as it was. `dropped` lists the ids that + * lost a pick. The inputs are never changed. + */ +export function pruneStaged(items, staged) { + const out = { ...(staged || {}) }; + const dropped = []; + const byId = new Map((items || []).filter((it) => it && it.id).map((it) => [it.id, it])); + for (const [id, v] of Object.entries(out)) { + const item = byId.get(id); + if (!item || !v || typeof v !== "object" || (item.kind !== "choice" && item.kind !== "multi")) continue; + const keys = new Set((item.options || []).map((o) => o && o.k)); + const next = { ...v }; + let lost = false; + if (item.kind === "choice" && next.k && !keys.has(next.k)) { + delete next.k; + lost = true; + } + if (item.kind === "multi" && Array.isArray(next.ks)) { + const kept = next.ks.filter((k) => keys.has(k)); + if (kept.length !== next.ks.length) { + next.ks = kept; + lost = true; + } + } + if (!lost) continue; + dropped.push(id); + const left = next.k || (Array.isArray(next.ks) && next.ks.length) || next.text || next.verdict || next.skipped; + if (left) out[id] = next; + else delete out[id]; + } + return { staged: out, dropped }; +} + /* ------------------------------------------------------------ patience */ /** diff --git a/src/web-console/public/app.js b/src/web-console/public/app.js index 7dd4199..c81c148 100644 --- a/src/web-console/public/app.js +++ b/src/web-console/public/app.js @@ -19,7 +19,7 @@ import { page, onRedraw, onSave, useHooks, bootData } from "./state.js"; import { - adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter, + adopt, askSuggestions, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter, renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope, wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding, wireActivities, wireLoopSetup, wireHelp, launchSkill, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace, @@ -36,7 +36,7 @@ import { sound } from "./sound.js"; // and the few calls a screen makes into another are handed to state.js first. onSave(save); useHooks({ - launchSkill, openHelpOn, openLoopSetup, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope, + launchSkill, openHelpOn, openLoopSetup, askSuggestions, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope, openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen, }); diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index 0684513..84f371f 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -32,6 +32,8 @@ import { sentAnswer, staleLaunchFeedback, submittedAwaiting, + suggestAction, + suggestReplyLines, verdictText, workflowLabel, workflowTitle, @@ -63,7 +65,7 @@ import { renderLaunching, renderWaiting } from "./starting.js"; import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js"; import { closeMentions } from "../mention-box.js"; import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js"; -import { sendState } from "../send-state.js"; +import { sendState, suggestState } from "../send-state.js"; import { renderBriefButton, renderDoc, renderOverview } from "./docs.js"; import { board, renderGitBoard, resetBoard } from "./git-host.js"; import { renderWorkspace, tellFolderIssues } from "./workspace.js"; @@ -1973,10 +1975,7 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) { for (const id of sentIds) { for (const prefix of ["other-", "text-", "note-"]) delete page.local.drafts[prefix + id]; if (sentNotes[id]) { - delete page.local.drafts["thread-" + id]; - const rest = noteImages(id).filter((img) => !sentNotes[id].has(img.key)); - if (rest.length) page.local.images[id] = rest; - else delete page.local.images[id]; + clearSentNote(id, sentNotes[id]); } else if (!page.local.images[id]) { delete page.local.drafts["thread-" + id]; } @@ -1997,6 +1996,58 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) { save(); } +// A card's note went: its draft goes, and of its attachments only those whose +// `key` is not in `keys` (the ones that did not go with it) stay. Shared by +// Send and the suggestion send. +export function clearSentNote(id, keys) { + delete page.local.drafts["thread-" + id]; + const rest = noteImages(id).filter((img) => !keys.has(img.key)); + if (rest.length) page.local.images[id] = rest; + else delete page.local.images[id]; +} + +// The Ask for suggestions chip: one request for suggestions on one card, with +// the card's ready note riding along. Its own send, beside Send: nothing +// staged goes or is cleared, and the card stays open to answer. +export async function askSuggestions(itemId) { + const item = byId(itemId); + if (!item || suggestState(item).disabled) return; + const note = pendingNotes().find((n) => n.id === itemId); + const text = note ? note.text : ""; + const images = note ? note.images : []; + try { + const res = await fetch("/submit", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + actions: [suggestAction(itemId, text, images)], + reply: suggestReplyLines(item.title, text, images).join("\n"), + }), + }); + if (res.status === 409) { + banner( + "Your last answers are still being picked up. Nothing is lost, and nothing was sent twice. Try again in a moment.", + "info" + ); + page.pendingBannerUp = true; + page.pendingResult = true; + } else if (!res.ok) { + const body = await res.json().catch(() => null); + banner(refusedLine({ status: res.status, reason: (body && (body.message || body.error)) || `error ${res.status}` }), "warn"); + } else { + // A note held back on an upload did not go, so it stays drafted. + if (note) clearSentNote(itemId, new Set(images.map((i) => i.key))); + save(); + banner("Asked for suggestions. Plan2Code is picking it up now.", "good"); + setTimeout(() => banner(null), 4000); + } + } catch { + await sendLost(); + } finally { + render(); + } +} + // The menu card whose staged pick is an option marked `fresh`, if any. function freshMenuPick(actions) { for (const a of actions) { diff --git a/src/web-console/public/send-state.js b/src/web-console/public/send-state.js index 94f9bcc..19be630 100644 --- a/src/web-console/public/send-state.js +++ b/src/web-console/public/send-state.js @@ -14,11 +14,14 @@ import { loopDriving, loopWaiting, } from "./selectors.js"; -import { finishPaused } from "./answers.js"; +import { finishPaused, noteAwaiting } from "./answers.js"; import { page } from "./state.js"; import { pendingNotes } from "./uploads.js"; -export function sendState() { +// `hasPayload` says whether there is something to send; left out, it is what +// the main Send would carry. The suggestion chip passes `true`: its request is +// the payload. +export function sendState(hasPayload = stagedCount() || pendingNotes().length > 0) { // Before `gone`, and before the grace period that can re-enable a send. A // finished session has nobody left to send to, whatever the socket says. if (finish()) @@ -48,7 +51,7 @@ export function sendState() { // "waiting" before asking, but an agent that asks and carries on ("while // you decide") must not lock the person out of answering for up to an // hour of quietMinutes. - if (myTurn().length && (stagedCount() || pendingNotes().length)) { + if (myTurn().length && hasPayload) { return { disabled: false, why: "Plan2Code is still working. Your answers wait for it to look.", @@ -65,7 +68,7 @@ export function sendState() { // duration printed here freezes between them, and a frozen number // beside "is it stuck?" makes the page look like the thing it is // warning about. The exact time already ticks away in the dock. - if (stagedCount() || pendingNotes().length) { + if (hasPayload) { return { disabled: false, why: "Plan2Code has been busy a while. You can send anyway.", short: "Busy ยท send anyway" }; } return openItems().length @@ -78,6 +81,15 @@ export function sendState() { } return { disabled: true, why: "Wait for Plan2Code to finish.", short: agentAdrift() ? "Gone quiet" : "" }; } - if (!stagedCount() && !pendingNotes().length) return { disabled: true, why: "" }; + if (!hasPayload) return { disabled: true, why: "" }; return { disabled: false, why: "" }; } + +// Whether the Ask for suggestions chip on `item` can fire, and why not. One +// request for suggestions waits at a time per card; otherwise it follows Send. +export function suggestState(item) { + const note = noteAwaiting(item); + if (note && note.suggest === true) return { disabled: true, why: "Plan2Code has your request for suggestions on this one." }; + const { disabled, why } = sendState(true); + return { disabled, why: why || (disabled ? "" : "Ask Plan2Code what it would pick here, and why.") }; +} diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index 45227d6..acc3f7e 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -1242,11 +1242,18 @@ function recordSubmitted(state, actions) { if (!item) continue; if (action.type === "comment") { const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []); - item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) }; + item.sentNote = { + at, + text: String(action.text || ""), + images: pick(action.images), + files: pick(action.files), + ...(action.suggest === true ? { suggest: true } : {}), + }; // The person's side of the Notes thread. Left to the agent it was never // written, so a question asked in a note vanished once it was picked up - // and the reply under it answered nothing on the page. - if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) { + // and the reply under it answered nothing on the page. A request for + // suggestions is always written, note or not. + if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length || item.sentNote.suggest) { item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }]; } continue;