diff --git a/docs/studio/CONTEXT.md b/docs/studio/CONTEXT.md index 323abd25..b2043cc7 100644 --- a/docs/studio/CONTEXT.md +++ b/docs/studio/CONTEXT.md @@ -34,7 +34,7 @@ One sentence, at most 16 words, on what a turn did, or what it waits on: an outc _Avoid_: Intention (the agent's own words while it works) **Turn summary**: -A Headline and up to three typed Body lines, written by one cheap writer call when the turn ends, or when Daniel opens the turn if summaries are set to write on open. A turn gets one when its final response is about 150 words or more, or when it ends asking Daniel something; other turns show their response as it is. The writer is given the turn's recorded facts (its files with their line counts, hunks up to a cap, each check's command, result and retries) and told not to restate them. A Body line is `why`, `reported`, `open` or `ask`, at most 20 words; `open` and `ask` always show, and a `reported` line reads "Agent says". A line with a number or id the turn's material lacks is dropped; numbers in the turn's diff, line counts or check results, number words and digits in a known path always pass. A summary stored before the Headline is read with its first line as the Headline and the rest as `reported` lines; the writer is not run again on it. +A Headline and up to three typed Body lines, written by one cheap writer call when the turn ends, or when Daniel opens the turn if summaries are set to write on open. A turn gets one when its final response is about 150 words or more, when it ends asking Daniel something, or when it changed files; other turns show their response as it is. The writer is given the turn's recorded facts (its files with their line counts, hunks up to a cap, each check's command, result and retries) and told not to restate them. A Body line is `why`, `reported`, `open` or `ask`, at most 20 words; `open` and `ask` always show, and a `reported` line reads "Agent says". A line with a number or id the turn's material lacks is dropped; numbers in the turn's diff, line counts or check results, number words and digits in a known path always pass. A summary stored before the Headline is read with its first line as the Headline and the rest as `reported` lines; the writer is not run again on it. The same call writes the turn card's fields (spec #1062): `next`, at most three things the reply asks of Daniel or leaves for him, and `did`, at most three things the turn did, each at most 14 words, a `did` item read through the same "Agent says:" rule as the Headline; and `prompts`, at most two `agent` prompts, each backed by a `quote` of the final response checked word for word, and one `suggested`, the writer's own, with no quote, each at most 12 words. Each item obeys the number-and-id rule, and an item that breaks a rule or its limit is dropped, never cut, without asking the writer again; a list whose every item is dropped is stored as none, not as an empty list. A summary stored before these fields has none of them, which differs from an empty list. _Avoid_: Card (retired), brief (the whole session's, kept for resuming) **Transcript**: @@ -78,9 +78,13 @@ What Daniel reads to resume an agent session he lost track of, in **Context mode The banner the rail opened on when Daniel returned to a session, retired into **Context mode** (spec #967, Q40), whose "since you looked" line became the session panel's **Since you looked** timeline (spec #1019). The rail's mode is decided at the selection and kept while he reads, the mode's hold. **Context mode**: -The story rail's mode while the session doesn't need Daniel, in every session (spec #967), drawn as the session panel (spec #1019): a card (purpose, state, the touched parts with their **behaviour lines**, Show on map) and the **Since you looked** timeline. Pressing the card's purpose opens the Goal, his last decision and one fold, "N decided · N facts · #issue", holding the issue's title, the decisions (the decision history's questions and plans, and answered rounds), Open, Design so far and the facts, each **checked** (a turn's evidence line) or **the agent's claim** (a `reported` Body line). The header's chip and linked issue go with it. It absorbs **Where we were** and the folded **Brief**. +The story rail's mode while the session doesn't need Daniel, in every session (spec #967), drawn as the session panel (spec #1019): at Your turn and Idle the **turn card** above all, then a card (purpose, state, the touched parts with their **behaviour lines**, Show on map) and the **Since you looked** timeline. Pressing the card's purpose opens the Goal, his last decision and one fold, "N decided · N facts · #issue", holding the issue's title, the decisions (the decision history's questions and plans, and answered rounds), Open, Design so far and the facts, each **checked** (a turn's evidence line) or **the agent's claim** (a `reported` Body line). The header's chip and linked issue go with it. It absorbs **Where we were** and the folded **Brief**. _Avoid_: Context view, status card +**Turn card**: +The block that leads the session panel (**Context mode**) at Your turn and Idle (spec #1062): the newest turn's **Headline**, "You next" and "Agent did" as short numbered lists, its `open` Body lines as "Not done: …", its **Reply** row and a "Full reply" fold. The Reply row holds up to two pills the reply proposes (solid) and one plotkeeper suggests (dashed, ✦), and a box: a pill fills the box, and Enter sends it by **Send** (spec #1062, ticket #1069). A summary stored before the lists shows only its Headline, the box and the fold, and a turn with no summary its reply's first line, the box and the fold. None while the session runs or needs Daniel. +_Avoid_: Turn banner + **Decision mode**: The story rail's mode while the session needs Daniel (spec #967): the docked question, plan or permission with "Why it asks", a blocked command's note with the Jump, a waiting plan's plan view and, from ticket #978, a round's planning view. The rail's mode is decided when Daniel selects the session and held while he reads, in both directions; a new ask still docks at once. A new prompt, his answer in the view, or selecting the session again decides it afresh. @@ -157,6 +161,7 @@ _Avoid_: Reveal, jump to file (a **Jump** goes to a terminal) **Send**: The **Planning view**'s main answer, "Send in Herdr", which types a **Round**'s reply into a session that runs directly in Herdr.app through herdr-core's `hc send`, with the reply as one argument so quotes and newlines arrive as written (spec #967). A guard lets it through only when the session recorded a Herdr terminal id and its agent's pid, `hc get` within 5 seconds reports that pid as the terminal's foreground, the app as `claude-code`, and the state `idle` or `done`; otherwise the button is disabled and names the reason, and the copy button sits beside it. The guard is checked when the round opens, and again by the send itself, and `hc send` gets 65 seconds, above its wait for a draft of Daniel's. A send records the round answered on the page the moment it succeeds; a refusal or a failure leaves it open. Where Send can't type — outside Herdr, or with the guard refusing — the copy button reads "Copy & Jump" when the Jump knows the session's terminal, else "Copy reply" with the Jump's one-line reason; either copies the same reply, and a prompt pasted from it records the form's answers. +The **Turn card**'s box sends the same way (ticket #1069): Enter, or its "Send in Herdr", types the box's text with the generic `send` past the same guard, asked once per ended turn, after marking the session seen; no round is recorded. A sent prompt empties the box, and a failed one keeps it and says why. Where Send can't type, the box has Copy & Jump or Copy reply, copying its text, and Enter only says why, so it never copies or jumps on its own. **Wiring**: plotkeeper putting its hooks into an agent, such as Claude Code or Codex, only with the user's consent. Each agent found is wired, declined or not yet asked: a start in a terminal asks only about the agents not yet asked, a start with no terminal never asks or wires, `plotkeeper install` wires every agent found, and `plotkeeper uninstall` unwires them all and forgets the answers. diff --git a/docs/studio/assets/readme/spotlit.png b/docs/studio/assets/readme/spotlit.png index a56e4820..8b033346 100644 Binary files a/docs/studio/assets/readme/spotlit.png and b/docs/studio/assets/readme/spotlit.png differ diff --git a/docs/studio/behaviour/rail.md b/docs/studio/behaviour/rail.md index 0c21e938..d5f88d76 100644 --- a/docs/studio/behaviour/rail.md +++ b/docs/studio/behaviour/rail.md @@ -18,6 +18,10 @@ A plan whose files could not be read says "The plan's files could not be read." **The session panel** (spec #1019, tickets #1020 to #1027; "D3") is Context mode's story ([The Brief and Context mode](brief.md), "The mode and its hold"): in place of the feed's turn blocks and the Decisions fold, a **card** and a **timeline**, with the Wait tip under them while the session runs. Decision mode, the round card and the dock are as they were. The panel is drawn for the session's own view only; a subagent's view keeps the feed. Hover on any of its rows tints the row and lights its parts on the map ([A turn on the map](#a-turn-on-the-map)) and never inserts content or moves a row; its controls keep a hint of their own, opening beside the panel, to the control's right, so none covers the rows above it. Colour is for what needs Daniel (the ◆, in the needs-you colour) and for a failure (a failed subagent's status, in the failure red); a failed check also stands out by its glyph and weight. +**The turn card** (spec #1062, tickets #1068 and #1069) leads the panel at Your turn and Idle, above the session card. It shows the newest turn's **Headline**; "You next", numbered, or "Nothing waiting on you" when the writer's `next` is an empty list (a summary with no `next` shows no "You next" at all); "Agent did", numbered; the turn's `open` Body lines as "Not done: …"; the **Reply** row; and a "Full reply" fold at its foot, the story's full-response fold (**Full response**, below) drawn in the panel. A summary stored before the lists (no `next`, no `did`) shows its Headline, the Reply row's box and the fold; a turn with no summary yet, or with summaries off, shows its reply's first line, the box and the fold. + +**The Reply row** (ticket #1069) is one "Reply" label over the summary's `prompts` as one-line rounded pills in a wrapping row: the agent's (at most two, solid) first, then the suggested one (at most one, dashed, muted and after a ✦), with no tag on a pill. A pill's hover names who wrote it ("Proposed in the agent's reply", or "Suggested by plotkeeper, not in the agent's reply") and holds its whole text, so a pill cut with an ellipsis still reads whole. A summary without `prompts` has no pills. Pressing a pill puts its text in the box, replacing what was there, and focuses it. The box starts one line tall and grows with its text, up to about 8 lines. Enter sends it by **Send** ([the glossary](../CONTEXT.md)), Shift+Enter adds a line, and the Enter that confirms an input method's word does neither. Under the box, one status line and the buttons: past the guard, "Enter sends · Shift+Enter new line", Copy & Jump and Send in Herdr, the main one; in Herdr with the guard refusing, "Send is off: ", Copy & Jump as the main one and Send in Herdr unavailable with the reason; outside Herdr, Copy & Jump with "Send is off: This session doesn't run in Herdr.app", or, where the Jump knows no terminal, Copy reply with "No jump: ". A send marks the session seen (`see_session`) first, as the planning view's Send does, then types the box's text with `send`; the box can't be edited while it waits, a sent prompt empties it and says "Sent", and a failed one keeps the text, says "Not sent: " and asks the guard again. Where Send can't type, Enter sends, copies and jumps nothing: it says "Not sent: ; use Copy & Jump" (or Copy reply). Copy & Jump and Copy reply copy the box's text inside the press and keep it. Typing again clears what the status line said. The guard is asked once per ended turn. The box is one node per session for the page's life, held by every draw (**The story is patched in place**, below), so a draft, its caret and the focus stay while the card is drawn anew, as when its summary arrives, and when Daniel leaves the session and comes back; it goes when the session leaves the list. There is no card while the session runs, none while it needs Daniel (Decision mode keeps its own views), and the session card and the Since you looked timeline are as they were. The card is keyed by its session, its turn count and what it shows, so a summary arriving, or a turn starting, draws it anew through the keyed patch (the card leaves at Running and comes back at the next Your turn), and a draw that changes nothing in it keeps its node and its open fold. + **The card** has four lines. The **purpose** is "#N · the issue's title" when the session has a linked issue (before the title arrives, "#N"), else the Goal, else the session's name, clamped to 2 lines; pressing it opens the Goal, Daniel's last decision and the facts' fold (the fold's contents are [Context mode's](brief.md)). The **state** is one quiet line from the session's own state, not the held mode's: "Running · 4m · 2 subagents" (the age of the live turn and its running subagents), "Your turn · 3m ago" (the end of the last turn, "just now" under a minute), or "Needs you · 2 questions ↑", where ↑ opens the live round or, with none, focuses the dock's first ask, the same act as the round line's press. Then, for an agent that records turn trees, the **touched parts**; and **Show on map**, which pans the map clear of the panel to every part the session changed (the card's last rows, such as "PR brief ready", follow it). An agent that reports no turn trees has the purpose and the state and the timeline's text rows, with no part rows, no ◆, no ▶ replay and no `[why?]`. **Part rows** list the parts the session changed, placed by the map's own placement file by file (a turn older than 7 days lights nothing, as on the map) and not only those since the read point: a touched part belongs to the session, so it stays with 0 unseen turns. The parts changed since the **read point** come first, then by the most recent change; there are at most 3 rows, then "+ N more parts". A row has a dot, the part's name on the map and its **behaviour line**. The dot is a bright ● for a part touched since the read point, a muted one for the others, and ◆ for a part first touched since the read point; with no read point (a session's first open, below) there is no ◆. The behaviour line is the writer's: what the part does differently now, in present tense, at most about 14 words, with no file names. Until it is written, or with summaries off, the row shows its changed files in italics ("2 files changed: panel.ts, card.ts, …"). A later turn that changes the part again makes its line stale: it shows muted and starts with "(earlier)" until the next Your turn (or, with summaries written on open, the next opening) writes a fresh one. Hovering or focusing a row lights its part on the map; its `why?` sits at the row's right, shown on hover or focus, reading "close" while open. @@ -45,11 +49,11 @@ Pressing a row expands it in place to a compact detail, with each thing once: wh **Decisions**, the fold under the feed, scrolls itself into the panel's view when opened, to the nearest edge: smoothly, or at once when reduced motion is asked for (spec #661). -**The turn summary.** When a turn ends, one `claude -p` call (the model and effort from `summaries` in `settings.json`; with `on_open` true, when you open the turn instead) writes a Headline and up to three Body lines, for a turn whose final response is about 150 words or more, that ends asking you something, or that changed files, so its row has a written headline. Any other turn shows its response as it is: its Headline is the response's first line, which is also what the Headline is until the summary arrives. With summaries off there is no call. +**The turn summary.** When a turn ends, one `claude -p` call (the model and effort from `summaries` in `settings.json`; with `on_open` true, when you open the turn instead) writes a Headline, up to three Body lines and the turn card's `next`, `did` and `prompts` (spec #1062: what the reply asks of you, what the turn did, and prompts you might send, each held to the guards below), for a turn whose final response is about 150 words or more, that ends asking you something, or that changed files, so its row has a written headline. Any other turn shows its response as it is: its Headline is the response's first line, which is also what the Headline is until the summary arrives. With summaries off there is no call. The writer is given the turn's recorded facts (its files with their line counts, hunks up to a cap, each check's command, result and retries) and told not to restate them. The Headline is at most 16 words, an outcome or what the turn waits on; for a turn that ends by asking you, the ask. A Body line is `why`, `reported`, `open` or `ask`, at most 20 words. The whole Body shows at once, since a turn's own Quiz is retired (danielrispler/plotkeeper#347); a `reported` line reads "Agent says:". -Code, not the prompt, holds the writer to the facts (`understanding/src/grounding.rs`): a Headline that claims a fix, a pass or a verification with no check of the turn that ended passed, or with one that ended failed, starts with "Agent says:"; a Headline or line with a count, percentage, issue or PR id or commit SHA that the turn's material lacks is stripped, a Headline asked for once more, and a stripped second one is replaced by the response's first line. Numbers in the diff, the line counts or a check's result, number words and digits in a known path always pass. +Code, not the prompt, holds the writer to the facts (`understanding/src/grounding.rs`): a Headline that claims a fix, a pass or a verification with no check of the turn that ended passed, or with one that ended failed, starts with "Agent says:"; a Headline or line with a count, percentage, issue or PR id or commit SHA that the turn's material lacks is stripped, a Headline asked for once more, and a stripped second one is replaced by the response's first line. Numbers in the diff, the line counts or a check's result, number words and digits in a known path always pass. The turn card's items are held the same way and dropped, never cut, without asking again: `next` and `did` at most three of at most 14 words, a `did` claim with no passed check reading "Agent says:"; `prompts` at most 12 words, at most two `agent` ones, each kept only when its `quote` passes the round's word-for-word check against the final response, and one `suggested`, its quote emptied. A list the writer filled whose every item is dropped is stored as none, so a `next` with nothing left shows no "You next", never "Nothing waiting on you". **Rounds** (spec #967, ticket #973). A live turn of a Claude Code session in planning or triage ([Sessions](sessions.md)) asks for its round (other agents' sessions ask for none in v1), the questions its final reply asks you, unless it ended on `AskUserQuestion` or `ExitPlanMode`. The request waits for the turn's files to be stored, and goes only while the session is still in planning or triage after them; the turn's summary request waits behind it, so the round is written first. When the shell gives up on the turn's files (no worktree has an end tree, the turn is older than the files' 7 days, or it was settled before its `Stop`, as a running turn of too many files is), both go on at once, round then summary. The summaries writer (`summaries.writer`, its model and effort, and its on/off switch: with summaries off there is no round) reads the reply with its own prompt and quotes each question, recommendation and option from it, giving each option a short name and hint; a writer that takes a JSON schema gets one, and another's reply is read as JSON. The round is kept as `extracting` at once, then written on the session's queue, never parked by `on_open`. Code checks each quote against the reply (`quoted` in `understanding/src/grounding.rs`), sentence by sentence, with list and heading markers, `*`, `_`, backticks, `|` and whitespace stripped from both: each sentence of a quote must be in the reply, so a question quoted as its heading and its asking sentence further down passes, and a paraphrase does not; an option that fails is dropped and counted, and a question or recommendation that fails marks its question answered in the terminal and turns Accept all off for the round. A reply with no JSON object fails the round with a one-line reason, which also goes to plotkeeper's log. A round with at least one question appends a `StudioRound` line to the event log ([Storage](storage.md)); one with none is closed and logs no line. The rail does not show rounds yet; the server's commands for them, and how the next prompt records a round's answer, are in [Cards](cards.md), "Answering a round". diff --git a/scripts/snap/fixtures-panel.ts b/scripts/snap/fixtures-panel.ts index faf7ef8b..5bbb0916 100644 --- a/scripts/snap/fixtures-panel.ts +++ b/scripts/snap/fixtures-panel.ts @@ -1651,6 +1651,32 @@ export const panelCaughtUp = (): Fixture => if (toggle.getAttribute("aria-expanded") !== "true") log("snap:fail the earlier turns did not open"); if (texts(".since-turns.earlier .since-n").join() !== "9,8,5,4,3,2,1") log("snap:fail the earlier rows: " + texts(".since-turns.earlier .since-n"));`); +/** + * The turn card at Your turn (spec #1062, tickets #1068 and #1069): above the session card, the turn's line, "You next" and "Agent did" + * numbered, a "Not done" line, the Reply row (two agent pills, solid, then the suggested one, dashed with ✦, the third cut to the row with an + * ellipsis) over the one-line box, Send in Herdr past the guard, and the Full reply fold, closed. The session card and the timeline follow, unchanged. + */ +export const panelTurnCard = (): Fixture => + sessionPanel(panelSession({ terminal: { bundle: "dev.herdr.app", program: null, herdr: "t1", app: "Herdr" }, transcript: { ...panelSession().transcript, responses: ["Drew the card.\n\nThe notes box is its own step, or sits on the bar: which do you want?"] } }), ` + const card = panelNode.querySelector(".turn-card"); + if (!card || panelNode.firstElementChild !== card) return log("snap:fail the turn card is not the panel's first block"); + const read = (selector) => [...card.querySelectorAll(selector)].map((node) => node.textContent); + if (read(".turn-card-line").join() !== "Drew the card; asks whether the notes box is its own step.") log("snap:fail the line: " + read(".turn-card-line")); + if (read(".turn-card-label").join() !== "You next,Agent did,Reply") log("snap:fail the labels: " + read(".turn-card-label")); + if (read(".turn-card-next li").length !== 2 || read(".turn-card-did li").length !== 3) log("snap:fail the lists"); + if (read(".turn-card-open").join() !== "Not done: The docs are not updated") log("snap:fail Not done: " + read(".turn-card-open")); + const fold = card.querySelector("details.fold"); + if (fold?.querySelector("summary")?.textContent !== "Full reply" || fold.open) log("snap:fail the Full reply fold"); + const pills = [...card.querySelectorAll(".turn-pill")]; + if (pills.map((pill) => pill.classList.contains("suggested")).join() !== "false,false,true") log("snap:fail the pills: agents first, then the suggested one"); + if (!pills.every((pill) => pill.getBoundingClientRect().height < 32)) log("snap:fail a pill is more than one line"); + const box = card.querySelector("textarea.turn-reply"); + if (!box || box.getBoundingClientRect().height > 44) log("snap:fail the box is not one line tall"); + if (read(".turn-reply-foot button").join() !== "Copy & Jump,Send in Herdr") log("snap:fail the reply's buttons: " + read(".turn-reply-foot button")); + if (!panelNode.querySelector(".session-card") || !panelNode.querySelector(".since-lead")) log("snap:fail the session card and the timeline stay");`, { + turn_summary: { __by: "id", values: { pt5: { summary: { summary: "", headline: "Drew the card; asks whether the notes box is its own step.", lines: [{ kind: "open", text: "The docs are not updated" }, { kind: "reported", text: "Agent says: the card stays still on hover." }], next: ["Choose where the notes box goes: on the bar, or its own step", "Implement #1052 when you're ready"], did: ["Drew the card: its purpose, its state and the parts it touched", "Sorted the rows by what changed since you looked", "Agent says: the hover audit passes"], prompts: [{ text: "The bar is fine, go ahead", from: "agent", quote: "q" }, { text: "Make notes its own step", from: "agent", quote: "q" }, { text: "Implement #1052 in a worktree, then open its pull request against main", from: "suggested", quote: "" }], quiz: null } } } }, + }); + /** Running (#1023): the live turn on top, its line the Intention, its step and its running subagents under it; the state counts them. */ export const panelRunning = (): Fixture => { const turns = panelTurns(); @@ -1755,7 +1781,11 @@ export const panelReplay = (): Fixture => { const lit = [...document.querySelectorAll("#map .plate.turn-lit")].map((p) => p.dataset.id).sort().join(); if (lit !== "core,shell") log("snap:fail step 2 lights " + JSON.stringify(lit)); for (const name of ["replay-back", "replay-next", "replay-stop"]) if (!panelNow.querySelector("." + name)?.checkVisibility()) log("snap:fail no " + name); - if (panelNow.querySelector(".since-replay")) log("snap:fail ▶ shows while playing");`); + if (panelNow.querySelector(".since-replay")) log("snap:fail ▶ shows while playing"); + // The pressed › keeps the focus, and its "Next step" hint with it; with the turn card above (spec #1062) that hint reaches the + // bare map the shared check tests, so the focus leaves first. + document.activeElement?.blur(); + await wait(200);`); }; /** A session's first open (#1019, D2): no read point, so its last 5 turns show as Recent, with no ◆ and no ▶ replay: nothing is unseen. */ diff --git a/scripts/snap/fixtures.ts b/scripts/snap/fixtures.ts index 467a8581..0985f5ae 100644 --- a/scripts/snap/fixtures.ts +++ b/scripts/snap/fixtures.ts @@ -10,7 +10,7 @@ import { alerts, listEmpty, listUnread, listUnreadHealed, cutText, cutTextStill, import { mapBadgeList, mapNowSubagents, mapBase, mapCheckout, mapDefaultNoBanner, mapNotGit, mapBriefPairLight, mapBriefSwitch, mapBroken, mapBusy, mapCalm, mapCamera, mapDotsOrder, mapDotsRetry, mapEmpty, mapFog, mapFogPlates, mapFresh, mapGlassMotion, mapGoneFocus, mapHeaderDot, mapMarkHints, mapScan, mapScanIgnore, mapScanMerge, mapScanGive, mapScanNoClaude, mapScanSwitch, mapScanZone, mapScanDissolved, mapScanDissolvedNone, mapDraftSteps, mapDrafting, mapDraftReview, mapDraftRound, mapDraftZoneSteps, mapDraftZoneFailed, mapDraftAccept, mapDraftPr, mapDraftPrMuted, mapDraftLoose, mapDraftReplace, mapDraftWrite, mapKeepCurrent, mapPendingClosed, mapPendingOpen, mapPendingSteps, mapPartKeys, mapPartRedraw, mapSheetFocus, mapProjectGone, mapProjectRemoved, mapRefresher, mapPurposeWhole, mapSheetLongName, mapCaughtUp, mapCatchUpOlder, mapReview, mapScrubbed, mapSmallGaps, mapSpotlight, mapStale, mapSwitchSavesViews, mapTalksTo, mapZones, mapZoneMarks, mapZoneOpen, mapPlanLight, mapZoneSheet, mapZoneSheetNarrow, mapDiffZones, mapUnread, mapHistoryUnread, mapBadgeSwitch } from "./fixtures-map.ts"; import { readmeFixtures } from "./fixtures-readme.ts"; import { readmeBriefFixtures } from "./fixtures-readme-brief.ts"; -import { mapFootprint, mapLatePlace, mapPanelBrief, mapPanelDiff, mapNotPlacedHint, mapPanelFieldHints, mapPanelFocus, mapPanelHead, mapPanelHistory, mapPanelLine2, mapPanelNoSession, mapPanelPeel, mapPanelMenuEsc, mapPanelChangeEsc, mapPanelLightDismiss, mapListFold, mapPanelSettings, mapPanelStory, mapPanelToggle, mapSheetClose, mapSheetExplained, mapSheetHere, mapSheetHolds, mapSheetKeptWidth, mapSheetResizeRedraw, mapSheetScrollShort, mapSheetStill, mapSheetUnratified, mapSheetWidth, mapToastBeside, mapTurnLight, mapPanelPatched, mapPanelAskStays, mapPanelBriefFoot, mapPrPanel, mapPrPanelPlaying, mapPrPanelRatify, mapPrPanelRewriting, mapPrPanelWriting, panelCaughtUp, panelExpanded, panelNeedsYou, panelFirstOpen, panelNoTrees, panelReplay, panelRunning, panelWhy, panelYourTurn } from "./fixtures-panel.ts"; +import { mapFootprint, mapLatePlace, mapPanelBrief, mapPanelDiff, mapNotPlacedHint, mapPanelFieldHints, mapPanelFocus, mapPanelHead, mapPanelHistory, mapPanelLine2, mapPanelNoSession, mapPanelPeel, mapPanelMenuEsc, mapPanelChangeEsc, mapPanelLightDismiss, mapListFold, mapPanelSettings, mapPanelStory, mapPanelToggle, mapSheetClose, mapSheetExplained, mapSheetHere, mapSheetHolds, mapSheetKeptWidth, mapSheetResizeRedraw, mapSheetScrollShort, mapSheetStill, mapSheetUnratified, mapSheetWidth, mapToastBeside, mapTurnLight, mapPanelPatched, mapPanelAskStays, mapPanelBriefFoot, mapPrPanel, mapPrPanelPlaying, mapPrPanelRatify, mapPrPanelRewriting, mapPrPanelWriting, panelCaughtUp, panelExpanded, panelNeedsYou, panelFirstOpen, panelNoTrees, panelReplay, panelRunning, panelTurnCard, panelWhy, panelYourTurn } from "./fixtures-panel.ts"; import { mapBackLaw, mapMicroWorld, mapMicroWorldBuilding, mapPreFlight, mapPreFlightOutside, mapPreFlightOutsideKept, mapPreFlightPalette, mapPreFlightPick, mapPreFlightStatus, mapRuns, mapRunsAnnounced, mapRunsBesideSheet, mapRunsPaused, mapTray, mapTrayAfterPush, mapPreFlightIssuesFailed } from "./fixtures-runs.ts"; import { mapBriefAlsoGroups, mapBriefAnnounce, mapBriefBar, mapBriefBold, mapBriefBoldUnpaired, mapBriefChapterLast, mapBriefChapterMid, mapBriefChapters, mapBriefCopied, mapBriefCopyByHand, mapBriefExplainBack, mapBriefExplained, mapBriefFigure, mapBriefGuard, mapBriefHeights, mapBriefMapCheck, mapBriefNoFacts, mapBriefReview, mapBriefStillTrue, mapBriefNoStaleBase, mapBriefOrderRight, mapBriefOrderSlots, mapBriefOrderWrong, mapBriefOverturn, mapBriefPartialFacts, mapBriefPick, mapBriefRatify, mapBriefRatifyDetail, mapBriefRatifyEvidence, mapBriefShort, mapBriefSince, mapBriefStaleBase, mapBriefStart, mapBriefStepCode, mapBriefStory, mapBriefTall, mapBriefTaller, mapBriefTallScroll, mapBriefUnconfirmed, mapBriefWhy, mapBriefWhyDecision, mapBriefWriting, mapCatchUp, mapCatchUpBold, mapCatchUpCard, mapCatchUpStage, mapCatchUpSummarising, mapCatchUpWriting, mapDiffClosed, mapDiffLitGhost, mapDiffRatifyLit, mapDiffRemoval, mapDiffRemovalBrief, mapDiffSplit, mapDiffSplitBrief, listBriefMark, railBriefReady } from "./fixtures-brief.ts"; import { writersBriefsNeedClaude, writersFailed, writersKeyError, writersTestUnrun, writersUnread, writersKeyNotSet, writersKeySet, writersList, writersOpenAI, writersPassed, writersSecretService } from "./fixtures-writers.ts"; @@ -19,6 +19,8 @@ export const fixtures = { ...railFixtures, // The session panel: the rail's Context mode as a card and a "since you looked" timeline (#1023). mapSessionPanel: panelYourTurn, + // The turn card above the session card at Your turn (spec #1062, #1068). + mapSessionPanelTurnCard: panelTurnCard, mapSessionPanelExpanded: panelExpanded, mapSessionPanelCaughtUp: panelCaughtUp, mapSessionPanelRunning: panelRunning, diff --git a/system-map.json b/system-map.json index d472a9d7..c53691a1 100644 --- a/system-map.json +++ b/system-map.json @@ -116,7 +116,7 @@ "holds": [ { "name": "The Map view", "text": "Parts, zones, links, fog, free scan, Map draft, a part's sheet with history and ratify, PR brief, tray, plan light, explanations, overlays.", "paths": ["ui/map.ts", "ui/map-plan-light.ts", "ui/map-scan.ts", "ui/map-draft.ts", "ui/map-keep.ts", "ui/map-model.ts", "ui/map-camera.ts", "ui/map-live.ts", "ui/map-sheet.ts", "ui/map-sheet-folds.ts", "ui/map-zone-sheet.ts", "ui/map-brief.ts", "ui/map-tray.ts", "ui/copy-button.ts", "ui/map-brief-player.ts", "ui/map-brief-model.ts", "ui/map-catch-up.ts", "ui/explanations.ts", "ui/overlay-focus.ts"] }, { "name": "The session list", "text": "A header for every project with a live session and every saved one whose folder is there and not temporary, whose headers switch the map.", "paths": ["ui/list.ts", "ui/list-model.ts", "ui/projects.ts"] }, - { "name": "The left panel", "text": "A session's story (Context mode's card and timeline, or Decision mode's feed), a plan or round, History, a diff, a log, a PR or Settings.", "paths": ["ui/panel.ts", "ui/pr-panel.ts", "ui/pr-panel-model.ts", "ui/story.ts", "ui/session-panel.ts", "ui/session-panel-model.ts", "ui/banner.ts", "ui/context.ts", "ui/diff.ts", "ui/plan-view.ts", "ui/plan-rules.ts", "ui/rounds.ts"] }, + { "name": "The left panel", "text": "A session's story (Context mode's panel, which sends a prompt, or Decision mode's feed), a plan or round, History, diff, log, PR, Settings.", "paths": ["ui/panel.ts", "ui/pr-panel.ts", "ui/pr-panel-model.ts", "ui/story.ts", "ui/session-panel.ts", "ui/session-panel-model.ts", "ui/banner.ts", "ui/context.ts", "ui/diff.ts", "ui/plan-view.ts", "ui/plan-rules.ts", "ui/rounds.ts"] }, { "name": "The writer's settings", "text": "Pick the program that writes the summaries, or set up an API-key writer, and test it with one tiny call.", "paths": ["ui/settings.ts", "ui/writers.ts"] }, { "name": "Patch review", "text": "A back a law run's proven test patch, to open as a draft PR or discard.", "paths": ["ui/patch-review.ts"] }, { "name": "Tips and what's new", "text": "A Wait tip teaches one feature while a session runs; after an update, one toast links to its Release.", "paths": ["ui/tips.ts", "ui/whats-new.ts"] }, diff --git a/ui/dom.ts b/ui/dom.ts index be42a0de..b2dd3c07 100644 --- a/ui/dom.ts +++ b/ui/dom.ts @@ -154,11 +154,11 @@ export const unseenWords = (words: string): HTMLElement => text("span", words, " /** * Enter in `field` runs `run`, except the Enter that confirms an input method's word (#461); Safari's out-of-order confirming key - * down reports keyCode 229 with isComposing false. + * down reports keyCode 229 with isComposing false. With `lines`, Shift+Enter is the field's own, adding a line. */ -export function onEnter(field: HTMLElement, run: () => void) { +export function onEnter(field: HTMLElement, run: () => void, lines = false) { field.addEventListener("keydown", (event) => { - if (event.key !== "Enter") return; + if (event.key !== "Enter" || (lines && event.shiftKey)) return; event.preventDefault(); if (!event.isComposing && event.keyCode !== 229) run(); }); diff --git a/ui/jump.ts b/ui/jump.ts index 1721f68b..5d258ee4 100644 --- a/ui/jump.ts +++ b/ui/jump.ts @@ -6,7 +6,10 @@ import { failure, invoke } from "./dom.js"; import { type Platform, platform } from "./settings.js"; import { studio } from "./state.js"; -import type { Terminal } from "./types.js"; +import type { Session, Terminal } from "./types.js"; + +/** A session that runs directly in a Herdr.app terminal: the only one Send can type into. */ +export const inHerdr = (session: Pick) => Boolean(session.terminal?.herdr); /** The jump's label for a session in `terminal`, such as "Open in Herdr"; none for an app the core doesn't know, or off macOS. */ export const jumpLabel = (terminal: Terminal | null | undefined, on: Platform = platform): string | null => diff --git a/ui/main.ts b/ui/main.ts index 74cf3365..49debd53 100644 --- a/ui/main.ts +++ b/ui/main.ts @@ -8,6 +8,7 @@ import { dismissNotice, dropUnreachable, NOT_RECORDING, setSettingsErrors, showE import { withGateNotice, withWriterNotice } from "./writer-notice.js"; import { startWatching } from "./answer.js"; import { forgetAsks } from "./ask.js"; +import { forgetReplies } from "./session-panel.js"; import { recheckSeen } from "./seen.js"; import { diffRequest, newestDiff } from "./diff.js"; import { cut, element, failure, hint, invoke, listen, logUncaught, stopEvents, watchConnection } from "./dom.js"; @@ -290,7 +291,9 @@ startList({ lastHeadline, forget: (sessions) => { forgetStories(sessions); - forgetAsks(new Set(sessions.map((session) => session.id))); + const listed = new Set(sessions.map((session) => session.id)); + forgetAsks(listed); + forgetReplies(listed); }, }); startRailBriefs(); diff --git a/ui/rounds.ts b/ui/rounds.ts index 2c7e0e60..8811598c 100644 --- a/ui/rounds.ts +++ b/ui/rounds.ts @@ -12,7 +12,7 @@ import { releaseMode, shownHold } from "./banner.js"; import { copyText } from "./copy-button.js"; import { availability, cut, element, failure, glyphOnly, hint, invoke, isUnavailable, keyed, logLine, messageOf, pressable, prose, statusLine, text } from "./dom.js"; -import { jump, jumpLabel, jumpReason } from "./jump.js"; +import { inHerdr, jump, jumpLabel, jumpReason } from "./jump.js"; import { sessionName } from "./list-model.js"; import { rendered, renderedInline } from "./markdown.js"; import { studio } from "./state.js"; @@ -418,8 +418,6 @@ function askGuard(round: Round, form: Form, session: Session) { if (showing === keyOf(round)) redraw(); }); } -// A session that runs directly in a Herdr.app terminal: the only one Send can type into. -const inHerdr = (session: Session) => Boolean(session.terminal?.herdr); // ---- Drawing diff --git a/ui/session-panel-model.ts b/ui/session-panel-model.ts index 4b1ba3b7..346698e5 100644 --- a/ui/session-panel-model.ts +++ b/ui/session-panel-model.ts @@ -1,7 +1,7 @@ // The session panel's rules (spec #1019, ticket #1021): pure functions over a session's turns, with no DOM. The page's placement is // passed in as `lit`, so the module touches nothing of the map's drawing. -import type { Anchor, PartLine, Subagent, Turn, TurnFile } from "./types.js"; +import type { Anchor, PartLine, ReplyPrompt, Subagent, SummaryLine, Turn, TurnFile, TurnSummary } from "./types.js"; import { plural, withoutAgentSays } from "./words.js"; export type Lit = Pick; @@ -152,3 +152,21 @@ export function replaySteps(turns: (Lit & Pick)[], snapshot: Pi .filter((step) => step.lit.ended_at !== null && lit(step.lit).length > 0); return steps.length < 2 ? [] : steps; } + +// The turn card's content (spec #1062, ticket #1068), from the newest turn's summary and the Headline and Body lines read from it. `next` +// and `did` are null for a summary stored before them (or none): the card then leaves the label out. An empty `next` is "asks nothing". +// `notDone` is the Body's `open` lines. `prompts` is passed on whole for the reply row (ticket #1069), null when the summary has none. +export type TurnCard = { headline: string | null; next: string[] | null; did: string[] | null; notDone: string[]; prompts: ReplyPrompt[] | null }; +// The line keeps the guards' "Agent says:" (outside review of spec #1062), as `did` items do, where the timeline's row drops it. +export function turnCardOf(summary: TurnSummary | null, said: { headline: string | null; body: SummaryLine[] }): TurnCard { + const stored = summary?.summary; + const line = said.headline ? plain(said.headline) : ""; + const marked = said.headline !== null && withoutAgentSays(said.headline) !== said.headline; + return { + headline: line ? `${marked ? "Agent says: " : ""}${line}` : null, + next: stored?.next ?? null, + did: stored?.did ?? null, + notDone: said.body.filter((line) => line.kind === "open").map((line) => plain(line.text)).filter(Boolean), + prompts: stored?.prompts ?? null, + }; +} diff --git a/ui/session-panel.ts b/ui/session-panel.ts index f197da39..1ef0f22d 100644 --- a/ui/session-panel.ts +++ b/ui/session-panel.ts @@ -12,11 +12,13 @@ // leaves the read point where it was. import { askAnchor, whyAnswer } from "./ask.js"; -import { age, code, cut, failure as failed, glyphOnly, hint, invoke, isUnavailable, keyed, pressable, stamp, text, unseenWords } from "./dom.js"; +import { copyText } from "./copy-button.js"; +import { age, availability, code, cut, failure as failed, glyphOnly, held as heldNode, hint, invoke, isUnavailable, keepOnly, keyed, messageOf, onEnter, pressable, stamp, text, unseenWords } from "./dom.js"; +import { inHerdr, jump, jumpLabel, jumpReason } from "./jump.js"; import { registerLayer } from "./map.js"; import { shortPaths } from "./paths.js"; -import { cameBack, groupLit, groupsOf, litOf, partAnchor, partRows, replaySteps, rowLine, snapshotOf, type Group, type Lit, type PartAnchor, type PartRows, type PartsOf, type ReplayStep } from "./session-panel-model.js"; -import { stateLabels, type PartLine, type Session, type Subagent, type SummaryLine, type Turn } from "./types.js"; +import { cameBack, groupLit, groupsOf, litOf, partAnchor, partRows, replaySteps, rowLine, snapshotOf, type Group, type Lit, type PartAnchor, type PartRows, type PartsOf, type ReplayStep, type TurnCard } from "./session-panel-model.js"; +import { stateLabels, type PartLine, type ReplyPrompt, type SendGuard, type Session, type Subagent, type SummaryLine, type Turn } from "./types.js"; import { plural, withoutAgentSays } from "./words.js"; /** What the story gives the panel to draw `session`, the server's own, its state not the held mode's. */ @@ -43,6 +45,8 @@ export type PanelInput = { select: (agent: string) => void; // The card's last rows, such as "PR brief ready". foot: HTMLElement[]; + // The newest turn's turn card (#1068): its content and its Full reply fold, null when the session has no turn. Drawn at Your turn and Idle only. + turn: { card: TurnCard; fold: HTMLElement | null } | null; // The turn whose row flashes once, as "This session here"'s press asks (#561). flash: number | null; redraw: () => void; @@ -185,10 +189,219 @@ export function panelElement(input: PanelInput): HTMLElement { node.id = "session-panel"; node.className = "session-panel"; node.setAttribute("aria-label", "Where the session stands"); - node.append(card(input, kept, snapshot.recent ? 0 : kept.base), ...timeline(input, kept, snapshot)); + node.append(...turnCard(input), card(input, kept, snapshot.recent ? 0 : kept.base), ...timeline(input, kept, snapshot)); return node; } +// ---- The turn card + +// The newest turn's card (spec #1062, ticket #1068), above the session card at Your turn and Idle: the Headline, "You next" and "Agent did" +// numbered, the Body's open lines as "Not done: …", and the Full reply fold. Read-only. A summary stored before the lists has the Headline and +// the fold only; a turn with no summary has its reply's first line (the story gives it as the Headline) and the fold. Keyed by what it +// shows, so a summary arriving, or the turn changing, draws it anew and anything else keeps the node. +function turnCard(input: PanelInput): HTMLElement[] { + const { session, turn } = input; + if (!turn || (session.state !== "your_turn" && session.state !== "idle")) return []; + const { card: said, fold } = turn; + const node = keyed(document.createElement("section"), `turn-card ${session.id} ${session.turns.length} ${stamp(JSON.stringify(said))}`); + node.className = "turn-card"; + node.setAttribute("aria-label", "This turn"); + if (said.headline) node.append(text("p", said.headline, "turn-card-line")); + const list = (label: string, className: string, items: string[]) => { + node.append(text("h3", label, "turn-card-label")); + const ordered = text("ol", "", className); + ordered.append(...items.map((item) => text("li", item))); + node.append(ordered); + }; + if (said.next !== null) { + if (said.next.length) list("You next", "turn-card-next", said.next); + else node.append(text("h3", "You next", "turn-card-label"), text("p", "Nothing waiting on you", "turn-card-nothing")); + } + if (said.did?.length) list("Agent did", "turn-card-did", said.did); + if (said.notDone.length) node.append(...said.notDone.map((line) => text("p", `Not done: ${line}`, "turn-card-open"))); + node.append(...replyNodes(input, said.prompts ?? [])); + if (fold) node.append(fold); + return [node]; +} + +// ---- The turn card's reply (ticket #1069) + +// What the reply holds for a session, for the page's life: its box, kept as it is by every draw (`held`), so a draft, its caret and the +// focus stay while the card is drawn anew (a summary arriving); Send's guard, asked once per ended turn (`turns`); whether a send is under +// way; the line under the box, once an act said something (a failed send, a copy); and the latest draw's input, which the box's and the +// buttons' handlers read at the press, as a kept node keeps the handler of the draw that made it. +type Reply = { field: HTMLTextAreaElement; turns: number; guard: SendGuard | null; sending: boolean; said: string | null; input: PanelInput }; +const replies = new Map(); + +/** Drops the reply boxes of sessions no longer listed. */ +export function forgetReplies(listed: ReadonlySet) { + keepOnly(replies, (id) => listed.has(id)); +} + +const sendable = (reply: Reply) => inHerdr(reply.input.session) && reply.guard?.passes === true; +// Why Send can't type, in one line: the guard's reason in Herdr.app, else that the session runs elsewhere. +const offReason = (reply: Reply) => (inHerdr(reply.input.session) ? (reply.guard?.reason ?? "Checking the terminal…") : "This session doesn't run in Herdr.app"); +const copyLabel = (session: Session) => (jumpLabel(session.terminal) === null ? "Copy reply" : "Copy & Jump"); + +function replyOf(input: PanelInput): Reply { + const { session } = input; + const reply = replies.get(session.id) ?? { field: replyField(session.id), turns: session.turns.length, guard: null, sending: false, said: null, input }; + if (reply.turns !== session.turns.length) Object.assign(reply, { turns: session.turns.length, guard: null, said: null }); + reply.input = input; + replies.set(session.id, reply); + return reply; +} + +// The box: one line that grows (`field-sizing`), Enter sending and Shift+Enter adding a line, except the Enter that confirms an input +// method's word (Safari's out-of-order one reports keyCode 229). +function replyField(id: string): HTMLTextAreaElement { + const field = keyed(document.createElement("textarea"), `turn-reply ${id}`); + field.className = "field turn-reply"; + field.rows = 1; + field.name = "turn-reply"; + field.autocomplete = "off"; + field.placeholder = "Write my own…"; + field.setAttribute("aria-label", "Your reply to the agent"); + onEnter(field, () => submit(id), true); + // Typing again clears what the last act said. + field.addEventListener("input", () => { + const reply = replies.get(id); + if (reply?.said == null) return; + reply.said = null; + reply.input.redraw(); + }); + return field; +} + +// The "Reply" label, the pills (the agent's first, then the suggested one), the box and its foot. +function replyNodes(input: PanelInput, prompts: ReplyPrompt[]): HTMLElement[] { + const reply = replyOf(input); + askGuard(reply); + reply.field.readOnly = reply.sending; + const nodes: HTMLElement[] = [text("h3", "Reply", "turn-card-label")]; + const ordered = [...prompts.filter((one) => one.from === "agent"), ...prompts.filter((one) => one.from === "suggested")]; + if (ordered.length) { + const row = text("div", "", "turn-pills"); + row.append(...ordered.map((prompt) => pill(input.session.id, prompt))); + nodes.push(row); + } + nodes.push(heldNode(reply.field), replyFoot(reply)); + return nodes; +} + +// One pill: one line, cut with an ellipsis, its hover naming who wrote it and holding its whole text. A press puts it in the box. +function pill(id: string, prompt: ReplyPrompt): HTMLElement { + const suggested = prompt.from === "suggested"; + const node = keyed(pressable(text("button", "", `turn-pill${suggested ? " suggested" : ""}`), null, () => fill(id, prompt.text)), `turn-pill ${id} ${prompt.from} ${stamp(prompt.text)}`); + if (suggested) node.append(glyphOnly("✦ ")); + node.append(prompt.text); + return hint(node, `${suggested ? "Suggested by plotkeeper, not in the agent's reply" : "Proposed in the agent's reply"}: ${prompt.text}`); +} + +function fill(id: string, words: string) { + const reply = replies.get(id); + if (!reply || reply.sending) return; + reply.field.value = words; + reply.field.focus(); + if (reply.said === null) return; + reply.said = null; + reply.input.redraw(); +} + +// Asks the switchboard's guard once per ended turn for a Herdr.app session, to offer Send or say why not (spec #967, "When the guard runs"). +// An answer that lands once the guard was asked again (a later turn ended, or a send failed) is dropped, so it never stands for the newer ask. +function askGuard(reply: Reply) { + const { session } = reply.input; + if (!inHerdr(session) || reply.guard !== null) return; + const asking: SendGuard = { passes: false, reason: "Checking the terminal…" }; + reply.guard = asking; + invoke("send_guard", { session: session.id }) + .catch((e: unknown): SendGuard => ({ passes: false, reason: messageOf(e) })) + .then((guard) => { + if (reply.guard !== asking) return; + reply.guard = guard; + reply.input.redraw(); + }); +} + +// The line under the box, then Copy & Jump (Copy reply where the Jump knows no terminal) and, in Herdr.app, Send in Herdr, the main one +// past the guard, else unavailable with its reason. +function replyFoot(reply: Reply): HTMLElement { + const { session } = reply.input; + const id = session.id; + const can = sendable(reply); + const foot = text("div", "", "turn-reply-foot"); + const words = reply.said ?? (reply.sending ? "Sending…" : can ? "Enter sends · Shift+Enter new line" : !inHerdr(session) && jumpLabel(session.terminal) === null ? `No jump: ${jumpReason()}` : `Send is off: ${offReason(reply)}`); + const status = text("span", words, "turn-reply-status"); + status.setAttribute("role", "status"); + const buttons = text("span", "", "turn-reply-buttons"); + const button = (words: string, primary: boolean, hover: string, why: string | null, click: () => void) => { + const node = keyed(pressable(text("button", words, primary ? "btn small primary" : "btn small"), null), `turn-reply-${words} ${id}`); + availability(node, hover, reply.sending ? "Sending the reply…" : why); + node.addEventListener("click", () => { + if (!isUnavailable(node)) click(); + }); + return node; + }; + const jumps = jumpLabel(session.terminal) !== null; + buttons.append(button(copyLabel(session), !can, jumps ? "Copy the reply and bring the session's terminal to the front" : "Copy the reply to paste in the session's terminal", null, () => copy(id))); + if (inHerdr(session)) buttons.append(button("Send in Herdr", can, "Type the reply into the session's terminal in Herdr (Enter)", can ? null : offReason(reply), () => submit(id))); + foot.append(status, buttons); + return foot; +} + +// Copy & Jump, or Copy reply: the box's text on the clipboard inside the press, and the Jump brings the terminal forward. +function copy(id: string) { + const reply = replies.get(id); + if (!reply) return; + const { session, redraw } = reply.input; + const words = reply.field.value; + if (!words.trim()) { + reply.said = "Nothing to copy: write a reply, or press a pill"; + return redraw(); + } + copyText(words); + reply.said = "Copied: paste it in the terminal"; + if (jumpLabel(session.terminal) !== null) { + jump(id, (e) => { + reply.said = `No jump: ${messageOf(e)}`; + reply.input.redraw(); + }); + } + redraw(); +} + +// Enter, or Send in Herdr: the box's text typed into the session's terminal (`send`), the session seen first, as the planning view's Send +// is (#1019, "The read point"). Where Send can't type, Enter only says why: it never copies or jumps on its own. A sent reply empties the +// box; a failed one keeps it and says why, and the guard is asked again. +function submit(id: string) { + const reply = replies.get(id); + if (!reply || reply.sending) return; + const words = reply.field.value; + if (!words.trim()) return; + if (!sendable(reply)) { + reply.said = `Not sent: ${offReason(reply)}; use ${copyLabel(reply.input.session)}`; + return reply.input.redraw(); + } + reply.sending = true; + reply.said = null; + reply.input.redraw(); + invoke("see_session", { id }).catch(failed("see_session")); + invoke("send", { session: id, text: words }) + .then(() => { + reply.field.value = ""; + reply.said = "Sent"; + }) + .catch((e: unknown) => { + reply.guard = null; + reply.said = `Not sent: ${messageOf(e)}`; + }) + .finally(() => { + reply.sending = false; + reply.input.redraw(); + }); +} + // ---- The card function card(input: PanelInput, kept: Held, base: number): HTMLElement { diff --git a/ui/story.ts b/ui/story.ts index b028599d..ffd19dac 100644 --- a/ui/story.ts +++ b/ui/story.ts @@ -31,6 +31,7 @@ import { holdTurn, lightTurn, revealTurn, turnLit } from "./map-agents.js"; import { OLD_TURN, oldTurn } from "./map-live.js"; import { refreshHere } from "./map-sheet.js"; import { watchSeen } from "./seen.js"; +import { turnCardOf } from "./session-panel-model.js"; import { askPartLines, forgetPanel, panelElement, stopReplay, unfoldTurn } from "./session-panel.js"; import { stretches, tipStore, tipText } from "./tips.js"; import { @@ -653,8 +654,9 @@ function belowHeadline(reply: string, summary: TurnSummary | null, message: stri } // The full response, folded: the latest turn's from the transcript, an older one's fetched at its first opening. None for a turn with -// neither, nor for the latest turn when its reply was only its Headline; an older turn's fold says so once its reply is fetched. -function responseFold(session: Session, turn: Turn, index: number | null, key: string): HTMLElement | null { +// neither, nor for the latest turn when its reply was only its Headline; an older turn's fold says so once its reply is fetched. `title` is +// the fold's name and `part` ends its key, so the panel's fold opens and closes apart from the feed's. +function responseFold(session: Session, turn: Turn, index: number | null, key: string, title = "Full response", part = "response"): HTMLElement | null { const latest = index !== null && index === session.turns.length - 1; const summary = turn.id ? summaryOf(turn.id) : null; const below = (reply: string) => belowHeadline(reply, summary, turn.message); @@ -681,7 +683,7 @@ function responseFold(session: Session, turn: Turn, index: number | null, key: s }) .catch(failure("turn_reply")); }; - const fold = folded(`${key} response`, "Full response", "Show or hide the agent's whole reply", [body], fetchReply); + const fold = folded(`${key} ${part}`, title, "Show or hide the agent's whole reply", [body], fetchReply); if (fold.hasAttribute("open")) fetchReply(); return fold; } @@ -954,7 +956,10 @@ function panelOf(session: Session): HTMLElement { else element("dock").querySelector("button")?.focus(); }; const brief = railBriefRow(session, drawFeed); + const last = session.turns.at(-1); + const lastSummary = last?.id ? summaryOf(last.id) : null; return panelElement({ + turn: last ? { card: turnCardOf(lastSummary, headlineOf(lastSummary, last.message)), fold: responseFold(session, last, session.turns.length - 1, `${session.id} ${session.turns.length - 1}`, "Full reply", "panel response") } : null, session, read: written, purpose, diff --git a/ui/style.css b/ui/style.css index 59197574..9376565a 100644 --- a/ui/style.css +++ b/ui/style.css @@ -750,6 +750,31 @@ h1 { margin: 0 0 var(--sp-4); } #view[data-session-panel] > :is(.feed, .decisions) { display: none; } .session-panel { display: grid; gap: var(--sp-4); margin: 0 0 var(--sp-5); } .session-card { display: grid; gap: var(--sp-3); padding: var(--sp-4) var(--sp-5); border: var(--hair) solid var(--line); border-radius: var(--radius); } +/* The turn card (spec #1062, ticket #1068): read-only, above the session card at Your turn and Idle. Variant A of the prototype: the line in + the larger weight, uppercase small labels, numbered lists, "Not done" muted, the Full reply fold at the foot. No colour: nothing here needs Daniel. */ +.turn-card { display: grid; grid-template-columns: minmax(0, 1fr); min-width: 0; gap: var(--sp-3); padding: var(--sp-4) var(--sp-5); border-radius: var(--radius); background: var(--raised); box-shadow: inset 0 0 0 var(--hair) var(--edge); } +.turn-card-line { margin: 0; font-size: var(--size-read); font-weight: 600; line-height: 1.4; text-wrap: pretty; overflow-wrap: anywhere; } +.turn-card-label { margin: var(--sp-2) 0 calc(-1 * var(--sp-2)); color: var(--faint); font-size: var(--size-xs); font-weight: 400; letter-spacing: .02em; text-transform: uppercase; } +.turn-card :is(ol, .turn-card-nothing, .turn-card-open) { margin: 0; font-size: var(--size-small); line-height: 1.45; overflow-wrap: anywhere; } +.turn-card ol { display: grid; gap: var(--sp-2); padding-inline-start: 1.4em; } +.turn-card-nothing, .turn-card-open { color: var(--muted); } +.turn-card .fold { margin-block-start: var(--sp-2); } +.turn-card .fold > summary { font-size: var(--size-small); } +/* The reply row (ticket #1069), the prototype's compact pills: one-line rounded pills in a wrapping row, the agent's solid, the suggested one + dashed and muted after its ✦; a pill too long for the row ends in an ellipsis, its hint holding the whole text. The box is one line that + grows with what is typed (`field-sizing`; where it is missing, a one-line box that scrolls), up to about 8 lines. */ +.turn-pills { display: flex; flex-wrap: wrap; gap: var(--sp-2); } +.btn.turn-pill { max-width: 100%; padding: var(--sp-1) var(--sp-4); border: var(--hair) solid var(--edge); border-radius: 1lh; background: var(--hover); + font-size: var(--size-small); line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.btn.turn-pill.suggested { border-style: dashed; background: none; color: var(--muted); } +.btn.turn-pill.suggested:hover:not([aria-disabled="true"]) { background: var(--hover); color: var(--fg); } +.turn-reply { display: block; width: 100%; min-block-size: calc(1lh + 2 * var(--sp-2)); max-block-size: calc(8lh + 2 * var(--sp-2)); resize: none; + field-sizing: content; background: var(--bg); line-height: 1.45; } +.turn-reply-foot { display: flex; flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); align-items: center; justify-content: space-between; + margin-block-start: calc(-1 * var(--sp-1)); } +.turn-reply-status { min-width: 0; color: var(--faint); font-size: var(--size-xs); overflow-wrap: anywhere; } +.turn-reply-buttons { display: flex; flex-wrap: wrap; gap: var(--sp-2); margin-inline-start: auto; } +.turn-reply-buttons > .btn { box-shadow: inset 0 0 0 var(--hair) var(--edge); } .btn.card-purpose { display: flex; gap: var(--sp-3); align-items: baseline; width: 100%; padding: 0; background: none; color: var(--fg); font-size: var(--size-read); font-weight: 600; } .btn.card-purpose:hover:not([aria-disabled="true"]) { background: none; } diff --git a/ui/tests/full-text.test.mjs b/ui/tests/full-text.test.mjs index 3be2b106..ca71d26d 100644 --- a/ui/tests/full-text.test.mjs +++ b/ui/tests/full-text.test.mjs @@ -230,6 +230,7 @@ const covered = { ".part-does": "session-panel.ts: a part row's line is clamped to 2 lines; its press shows it whole, and the row's label holds it", ".since-h": "session-panel.ts: a row's line is clamped to 2 lines; its press shows it whole in place", ".since-step": "session-panel.ts: the live row's step is cut text that scrolls in place on hover (cut())", + ".btn.turn-pill": "session-panel.ts: a reply pill is one line cut with an ellipsis; its hint holds its whole text", code: "a check's command has its own title (story.ts); any other code span wraps or sits in a text that wraps", }; diff --git a/ui/tests/session-panel.test.mjs b/ui/tests/session-panel.test.mjs index 762ebb17..07647130 100644 --- a/ui/tests/session-panel.test.mjs +++ b/ui/tests/session-panel.test.mjs @@ -2,7 +2,7 @@ // Run: `npm test`. import { mock, test } from "node:test"; import assert from "node:assert/strict"; -import { cameBack, groupsOf, litOf, partAnchor, partRows, replaySteps, rowLine, snapshotOf, wakeNames } from "../../dist/session-panel-model.js"; +import { cameBack, groupsOf, litOf, partAnchor, partRows, replaySteps, rowLine, snapshotOf, turnCardOf, wakeNames } from "../../dist/session-panel-model.js"; /** @param {any[][]} table */ const rows = (table) => table; @@ -329,7 +329,7 @@ test("a part row's [why?] after a later turn changed the part asks with the new let session = sessionOf({ id: "w1", resume_id: "w1", seen: 1, seen_at_selection: 1, turns: [turn(0, ["core/a.rs"])] }); const input = () => ({ session, read: () => ({ headline: null, body: [] }), purpose: "Why", opened: [], up: { questions: null, open() {} }, lit, name: (part) => part, - lights() {}, reveal() {}, hold() {}, select() {}, foot: [], flash: null, redraw, now: NOW, + lights() {}, reveal() {}, hold() {}, select() {}, foot: [], turn: null, flash: null, redraw, now: NOW, }); const redraw = () => patch(box, [panelElement(input())]); const part = () => box.querySelector(".card-part"); @@ -366,7 +366,7 @@ const player = (first) => { const input = () => ({ session: out.session, read: () => ({ headline: null, body: [] }), purpose: "Play", opened: [], up: { questions: null, open() {} }, lit, name: (part) => part, lights() {}, reveal: (l) => out.revealed.push(l.files.files.map((f) => f.path)), hold: (l) => out.held.push(l?.files.files.map((f) => f.path) ?? null), - select() {}, foot: [], flash: null, redraw: () => { + select() {}, foot: [], turn: null, flash: null, redraw: () => { out.node = panelElement(input()); }, now: NOW, }); @@ -492,3 +492,222 @@ test("← → step only while replay is on and its key handler outlives redraws; } document.querySelector = lookUp; }); + +// Spec #1062, ticket #1068: the turn card leads the panel at Your turn and Idle, read-only, from the newest turn's summary. +const card = () => panel()?.querySelector(".turn-card") ?? null; +const items = (node, list) => node.querySelector(list)?.querySelectorAll("li").map((li) => li.text) ?? null; +const labels = (node) => node.querySelectorAll(".turn-card-label").map((label) => label.text); +const written = (fields) => ({ summary: { summary: "x", quiz: null, lines: [], ...fields } }); +const pills = (node = card()) => node.querySelectorAll(".turn-pill"); +const box = (node = card()) => node?.querySelector("textarea.turn-reply") ?? null; + +test("the turn card: the Headline, the numbered lists, Not done lines, the reply's pills and box, and the Full reply fold; an empty next, an old summary and a turn with no summary", async () => { + for (const [name, summary, want] of rows([ + ["both lists", written({ headline: "Filed #7.", next: ["Choose A or B", "Implement #7"], did: ["Filed #7", "Fixed the name"], prompts: [{ text: "Go with A", from: "agent", quote: "q" }, { text: "Implement #7 in a worktree", from: "suggested", quote: "" }, { text: "Go with B", from: "agent", quote: "q2" }], lines: [{ kind: "open", text: "Docs not updated" }, { kind: "reported", text: "It works" }] }), + { line: "Filed #7.", labels: ["You next", "Agent did", "Reply"], next: ["Choose A or B", "Implement #7"], did: ["Filed #7", "Fixed the name"], notDone: "Not done: Docs not updated", + // The agent's pills solid, the suggested one dashed with ✦, each hover naming who wrote it and holding the whole text. + pills: [["Go with A", false, "Proposed in the agent's reply: Go with A"], ["Go with B", false, "Proposed in the agent's reply: Go with B"], + ["✦ Implement #7 in a worktree", true, "Suggested by plotkeeper, not in the agent's reply: Implement #7 in a worktree"]] }], + ["an empty next", written({ headline: "PR opened.", next: [], did: ["Opened the PR"], prompts: [] }), + { line: "PR opened.", labels: ["You next", "Agent did", "Reply"], nothing: "Nothing waiting on you", next: null, did: ["Opened the PR"], notDone: null, pills: [] }], + ["an old summary", { summary: { summary: "Old headline\nsome body", quiz: null } }, + { line: "Old headline", labels: ["Reply"], next: null, did: null, notDone: null, pills: [] }], + ["no summary", null, { line: "Filed #7. Tell me more.", labels: ["Reply"], next: null, did: null, notDone: null, pills: [] }], + ])) { + replies.turn_summary = () => summary; + const id = `tc${name.replace(/\W/g, "")}`; + await draw(sessionOf({ id, resume_id: id, turns: [turn(1, null), turn(2, null, { id: `${id}-t`, message: "Filed #7. Tell me more." })], transcript: { ...sessionOf().transcript, responses: ["Filed #7. Tell me more.\n\nThe notes box is open."] } })); + const node = card(); + assert.ok(node, name); + assert.equal(node.querySelector(".turn-card-line").text, want.line, name); + assert.deepEqual(labels(node), want.labels, name); + assert.deepEqual(items(node, ".turn-card-next"), want.next, name); + assert.equal(node.querySelector(".turn-card-nothing")?.text ?? undefined, want.nothing, name); + assert.deepEqual(items(node, ".turn-card-did"), want.did, name); + assert.equal(node.querySelector(".turn-card-open")?.text ?? null, want.notDone, name); + assert.deepEqual(pills(node).map((pill) => [pill.text, pill.classList.contains("suggested"), hintOf(pill)?.textContent]), want.pills, name); + assert.ok(box(node), `${name}: the reply box`); + const fold = node.querySelector("details.fold"); + assert.equal(fold?.querySelector("summary").text, "Full reply", name); + assert.ok(fold.querySelector("div.response"), `${name}: the fold holds the reply`); + // The card leads: it is the panel's first child, above the session card. + assert.equal(panel().childNodes[0], node, name); + } + delete replies.turn_summary; +}); + +test("the turn card comes at Your turn and Idle only: none while Running or in Decision mode, and it appears and leaves on the keyed patch", async () => { + replies.turn_summary = () => written({ headline: "Filed #7.", next: [], did: [] }); + const base = sessionOf({ id: "tg", resume_id: "tg", turns: [turn(1, null), turn(2, null, { id: "tg-t" })] }); + await draw(base); + const first = card(); + assert.ok(first, "Your turn"); + await draw({ ...base, state: "running" }); + assert.equal(card(), null, "Running"); + await draw({ ...base, state: "your_turn", last_event_at: base.last_event_at + 1 }); + assert.ok(card(), "Your turn again"); + await draw({ ...base, state: "idle" }); + assert.ok(card(), "Idle"); + await draw({ ...base, state: "needs_you", questions: [] }); + assert.equal(card(), null, "Decision mode"); + // The kept node is the same on a draw that changes nothing in the card. + await draw(base); + const kept = card(); + await draw({ ...base, last_event_at: base.last_event_at + 5 }); + assert.equal(card(), kept, "an unchanged card is the node it was"); + delete replies.turn_summary; +}); + +test("the turn card's content passes the summary's prompts through whole, and null where a summary has none; Not done lines are the open ones, plain", () => { + const prompts = [{ text: "Go on", from: "agent", quote: "q" }]; + for (const [summary, said, want] of rows([ + [written({ next: ["a"], did: [], prompts }), { headline: "H.", body: [{ kind: "open", text: "`x` not done" }, { kind: "ask", text: "?" }] }, { headline: "H.", next: ["a"], did: [], notDone: ["x not done"], prompts }], + [{ summary: { summary: "old", quiz: null } }, { headline: "old", body: [] }, { headline: "old", next: null, did: null, notDone: [], prompts: null }], + // A Headline the guards marked keeps its "Agent says:", as the card's `did` items do (outside review of spec #1062). + [written({ next: [], did: [] }), { headline: "Agent says: Fixed the `overlay`", body: [] }, { headline: "Agent says: Fixed the overlay", next: [], did: [], notDone: [], prompts: null }], + [null, { headline: null, body: [] }, { headline: null, next: null, did: null, notDone: [], prompts: null }], + ])) assert.deepEqual(turnCardOf(summary, said), want); +}); + +// Ticket #1069: the turn card's reply. A pill fills the box; Enter sends it past the guard, after `see_session`; where Send can't type, the +// box shows Copy & Jump or Copy reply and Enter only says why; the draft and its focus outlast the card being drawn anew. +/** @type {unknown[][]} */ +const acts = []; +const clipboard = []; +/** @type {any} */ (globalThis.navigator).clipboard = { writeText: async (words) => void clipboard.push(words) }; +const herdr = { bundle: null, program: null, herdr: "t7", app: "Herdr" }; +const ghostty = { bundle: "com.mitchellh.ghostty", program: "ghostty", herdr: null, app: "Ghostty" }; +const unknownTerminal = { bundle: null, program: "xterm", herdr: null, app: null }; +/** @param {string} command @param {(args: any) => unknown} [reply] */ +const record = (command, reply = () => null) => (replies[command] = (args) => { + acts.push([command, args]); + return reply(args); +}); +const enter = (field, fields = {}) => { + const event = { key: "Enter", shiftKey: false, isComposing: false, keyCode: 13, defaultPrevented: false, preventDefault() { + event.defaultPrevented = true; + }, ...fields }; + field.listeners.keydown(event); + return event; +}; +const type = (field, words) => { + field.value = words; + field.listeners.input?.(); +}; +const replyButtons = () => card().querySelector(".turn-reply-foot").querySelectorAll("button").map((b) => [b.text, b.classList.contains("primary"), b.getAttribute("aria-disabled") === "true"]); +const replyStatus = () => card().querySelector(".turn-reply-status")?.text ?? null; +const replySession = (id, terminal = herdr) => sessionOf({ id, resume_id: id, terminal, turns: [turn(1, null), turn(2, null, { id: `${id}-t` })] }); + +test("a pill puts its text in the box and focuses it, replacing what the box held", async () => { + replies.turn_summary = () => written({ headline: "Filed #7.", next: [], did: [], prompts: [{ text: "Go with A", from: "agent", quote: "q" }, { text: "Implement #7", from: "suggested", quote: "" }] }); + await draw(replySession("rp", ghostty)); + type(box(), "half a thought"); + pills()[1].click(); + assert.equal(box().value, "Implement #7"); + assert.equal(document.activeElement, box(), "the box has the focus"); + pills()[0].click(); + assert.equal(box().value, "Go with A"); + delete replies.turn_summary; +}); + +test("Enter sends the box's text after see_session and empties the box; Shift+Enter and an input method's Enter send nothing; a failed send keeps the text and says why", async () => { + replies.turn_summary = () => written({ headline: "Filed #7.", next: [], did: [], prompts: [] }); + replies.send_guard = () => ({ passes: true, reason: null }); + for (const [name, keys, send, want] of rows([ + ["Enter", {}, () => null, { acts: ["see_session", "send"], value: "", status: "Sent", prevented: true }], + ["Shift+Enter", { shiftKey: true }, () => null, { acts: [], value: "Go with A", status: "Enter sends · Shift+Enter new line", prevented: false }], + ["an input method's Enter", { isComposing: true }, () => null, { acts: [], value: "Go with A", status: "Enter sends · Shift+Enter new line", prevented: true }], + ["Safari's input method Enter", { keyCode: 229 }, () => null, { acts: [], value: "Go with A", status: "Enter sends · Shift+Enter new line", prevented: true }], + ["a failed send", {}, () => Promise.reject(new Error("The agent is busy")), { acts: ["see_session", "send"], value: "Go with A", status: "Not sent: The agent is busy", prevented: true }], + ])) { + const id = `rs${name.replace(/\W/g, "")}`; + await draw(replySession(id)); + assert.deepEqual(replyButtons(), [["Copy & Jump", false, false], ["Send in Herdr", true, false]], `${name}: Send past the guard`); + acts.length = 0; + record("see_session"); + record("send", send); + type(box(), "Go with A"); + const event = enter(box(), keys); + await later(); + await later(); + assert.deepEqual(acts.map(([command]) => command), want.acts, name); + if (want.acts.length) assert.deepEqual(acts, [["see_session", { id }], ["send", { session: id, text: "Go with A" }]], name); + assert.equal(event.defaultPrevented, want.prevented, `${name}: Shift+Enter adds its line`); + assert.equal(box().value, want.value, name); + assert.equal(replyStatus(), want.status, name); + } + delete replies.send; + delete replies.see_session; + delete replies.send_guard; + delete replies.turn_summary; +}); + +test("where Send can't type, the box shows Copy & Jump or Copy reply with the reason; Enter only says why, sending, copying and jumping nothing; the copy copies the box", async () => { + replies.turn_summary = () => written({ headline: "Filed #7.", next: [], did: [], prompts: [] }); + replies.send_guard = () => ({ passes: false, reason: "The agent is busy" }); + for (const [name, terminal, want] of rows([ + ["the guard refuses", herdr, { buttons: [["Copy & Jump", true, false], ["Send in Herdr", false, true]], status: "Send is off: The agent is busy", enter: "Not sent: The agent is busy; use Copy & Jump", jumps: true }], + ["a terminal the Jump knows", ghostty, { buttons: [["Copy & Jump", true, false]], status: "Send is off: This session doesn't run in Herdr.app", enter: "Not sent: This session doesn't run in Herdr.app; use Copy & Jump", jumps: true }], + ["a terminal it doesn't", unknownTerminal, { buttons: [["Copy reply", true, false]], status: "No jump: plotkeeper doesn't know this session's terminal", enter: "Not sent: This session doesn't run in Herdr.app; use Copy reply", jumps: false }], + ])) { + const id = `ro${name.replace(/\W/g, "")}`; + await draw(replySession(id, terminal)); + assert.deepEqual(replyButtons(), want.buttons, name); + assert.equal(replyStatus(), want.status, name); + acts.length = 0; + clipboard.length = 0; + for (const command of ["see_session", "send", "jump"]) record(command); + type(box(), "Go with A"); + enter(box()); + await later(); + assert.deepEqual([acts, clipboard], [[], []], `${name}: Enter sends, copies and jumps nothing`); + assert.equal(replyStatus(), want.enter, name); + card().querySelector(".turn-reply-foot").querySelector("button").click(); + await later(); + assert.deepEqual(clipboard, ["Go with A"], `${name}: the box's text is copied`); + assert.deepEqual(acts, want.jumps ? [["jump", { session: id }]] : [], name); + assert.equal(box().value, "Go with A", `${name}: the copy keeps the box`); + } + for (const command of ["see_session", "send", "jump", "send_guard", "turn_summary"]) delete replies[command]; +}); + +test("a turn's guard answer that lands after the next turn ended is dropped: the newer turn's answer stands", async () => { + replies.turn_summary = () => written({ headline: "Filed #7.", next: [], did: [], prompts: [] }); + /** @type {((guard: unknown) => void)[]} */ + const answers = []; + replies.send_guard = () => new Promise((done) => void answers.push(done)); + const session = replySession("rg"); + await draw(session); + await draw({ ...session, turns: [...session.turns, turn(3, null, { id: "rg-t3" })] }); + assert.equal(answers.length, 2, "the guard is asked again for the new turn"); + answers[1]({ passes: false, reason: "The agent is busy" }); + await later(); + answers[0]({ passes: true, reason: null }); + await later(); + await later(); + assert.equal(replyStatus(), "Send is off: The agent is busy"); + delete replies.send_guard; + delete replies.turn_summary; +}); + +test("the draft and its focus outlast the card drawn anew as its summary arrives", async () => { + let arrive = () => {}; + replies.turn_summary = () => new Promise((done) => { + arrive = () => done(written({ headline: "Filed #7.", next: ["Choose A or B"], did: [], prompts: [{ text: "Go with A", from: "agent", quote: "q" }] })); + }); + await draw(replySession("rd", ghostty)); + const before = card(); + const field = box(); + assert.equal(pills().length, 0, "no pills before the summary"); + type(field, "Half written"); + field.focus(); + arrive(); + await later(); + await later(); + assert.notEqual(card(), before, "the card is drawn anew"); + assert.equal(pills().length, 1, "the pills came with the summary"); + assert.equal(box(), field, "the same box"); + assert.equal(box().value, "Half written"); + assert.equal(document.activeElement, field, "the box keeps the focus"); + delete replies.turn_summary; +}); diff --git a/ui/types.ts b/ui/types.ts index 31bba6bc..2d361780 100644 --- a/ui/types.ts +++ b/ui/types.ts @@ -318,8 +318,13 @@ export type BlockedCommand = { * before danielrispler/plotkeeper#118 read as the old Quiz. * `headline` and `lines` are the turn writer's Headline and typed Body lines (danielrispler/plotkeeper#115); a summary stored * before them has neither, and its `summary` text reads as a Headline and `reported` lines. + * `next`, `did` and `prompts` are the turn card's lists and reply prompts (spec #1062): absent or null on a summary + * stored before them, an empty list when the turn has none. */ export type SummaryLine = { kind: "why" | "reported" | "open" | "ask"; text: string }; +// A prompt Daniel may send in reply: `agent` when the final reply proposes it, `quote` being that sentence; `suggested` +// when the writer suggests it, with an empty quote. +export type ReplyPrompt = { text: string; from: "agent" | "suggested"; quote: string }; // The server sends the summary as the store keeps it: also the request it was written from, when it arrived and the // turn's hunks, which the window never reads. type SummaryRequest = { @@ -337,7 +342,15 @@ export type TurnSummary = { added_at?: number; hunk?: string; // The Quiz of a summary stored before #347, which the window no longer shows; a new summary has none. - summary: { summary: string; headline?: string | null; lines?: SummaryLine[]; quiz?: Quiz | null }; + summary: { + summary: string; + headline?: string | null; + lines?: SummaryLine[]; + quiz?: Quiz | null; + next?: string[] | null; + did?: string[] | null; + prompts?: ReplyPrompt[] | null; + }; taps?: QuizTap[]; // The self-test's arm (#130), kept in the store. arm?: "quiz_first" | "body_only" | null; diff --git a/understanding/src/lib.rs b/understanding/src/lib.rs index 929659cd..ac8c51e3 100644 --- a/understanding/src/lib.rs +++ b/understanding/src/lib.rs @@ -57,7 +57,8 @@ pub use store::{ SessionCards, StoredCard, StoredSummary, Surface, Tap, millis, }; pub use summary::{ - Line, LineKind, SummarySetup, TurnSummary, write_agent_summary, write_name, write_summary, + Line, LineKind, PromptFrom, ReplyPrompt, SummarySetup, TurnSummary, write_agent_summary, + write_name, write_summary, }; pub use turn_trees::{ Hunk, MAX_TURN_FILES, add_hunks, anchor, diff_turn, found_files, hunk, hunk_view, numstat, diff --git a/understanding/src/summary.rs b/understanding/src/summary.rs index 7bb00863..d16aabb9 100644 --- a/understanding/src/summary.rs +++ b/understanding/src/summary.rs @@ -2,7 +2,9 @@ //! writer call when a long turn ends, on a small model with the studio's own system prompt, read with the session's last 3 //! summaries. It writes no Quiz since danielrispler/plotkeeper#347. -use crate::grounding::{HEADLINE_WORDS, agent_says, facts_text, grounded, material, words}; +use crate::grounding::{ + HEADLINE_WORDS, agent_says, bare, facts_text, grounded, material, quoted, words, +}; use crate::{CardStore, CardWriter, ClaudeWriter, MAX_CHANGE, Quiz, WriterRequest}; use serde::{Deserialize, Serialize}; use std::{process::Command, sync::Mutex}; @@ -34,6 +36,33 @@ pub struct Line { /// The most Body lines a turn has. const LINES: usize = 3; +/// Who a reply prompt comes from (spec #1062). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PromptFrom { + /// A move the reply proposes, backed by its `quote`. + Agent, + /// The writer's own suggestion for a next step. + Suggested, +} + +/// A prompt Daniel may send in reply to the turn, written as his own words (spec #1062). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ReplyPrompt { + pub text: String, + pub from: PromptFrom, + /// The final reply's sentence that proposes it, for an `agent` prompt; empty for a `suggested` one. + pub quote: String, +} + +/// The most items of what's next and of what was done, and their most words. +const ITEMS: usize = 3; +const ITEM_WORDS: usize = 14; +/// The most words of a reply prompt, and the most `agent` and `suggested` prompts kept. +const PROMPT_WORDS: usize = 12; +const AGENT_PROMPTS: usize = 2; +const SUGGESTED_PROMPTS: usize = 1; + /// A turn's summary: its Headline and Body. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TurnSummary { @@ -51,6 +80,16 @@ pub struct TurnSummary { /// `None`. A learning section stored before danielrispler/plotkeeper#118 reads as its question (`stored_quiz`). #[serde(default, alias = "learning", deserialize_with = "stored_quiz")] pub quiz: Option, + /// What the reply asks of Daniel or leaves for him, at most 3 (spec #1062). `None` on a summary stored before it, + /// or from a reply without it; empty when the turn asks nothing. + #[serde(default)] + pub next: Option>, + /// What the turn did, at most 3, each claim no check backs read as "Agent says:"; `None` as `next` is. + #[serde(default)] + pub did: Option>, + /// Prompts Daniel may send in reply: at most 2 `agent` and 1 `suggested`; `None` as `next` is. + #[serde(default)] + pub prompts: Option>, } /// A stored Quiz, or a stored learning section, `{idea, question}`, whose question is the Quiz. @@ -97,7 +136,9 @@ impl TurnSummary { /// lines of an unknown kind, or with a number or id that `material` lacks, are dropped. A /// Headline with such a number is stripped, and one over `HEADLINE_WORDS` stands, each with why /// so the reply is asked for once more; a claim of a fix, a pass or a verification gets "Agent - /// says:" unless a check backs it. A Quiz in the reply is ignored. + /// says:" unless a check backs it. A Quiz in the reply is ignored. What's next, what was done and the reply + /// prompts are held to their limits and guards item by item (`items`, `prompts`): a failing item is dropped, + /// never cut, and never asks the reply again. fn from_reply( reply: &str, request: &SummaryRequest, @@ -145,16 +186,78 @@ impl TurnSummary { .chain(texts) .collect::>() .join("\n"); + let did = items(&value["did"], material) + .map(|did| did.iter().map(|d| agent_says(d, &request.facts)).collect()); let summary = TurnSummary { summary, headline: Some(headline), lines, quiz: None, + next: items(&value["next"], material), + did, + prompts: prompts(&value["prompts"], request, material), }; Ok((summary, headline_problem)) } } +/// What is left of a reply's list `sent` once its failing items are dropped: `None` when every item was, so a list the +/// writer filled never reads as an empty one ("Nothing waiting on you"). An empty list sent stays empty. +fn left(sent: &[serde_json::Value], kept: Vec) -> Option> { + (sent.is_empty() || !kept.is_empty()).then_some(kept) +} + +/// The strings of a reply's list, `None` when it holds none or `left` gives none: each grounded in `material` and of at +/// most `ITEM_WORDS` words, at most `ITEMS`. +fn items(list: &serde_json::Value, material: &str) -> Option> { + let list = list.as_array()?; + let items = (list.iter().filter_map(serde_json::Value::as_str)) + .map(str::trim) + .filter(|item| !item.is_empty() && words(item) <= ITEM_WORDS && grounded(item, material)) + .take(ITEMS) + .map(String::from); + left(list, items.collect()) +} + +/// The reply prompts of a reply's list, `None` when it holds none or `left` gives none: each text grounded in `material` and of at most +/// `PROMPT_WORDS` words; an `agent` one's quote in `request`'s final reply, a `suggested` one's quote empty. The first `AGENT_PROMPTS` `agent` and +/// `SUGGESTED_PROMPTS` `suggested` ones are kept, in the reply's order. +fn prompts( + list: &serde_json::Value, + request: &SummaryRequest, + material: &str, +) -> Option> { + let list = list.as_array()?; + let reply = bare(request.responses.last().map_or("", String::as_str)); + let (mut agent, mut suggested) = (0, 0); + let prompts = list.iter().filter_map(|prompt| { + let from = serde_json::from_value(prompt["from"].clone()).ok()?; + let text = prompt["text"].as_str()?.trim(); + let quote = prompt["quote"].as_str().unwrap_or_default().trim(); + let fits = !text.is_empty() && words(text) <= PROMPT_WORDS && grounded(text, material); + let kept = fits + && match from { + PromptFrom::Agent => quoted(quote, &reply) && take(&mut agent, AGENT_PROMPTS), + PromptFrom::Suggested => take(&mut suggested, SUGGESTED_PROMPTS), + }; + kept.then(|| ReplyPrompt { + text: text.into(), + from, + quote: match from { + PromptFrom::Agent => quote.into(), + PromptFrom::Suggested => String::new(), + }, + }) + }); + left(list, prompts.collect()) +} + +/// Whether one more of a kind fits under `most`, counting it in `taken` when it does. +fn take(taken: &mut usize, most: usize) -> bool { + *taken += 1; + *taken <= most +} + /// The summary of `request`'s turn from `writer`, read with the session's last 3 summaries in /// `store`, which keeps it. The writer is asked once more when its reply gives none, or gives a /// Headline with an invented number or over 16 words; the second reply stands, or the first when @@ -362,9 +465,12 @@ The studio shows the recorded files and checks itself, next to your headline. Do r#" Reply with one JSON object and nothing else: -{"headline": string, "lines": [{"kind": "why" | "reported" | "open" | "ask", "text": string}]} +{"headline": string, "lines": [{"kind": "why" | "reported" | "open" | "ask", "text": string}], "next": [string], "did": [string], "prompts": [{"text": string, "from": "agent" | "suggested", "quote": string}]} - headline: at most 16 words, one sentence that states an outcome, or what the turn waits on. Never narrate ("Looked at", "Started by"). When the turn ends by asking the developer something, the headline is that ask. - lines: at most 3, each at most 20 words, each typed. why: the reason for a choice the turn made. reported: something the agent claims that the recorded facts do not show. open: what was left undone or was not checked, such as "Nobody looked at the rows in a real window." ask: a question or decision the agent puts to the developer. Leave out a line that says nothing more than the headline. +- next: at most 3, each at most 14 words: what the agent's final response asks of the developer or leaves for him to do, such as "Choose where the notes box goes". [] when it asks and leaves him nothing. +- did: at most 3, each at most 14 words: what the turn did, such as "Filed the ticket for the notes box". +- prompts: at most 3 prompts the developer might send next, each one line of at most 12 words, written as his own words to the agent, such as "Implement it in a worktree". from "agent": a move the agent's final response itself proposes or offers; quote is that response's sentence that proposes it, copied exactly. At most two agent prompts. from "suggested": your own suggestion for a next step that the response does not propose, with quote "". At most one suggested prompt. [] when nothing fits. A number taken from the input keeps its bound or condition, such as "upper bound", "on fixtures" or "median", wherever it appears. "# diff --git a/understanding/tests/brief.rs b/understanding/tests/brief.rs index 29ec6313..7c1dc33f 100644 --- a/understanding/tests/brief.rs +++ b/understanding/tests/brief.rs @@ -66,6 +66,9 @@ fn store(dir: &std::path::Path) -> CardStore { line(LineKind::Ask, "Should the ref be pruned?"), ], quiz: None, + next: None, + did: None, + prompts: None, }; store.add_summary(request, summary).unwrap(); store diff --git a/understanding/tests/fixtures/stored/README.md b/understanding/tests/fixtures/stored/README.md index 01ef8b62..e58ab293 100644 --- a/understanding/tests/fixtures/stored/README.md +++ b/understanding/tests/fixtures/stored/README.md @@ -54,6 +54,11 @@ one with two parts, each line with the last turn it covers. The store reads the open round whose first question quotes a context and has no recommendation, and whose second has an empty one. The store reads the other files as missing; `full-4/` to `full-7/`, with no `context`, read with an empty one. +`full-10/` holds one file, `summaries.json`, as written once a turn summary keeps the turn card's lists and reply prompts (spec +#1062, ticket #1067): one summary with `next`, `did` (a claim read as "Agent says:") and `prompts`, an `agent` one with its quote +and a `suggested` one with none, and one of a turn that asks nothing, with empty lists. The store reads the other files as missing; +the older samples, with none of these fields, read with `None`. + `pr-brief-v4/` holds a stored PR brief and a stored part catch-up as written once chapters carry a gist (#397): `gist` and its `gist_flags` on a Core chapter, an empty gist on a chapter of no Core part. `understanding/tests/pr_brief.rs` loads them beside `pr-brief-v3/`, whose replies and stored briefs have no gist and still read. diff --git a/understanding/tests/fixtures/stored/full-10/summaries.json b/understanding/tests/fixtures/stored/full-10/summaries.json new file mode 100644 index 00000000..36dd24e3 --- /dev/null +++ b/understanding/tests/fixtures/stored/full-10/summaries.json @@ -0,0 +1,61 @@ +[ + { + "request": { + "session_id": "sess-1", + "id": "sess-1@1761743900000", + "prompt": "Sample prompt.", + "responses": ["Sample first reply.", "Filed the sample ticket. Shall I implement it in a worktree?"], + "intentions": ["Sample intention.", "Filing the sample ticket."], + "card": null, + "facts": { + "files": [ + { "root": "/work/sample", "path": "a.rs", "from": null, "added": 1, "removed": 1, "agent": null } + ], + "checks": [], + "external": 0 + }, + "wanted": true + }, + "summary": { + "summary": "Filed the sample ticket; asks whether to implement it.\nNobody ran the sample check.", + "headline": "Filed the sample ticket; asks whether to implement it.", + "lines": [{ "kind": "open", "text": "Nobody ran the sample check." }], + "quiz": null, + "next": ["Choose whether to implement the sample ticket", "Read the sample ticket"], + "did": ["Filed the sample ticket", "Agent says: Fixed the sample name"], + "prompts": [ + { "text": "Implement it in a worktree", "from": "agent", "quote": "Shall I implement it in a worktree?" }, + { "text": "Run the sample check first", "from": "suggested", "quote": "" } + ] + }, + "added_at": 1761743960000, + "taps": [], + "hunk": "@@ -1 +1 @@\n-old\n+new\n", + "arm": null + }, + { + "request": { + "session_id": "sess-1", + "id": "sess-1@1761744000000", + "prompt": "Sample second prompt.", + "responses": ["Renamed the sample function."], + "intentions": ["Renaming the sample function."], + "card": null, + "facts": { "files": [], "checks": [], "external": 0 }, + "wanted": true + }, + "summary": { + "summary": "Renamed the sample function.", + "headline": "Renamed the sample function.", + "lines": [], + "quiz": null, + "next": [], + "did": ["Renamed the sample function"], + "prompts": [] + }, + "added_at": 1761744060000, + "taps": [], + "hunk": "", + "arm": null + } +] diff --git a/understanding/tests/stored_fixtures.rs b/understanding/tests/stored_fixtures.rs index fcc7d39a..4dc5e79d 100644 --- a/understanding/tests/stored_fixtures.rs +++ b/understanding/tests/stored_fixtures.rs @@ -10,7 +10,7 @@ use std::fs; use std::path::Path; use studio_core::CheckStatus as Status; use studio_core::{PlanMode, Source}; -use studio_understanding::{AnswerSource, CardStore, Level, Pick, Reason, RoundStatus}; +use studio_understanding::{AnswerSource, CardStore, Level, Pick, PromptFrom, Reason, RoundStatus}; use studio_understanding::{CheckResult, RiskLevel, RiskNotes, RiskView, Surface, Tap}; const FILES: [&str; 7] = [ @@ -618,3 +618,73 @@ fn the_sample_of_the_behaviour_lines_loads_with_its_values() { assert_eq!(store.part_lines("sess-1"), [], "{sample}"); } } + +/// Spec #1062, ticket #1067: `summaries.json` as written once a turn summary keeps the turn card's lists and reply prompts +/// (`next`, `did`, `prompts`). `full-10/` holds that file alone: a summary with each field filled, an `agent` prompt with its +/// quote and a `suggested` one, and a summary of a turn that asks nothing, with empty lists. The older samples, with none of +/// these fields, read with `None`, which the page tells from an empty list. +// @law: old-stored-files-load +#[test] +fn the_sample_of_the_turn_cards_lists_and_prompts_loads_with_its_values() { + let from = + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/stored/full-10/summaries.json"); + let data = tempfile::tempdir().unwrap(); + fs::copy(&from, data.path().join("summaries.json")).expect("sample `full-10/summaries.json`"); + let store = + CardStore::open(data.path().join("cards-v2.json")).expect("the `full-10` sample loads"); + + let [filled, empty] = store.summaries() else { + panic!("two summaries") + }; + let filled = &filled.summary; + assert_eq!( + filled.next.as_deref(), + Some( + &[ + "Choose whether to implement the sample ticket".to_string(), + "Read the sample ticket".to_string() + ][..] + ) + ); + assert_eq!( + filled.did.as_deref(), + Some( + &[ + "Filed the sample ticket".to_string(), + "Agent says: Fixed the sample name".to_string() + ][..] + ) + ); + let prompts: Vec<_> = (filled.prompts.iter().flatten()) + .map(|p| (p.text.as_str(), p.from, p.quote.as_str())) + .collect(); + assert_eq!( + prompts, + [ + ( + "Implement it in a worktree", + PromptFrom::Agent, + "Shall I implement it in a worktree?" + ), + ("Run the sample check first", PromptFrom::Suggested, ""), + ] + ); + let empty = &empty.summary; + assert_eq!( + (empty.next.as_deref(), empty.prompts.as_deref()), + (Some(&[][..]), Some(&[][..])) + ); + + for sample in ["full", "minimal"] { + let (_data, store) = open(sample); + let [old] = store.summaries() else { + panic!("{sample}: one summary") + }; + let old = &old.summary; + assert_eq!( + (&old.next, &old.did, &old.prompts), + (&None, &None, &None), + "{sample}" + ); + } +} diff --git a/understanding/tests/wire.rs b/understanding/tests/wire.rs index cb302313..7976d606 100644 --- a/understanding/tests/wire.rs +++ b/understanding/tests/wire.rs @@ -5,9 +5,9 @@ use crate::samples::{Sample, json, write}; use studio_core::{FactFile, Facts, Studio, SummaryRequest, TurnFile}; use studio_understanding::{ - Answered, Arm, CardStore, Choice, DesignLine, Line, LineKind, OpenItem, OpenKind, Quiz, - QuizTap, RiskLevel, RiskView, Row, SessionCards, StoredSummary, Surface, Tap, TurnSummary, - hunk_view, + Answered, Arm, CardStore, Choice, DesignLine, Line, LineKind, OpenItem, OpenKind, PromptFrom, + Quiz, QuizTap, ReplyPrompt, RiskLevel, RiskView, Row, SessionCards, StoredSummary, Surface, + Tap, TurnSummary, hunk_view, }; const SESSION: &str = "5b9e3d71-0c2a-4f8e-b6d4-8a1c3e5f7092"; @@ -53,7 +53,8 @@ fn taps() -> Vec { .collect() } -/// A turn's summary with its request, facts and Quiz, and one stored before the Headline and lines. +/// A turn's summary with its request, facts, Quiz, lists and reply prompts, and one stored before the Headline and +/// lines. fn summaries(checks: &Studio) -> [StoredSummary; 2] { let check = (checks.sessions().iter()) .flat_map(|s| &s.turns) @@ -104,6 +105,20 @@ fn summaries(checks: &Studio) -> [StoredSummary; 2] { }) .collect(), quiz: Some(quiz()), + next: Some(vec!["Choose where the box goes".into()]), + did: Some(vec!["Agent says: Fixed the reader".into()]), + prompts: Some(vec![ + ReplyPrompt { + text: "Merge it now".into(), + from: PromptFrom::Agent, + quote: "Shall I merge it now?".into(), + }, + ReplyPrompt { + text: "Write the docs".into(), + from: PromptFrom::Suggested, + quote: String::new(), + }, + ]), }, added_at: AT, taps: taps(), @@ -117,6 +132,9 @@ fn summaries(checks: &Studio) -> [StoredSummary; 2] { headline: None, lines: Vec::new(), quiz: None, + next: None, + did: None, + prompts: None, }, added_at: AT, taps: Vec::new(), diff --git a/understanding/tests/writer.rs b/understanding/tests/writer.rs index 4c7ec85b..22e0e597 100644 --- a/understanding/tests/writer.rs +++ b/understanding/tests/writer.rs @@ -13,8 +13,8 @@ use studio_core::{ Check, CheckRun, CheckStatus, FactFile, Facts, RoundRequest, SummaryRequest, TurnFile, }; use studio_understanding::{ - CardStore, ClaudeWriter, LineKind, Risk, SummarySetup, TurnSummary, write_agent_summary, - write_name, write_summary, + CardStore, ClaudeWriter, Risk, SummarySetup, TurnSummary, write_agent_summary, write_name, + write_summary, }; #[cfg(unix)] use studio_understanding::{CardWriter, RISK_TIMEOUT, RiskLevel, find_claude}; @@ -442,25 +442,6 @@ fn the_summary_input_holds_the_sessions_last_3_summaries() { ); } -#[test] -fn a_reply_with_a_null_or_missing_quiz_gives_the_summary_alone_and_logs_nothing() { - for reply in [ - r#"{"headline": "Merged the lanes.", "quiz": null}"#, - r#"{"headline": "Rewrote the parser."}"#, - ] { - let dir = tempfile::tempdir().unwrap(); - let store = summaries(dir.path()); - let writer = recording(reply.into()); - let mut lines = Vec::new(); - - let summary = write_summary(&store, &writer, &setup(), turn("s", 1), |l| lines.push(l)); - - assert_eq!(summary.unwrap().quiz, None, "{reply}"); - assert_eq!(lines, Vec::::new(), "{reply}"); - assert_eq!(writer.inputs().len(), 1, "no retry: {reply}"); - } -} - #[test] fn a_learning_section_stored_before_the_quiz_reads_as_a_quiz() { let old = r#"{"summary": "Rewrote the parser.", "learning": {"idea": "A stack.", "question": {"text": "Why a stack?", "options": [{"text": "It nests.", "why": "Yes."}, {"text": "It is fast.", "why": "No."}], "key": 0}}}"#; @@ -549,6 +530,15 @@ fn the_summary_and_subagent_calls_run_in_safe_mode_with_the_settings_model_effor ); if system_mentions == "turn summary" { assert!(system.contains("keeps its bound or condition"), "{system}"); + // The turn card's lists and reply prompts (spec #1062), one `suggested` prompt at most. + for field in [ + r#""next": [string]"#, + r#""did": [string]"#, + r#""prompts": [{"text""#, + ] { + assert!(system.contains(field), "{field} in {system}"); + } + assert!(system.contains("At most one suggested prompt"), "{system}"); assert!(input.contains("Explain the parser")); assert!(input.contains("It keeps a bracket stack.")); } else if system_mentions == "questions" { @@ -784,60 +774,28 @@ fn the_writers_input_holds_the_turns_files_counts_capped_hunks_and_check_facts() ); } +/// One summary reply read for `request`, each field of `want` compared with the stored summary's, as JSON; a field +/// `want` leaves out is not checked. No row asks the writer again or logs a line: only the Headline's problems do. #[test] -fn typed_lines_parse_and_a_line_of_an_unknown_type_is_dropped() { - let lines = serde_json::json!([ - { "kind": "why", "text": "A bracket stack keeps nesting." }, - { "kind": "opinion", "text": "I like it." }, - { "kind": "open", "text": "Nobody looked at it in a real window." }, - { "kind": "ask", "text": "Merge it?" }, - ]); - - let (summary, _) = written_by(turn("s", 1), &[reply("Rewrote the parser.", lines)]); - - assert_eq!(summary.headline.as_deref(), Some("Rewrote the parser.")); - let kinds: Vec = summary.lines.iter().map(|l| l.kind).collect(); - assert_eq!(kinds, [LineKind::Why, LineKind::Open, LineKind::Ask]); - assert_eq!( - summary.summary, - "Rewrote the parser.\nA bracket stack keeps nesting.\nNobody looked at it in a real window.\nMerge it?" - ); -} - -#[test] -fn a_fix_with_no_passed_check_is_the_agents_claim_and_one_with_a_passed_check_is_not() { - let said = |checks: Vec| { - let request = with_facts(checks); - written_by( - request, - &[reply("Fixed the overlay", serde_json::json!([]))], - ) - .0 - .headline +#[allow( + clippy::too_many_lines, + reason = "one row per reply, written out in one place" +)] +fn a_summary_reply_reads_into_its_headline_body_and_lists() { + use serde_json::{Value, json}; + let passed = || with_facts(vec![check(CheckStatus::Passed, 2, 0)]); + // A turn whose final reply proposes moves; its first response is not the final reply. + let proposing = || { + SummaryRequest { + responses: vec![ + "Reading the parser first.".into(), + "Rewrote the parser.\n\n**Shall I merge it now?** I can also add a test for nesting. Or I could write the docs.".into(), + ], + ..passed() + } }; - - assert_eq!( - said(vec![]).as_deref(), - Some("Agent says: Fixed the overlay") - ); - assert_eq!( - said(vec![check(CheckStatus::Failed, 0, 1)]).as_deref(), - Some("Agent says: Fixed the overlay") - ); - assert_eq!( - said(vec![check(CheckStatus::Ran, 0, 0)]).as_deref(), - Some("Agent says: Fixed the overlay") - ); - assert_eq!( - said(vec![check(CheckStatus::Passed, 0, 0)]).as_deref(), - Some("Fixed the overlay") - ); -} - -#[test] -fn a_line_with_a_number_or_id_the_turn_lacks_is_stripped_and_true_numbers_stay() { - let request = with_facts(vec![check(CheckStatus::Passed, 2, 0)]); - let texts = [ + let long = |n: usize| vec!["word"; n].join(" "); + let numbers = [ "Made 12 changes.", // an invented count "Cut the cost by 40%.", // a percentage "Closes #123.", // an issue id @@ -849,16 +807,206 @@ fn a_line_with_a_number_or_id_the_turn_lacks_is_stripped_and_true_numbers_stay() "Edited src/parser2.rs.", // digits in a known path "Edited src/parser3.rs.", // digits in an unknown path ]; - let kept: Vec<&str> = texts - .into_iter() - .filter(|text| { - let lines = serde_json::json!([{ "kind": "why", "text": text }]); - let (summary, _) = written_by(request.clone(), &[reply("Widened the parser.", lines)]); - !summary.lines.is_empty() - }) - .collect(); - - assert_eq!(kept, [texts[4], texts[5], texts[6], texts[7], texts[8]]); + let why = |texts: &[&str]| { + let lines: Vec = (texts.iter()) + .map(|text| json!({ "kind": "why", "text": text })) + .collect(); + Value::from(lines) + }; + let fix = json!({ "headline": "Fixed the overlay", "quiz": null }); + let cases: Vec<(&str, SummaryRequest, Value, Value)> = vec![ + ( + "typed lines parse and a line of an unknown type is dropped", + passed(), + json!({ "headline": "Rewrote the parser.", "lines": [ + { "kind": "why", "text": "A bracket stack keeps nesting." }, + { "kind": "opinion", "text": "I like it." }, + { "kind": "open", "text": "Nobody looked at it in a real window." }, + { "kind": "ask", "text": "Merge it?" }, + ] }), + json!({ + "headline": "Rewrote the parser.", + "lines": [ + { "kind": "why", "text": "A bracket stack keeps nesting." }, + { "kind": "open", "text": "Nobody looked at it in a real window." }, + { "kind": "ask", "text": "Merge it?" }, + ], + "summary": "Rewrote the parser.\nA bracket stack keeps nesting.\nNobody looked at it in a real window.\nMerge it?", + }), + ), + ( + "a fix with no check is the agent's claim", + with_facts(vec![]), + fix.clone(), + json!({ "headline": "Agent says: Fixed the overlay" }), + ), + ( + "a fix with a failed check is the agent's claim", + with_facts(vec![check(CheckStatus::Failed, 0, 1)]), + fix.clone(), + json!({ "headline": "Agent says: Fixed the overlay" }), + ), + ( + "a fix with a check that only ran is the agent's claim", + with_facts(vec![check(CheckStatus::Ran, 0, 0)]), + fix.clone(), + json!({ "headline": "Agent says: Fixed the overlay" }), + ), + ( + "a fix with a passed check is not", + with_facts(vec![check(CheckStatus::Passed, 0, 0)]), + fix.clone(), + json!({ "headline": "Fixed the overlay" }), + ), + ( + "a line with a number or id the turn lacks is dropped", + passed(), + json!({ "headline": "Widened the parser.", "lines": why(&[ + numbers[0], numbers[1], numbers[2], numbers[3], numbers[9], + ]) }), + json!({ "lines": [] }), + ), + ( + "a line with numbers the turn holds stays", + passed(), + json!({ "headline": "Widened the parser.", "lines": why(&numbers[5..=7]) }), + json!({ "lines": why(&numbers[5..=7]) }), + ), + ( + "a line with number words or a known path with digits stays", + passed(), + json!({ "headline": "Widened the parser.", "lines": why(&[numbers[4], numbers[8]]) }), + json!({ "lines": why(&[numbers[4], numbers[8]]) }), + ), + ( + "a null quiz gives the summary alone", + passed(), + json!({ "headline": "Merged the lanes.", "quiz": null }), + json!({ "headline": "Merged the lanes.", "quiz": null }), + ), + ( + "a reply with only a headline gives the summary alone", + passed(), + json!({ "headline": "Rewrote the parser." }), + json!({ + "headline": "Rewrote the parser.", "lines": [], "quiz": null, + "next": null, "did": null, "prompts": null, + }), + ), + ( + "what's next and what was done parse, at most 3 each", + passed(), + json!({ + "headline": "Rewrote the parser.", + "next": ["Choose where the box goes", "Merge the branch", "Read the docs", "Rest"], + "did": ["Rewrote the parser", "Kept a bracket stack", "Wrote a note", "Slept"], + }), + json!({ + "next": ["Choose where the box goes", "Merge the branch", "Read the docs"], + "did": ["Rewrote the parser", "Kept a bracket stack", "Wrote a note"], + "prompts": null, + }), + ), + ( + "an item over its word limit is dropped, not cut", + proposing(), + json!({ + "headline": "Rewrote the parser.", + "next": [&long(15), "Merge the branch", &long(14)], + "did": [&long(15), "Rewrote the parser"], + "prompts": [ + { "text": long(13), "from": "suggested", "quote": "" }, + { "text": long(12), "from": "agent", "quote": "Shall I merge it now?" }, + ], + }), + json!({ + "next": ["Merge the branch", long(14)], + "did": ["Rewrote the parser"], + "prompts": [{ "text": long(12), "from": "agent", "quote": "Shall I merge it now?" }], + }), + ), + ( + "an item with a number the turn lacks is dropped", + passed(), + json!({ + "headline": "Widened the parser.", + "next": ["Review the 12 changes", "Merge the branch"], + "did": [numbers[5], numbers[0]], + "prompts": [{ "text": "Close #123", "from": "suggested", "quote": "" }], + }), + json!({ "next": ["Merge the branch"], "did": [numbers[5]], "prompts": null }), + ), + ( + "a list whose every item is dropped is no list, not an empty one", + passed(), + json!({ + "headline": "Widened the parser.", + "next": ["Review the 12 changes", &long(15)], + "did": [numbers[0], ""], + "prompts": [{ "text": "Close #123", "from": "suggested", "quote": "" }], + }), + json!({ "next": null, "did": null, "prompts": null }), + ), + ( + "an agent prompt is kept when its quote is in the final reply", + proposing(), + json!({ "headline": "Rewrote the parser.", "prompts": [ + { "text": "Merge it now", "from": "agent", "quote": "Shall I merge it now?" }, + { "text": "Delete the parser", "from": "agent", "quote": "Shall I delete the parser?" }, + { "text": "Read the parser", "from": "agent", "quote": "Reading the parser first." }, + { "text": "Add a test", "from": "agent", "quote": "" }, + { "text": "Add a test", "from": "nobody", "quote": "" }, + ] }), + json!({ "prompts": [ + { "text": "Merge it now", "from": "agent", "quote": "Shall I merge it now?" }, + ] }), + ), + ( + "a third agent prompt and a second suggested one are dropped; a suggested one has no quote", + proposing(), + json!({ "headline": "Rewrote the parser.", "prompts": [ + { "text": "Write the docs", "from": "suggested", "quote": "Or I could write the docs." }, + { "text": "Merge it now", "from": "agent", "quote": "Shall I merge it now?" }, + { "text": "Ship it too", "from": "suggested", "quote": "" }, + { "text": "Add a nesting test", "from": "agent", "quote": "I can also add a test for nesting." }, + { "text": "Write the docs", "from": "agent", "quote": "Or I could write the docs." }, + ] }), + json!({ "prompts": [ + { "text": "Write the docs", "from": "suggested", "quote": "" }, + { "text": "Merge it now", "from": "agent", "quote": "Shall I merge it now?" }, + { "text": "Add a nesting test", "from": "agent", "quote": "I can also add a test for nesting." }, + ] }), + ), + ( + "a claim of a fix that no passed check backs is what the agent says", + with_facts(vec![]), + json!({ + "headline": "Rewrote the parser.", + "did": ["Fixed the overlay", "Rewrote the parser"], + "next": [], "prompts": [], + }), + json!({ + "did": ["Agent says: Fixed the overlay", "Rewrote the parser"], + "next": [], "prompts": [], + }), + ), + ]; + for (name, request, reply, want) in cases { + let dir = tempfile::tempdir().unwrap(); + let store = summaries(dir.path()); + let writer = Scripted { + summarize: Answer::replies([reply.to_string()]), + ..Scripted::bare() + }; + let mut log = Vec::new(); + let summary = write_summary(&store, &writer, &setup(), request, |l| log.push(l)); + let got = serde_json::to_value(summary.expect(name)).unwrap(); + for (field, want) in want.as_object().unwrap() { + assert_eq!(&got[field], want, "{name}: {field}"); + } + assert_eq!(writer.inputs().len(), 1, "{name}: no retry"); + assert_eq!(log, Vec::::new(), "{name}"); + } } #[test]