Get past a stuck continue or a failed send in one step

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-25 17:04:21 -07:00
1 parent 7a9f56a452
commit 3e22d53bf5
8 files changed
+266 -17

No files matched your search

+2 -1
View File
@@ -193,6 +193,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
| `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` |
| `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser |
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
@@ -254,7 +255,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types `continue` and Enter into the agent's terminal) and `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all). Nothing outside a frame |
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered) and `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all). Nothing outside a frame |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
+8 -1
View File
@@ -24,7 +24,7 @@ All notable changes to Plan2Code will be documented in this file.
- **desktop app**: with nothing saved yet, the terminal panel now starts docked right at a width that keeps the console's own side panels (such as Notes) from stacking under the main content, instead of the bottom dock it always opened with before; a saved choice from before is still kept exactly as it was.
- **desktop app**: docked right and collapsed, the terminal panel's **Expand** label now reads top to bottom instead of running off the edge of the narrow strip.
- **desktop app**: the agent no longer prints the console's web address in the terminal panel, since the page is already in the window beside it: `terminalLine` under the app points at the dashboard instead, and the agent contract says to give no link there.
- **desktop app**: the console's "Not running... type **continue**" line makes **continue** a button under the app, which types `continue` and Enter into the agent's terminal panel for you; the session meter's **Start a New Session** button presses the bar's own New Session (its confirmation included), replacing a "Press New Session at the top of the window" sentence now that the press works from there.
- **desktop app**: the console's "Not running... type **continue**" line makes **continue** a button under the app, which types `continue` and Enter (and, under Claude Code, its send-now chord) into the agent's terminal panel for you; the session meter's **Start a New Session** button presses the bar's own New Session (its confirmation included), replacing a "Press New Session at the top of the window" sentence now that the press works from there.
- **desktop app**: **New Session** now starts the fresh agent on a new console session, so the session meter starts over at green. Before, the fresh agent joined the window's old session, and the meter stayed red after the very press it asks for. The brief of where you were is still written from the old session first, and the old console shuts itself down once the window moves on.
- **web console**: the **Wrapping up** dialog after **Stop session** no longer closes itself when the stop lands: it turns into **Done**, with every step ticked, and stays up until you close it, so someone who stepped away comes back to an answer. Its "you can close the window/tab if you need to" line is gone.
- **web console**: a plan's **Build order** card has a **Combine phases** button beside **No changes**. One click fills the box with a request to merge phases where possible while keeping each to a clear concern. It shows only in Plan and Revise plan, where the breakdown is phases.
@@ -33,6 +33,13 @@ All notable changes to Plan2Code will be documented in this file.
- **desktop app**: the New Session confirmation shows Planny, drawn like the console's own (outlined shell, star eye, smile), holding a steaming cup of coffee, and its buttons use the console's style: **New Session** in your highlight colour, **Cancel** a plain button. The same highlight applies to the panel's other one-button prompts, such as **Retry** and **Reconnect the console**.
- **desktop app**: the top bar is rebuilt around two menus and one next step. The project shows as its folder name, with the full path and **Change project** in its menu; **New Session** always sits just left of the agent's menu, which carries a state dot, an amber **checks off** badge in place of the "Permission checks are off for ..." sentence, and **Change agent** once the agent has ended. The console's and the skills' messages share one slot at the right end that shows the most pressing step with its button (**Reconnect the console**, **Update skills**) and "+N more" for the rest, so the bar no longer overflows when several things go wrong at once. The repeated "Plan2Code" label, the full path, the "agent:" prefix and the long "Nothing starts until you press New Session" line are gone.
### 🐛 Fixed
- **desktop app**: under Claude Code, the console's **continue** button also sends Claude Code's send-now chord (ctrl+x ctrl+s), so a `continue` it held as a queued message behind a stuck turn is delivered in one press instead of waiting in the terminal.
- **desktop app**: links that leave the console (**Open pull request**, links in documents, the feedback button) open in the default browser instead of doing nothing; when no browser can be started, the page shows the link with a **Copy** button to paste into one.
- **web console**: answers sent and not picked up bring up the "not running, type **continue**" help after a minute of the agent's silence (three when it said it was working), instead of after its quiet allowance, which a build can set to half an hour.
- **web console**: a failed Send says why: the lost-contact state and its reconnect help at once when the console is gone, the console's reason when it refuses the send, or that the console is still up and Send can be pressed again.
## v2.11.1
### 🐛 Fixed
+12 -7
View File
@@ -2,7 +2,7 @@
// agent's terminal panel docked at the bottom with a drag handle.
import { mountTerminal } from './terminal.js';
import { barNextSteps, defaultRightFraction, folderName, windowTitleFor } from './meter.js';
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor } from './meter.js';
const { invoke, Channel } = window.__TAURI__.core;
@@ -553,16 +553,21 @@ window.addEventListener('message', (event) => {
}
});
// Its "Not running... type continue" line, pressed: the word, then Enter on
// its own a moment later, so an agent that treats one burst of input as a
// paste still reads the Enter as a submit.
// Its "Not running... type continue" line, pressed: the keystrokes
// continueKeys names, each on its own a moment after the last, so an agent
// that treats one burst of input as a paste still reads the Enter as a submit.
const ENTER_AFTER_MS = 120;
function typeContinue() {
if (!agentActive()) return;
invoke('agent_input', { data: 'continue' })
.then(() => new Promise((resolve) => setTimeout(resolve, ENTER_AFTER_MS)))
.then(() => invoke('agent_input', { data: '\r' }))
continueKeys(agent.kind)
.reduce(
(typed, data, i) =>
typed
.then(() => (i ? new Promise((resolve) => setTimeout(resolve, ENTER_AFTER_MS)) : null))
.then(() => invoke('agent_input', { data })),
Promise.resolve()
)
.catch((error) => {
setAgentStatus(`Could not type continue: ${error}`, { error: true });
});
+14
View File
@@ -11,6 +11,20 @@ export const NEXT_STEP_LABELS = {
update: 'Update skills',
};
/**
* What the console page's **continue** button types into the agent's
* terminal, one write each: the word, then Enter. Claude Code holds typed
* text as a queued message while its turn is busy, and the button only shows
* once the agent stopped checking in with the console, so by then the turn is
* stuck and the queued word would never send by itself: for it, the send-now
* chord (ctrl+x ctrl+s) follows.
*/
export function continueKeys(kind) {
const keys = ['continue', '\r'];
if (kind === 'claude') keys.push('\x18\x13');
return keys;
}
/**
* What the right end of the bar offers, most pressing first: the bar shows
* the first step (short text plus its one button) and counts the rest as
+17 -1
View File
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { barNextSteps, defaultRightFraction, folderName, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { findBrowser, launchBrowser } from "./browser.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -69,6 +69,22 @@ test("app.js draws the bar's right end through barNextSteps, not a hand-rolled c
}
});
// Claude Code holds typed text as a queued message while its turn is busy,
// and the continue button only shows once the agent stopped checking in, so
// by then the turn is stuck and the queued word would never send by itself.
test("continueKeys types continue and Enter, and under Claude Code also its send-now chord (ctrl+x ctrl+s)", () => {
assert.deepEqual(continueKeys("claude"), ["continue", "\r", "\x18\x13"]);
for (const kind of ["devin", "codex", null, undefined, "something-new"]) {
assert.deepEqual(continueKeys(kind), ["continue", "\r"], `${kind} gets the plain word and Enter`);
}
});
test("app.js types the continue button's keystrokes through continueKeys, for the running agent's kind", () => {
const typeContinue = APP_JS.slice(APP_JS.indexOf("function typeContinue"), APP_JS.indexOf("function typeContinue") + 800);
assert.match(typeContinue, /continueKeys\(agent\.kind\)/, "the keystrokes come from continueKeys");
assert.doesNotMatch(typeContinue, /data: 'continue'/, "no hand-typed word left beside it");
});
test("the bar reads project menu, New Session, agent menu, with both menus outside the scrolling row", () => {
const row = INDEX_HTML.slice(INDEX_HTML.indexOf('<div id="bar-row">'), INDEX_HTML.indexOf('<div id="project-menu"'));
const at = (id) => row.indexOf(`id="${id}"`);
+119
View File
@@ -240,6 +240,48 @@ test("under the app, the not running line's continue is a button that asks the a
assert.ok(await press.isDisabled(), "held off, so a double press does not type it twice");
});
// The app's webview opens no new windows, so a link off the page asks the
// console to open it in the default browser instead, and says where to paste
// it when that fails.
const FEEDBACK_URL = "https://github.com/jparkerweb/plan2code/issues/new/choose";
test("under the app, a link off the page goes to the default browser through the console, not a new window", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
const asked = [];
await s.page.route("**/open-link", async (route) => {
asked.push(route.request().postDataJSON());
await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, url: FEEDBACK_URL }) });
});
let popups = 0;
s.page.context().on("page", () => popups++);
await s.page.locator("#btn-feedback").click();
await until(async () => asked.length === 1, 5000);
assert.deepEqual(asked, [{ url: FEEDBACK_URL }]);
await new Promise((r) => setTimeout(r, 300));
assert.equal(popups, 0, "no window opened inside the app");
});
test("under the app, a link the console cannot open is shown to paste into a browser", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
await s.page.route("**/open-link", (route) => route.fulfill({ status: 500, contentType: "application/json", body: "{}" }));
await s.page.locator("#btn-feedback").click();
await s.page.waitForFunction((u) => document.getElementById("banner").textContent.includes(u), FEEDBACK_URL, { timeout: 5000 });
assert.match(await s.page.locator("#banner").innerText(), /paste it into your browser/i);
});
test("outside the app, a link off the page opens as a plain link, with no detour through the console", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
let asked = 0;
await s.page.route("**/open-link", (route) => {
asked++;
return route.fulfill({ status: 200, contentType: "application/json", body: "{}" });
});
const popup = s.page.context().waitForEvent("page", { timeout: 5000 });
await s.page.locator("#btn-feedback").click();
await (await popup).close();
assert.equal(asked, 0);
});
test("outside the app, the not running line's continue stays a word to type", async (t) => {
const s = await openSession(await suite.browser(), {
t,
@@ -414,6 +456,83 @@ test("the quiet, not running and not connected lines offer What to check, openin
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
});
// An agent sitting in `wait` pings every five seconds and collects a send at
// once, so answers still uncollected after a minute of its silence mean
// nothing is listening: the wake-up help shows then, not after three minutes.
test("answers a waiting agent never collects bring up the saved-and-waiting line after a minute of silence, not before", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", clock: true, payload: PLAN_QUESTION });
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-send");
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
await s.page.clock.fastForward(30_000);
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
await s.page.clock.fastForward(40_000);
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
assert.equal(await whatToCheck(s).count(), 1, "the line carries What to check");
});
// An agent that asked and carried on working collects at its next `wait`, so
// a minute is no proof against it; three minutes of silence is, whatever
// longer quiet allowance it gave itself before it went.
test("answers a working agent has not collected bring up the saved-and-waiting line after three minutes, not its long quiet allowance", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement", clock: true, payload: PLAN_QUESTION });
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-send");
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
// Its last word before it went quiet: working, with half an hour to spare.
s.post({ agent: { status: "working", activity: "Task 1 of 3: the reader", quietMinutes: 30 } });
await lineSays(s, /Task 1 of 3: the reader/);
await s.page.clock.fastForward(70_000);
await lineSays(s, /Task 1 of 3: the reader/);
await s.page.clock.fastForward(130_000);
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
assert.equal(await whatToCheck(s).count(), 1, "the line carries What to check");
});
// A failed Send says why at once, rather than one line for every cause and
// the real state only showing once the page's own timers catch up.
test("a Send that finds the server gone says so at once, with the reconnect help", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await stopServer(s);
await s.page.click("#btn-send");
await s.page.waitForFunction(() => document.getElementById("planny").classList.contains("is-gone"), null, { timeout: 3000 });
assert.match(await s.page.locator("#banner").innerText(), LOST_CONTACT);
assert.match(await textOf(statusLine(s)), /^Not connected\. Your answers are saved\./);
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
});
test("a Send the server refuses shows the server's reason", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.route("**/submit", (route) =>
route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: "the disk is full" }) })
);
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-send");
await s.page.waitForFunction(() => /the disk is full/.test(document.getElementById("banner").textContent), null, { timeout: 3000 });
assert.match(await s.page.locator("#banner").innerText(), /Nothing was lost/);
});
test("a Send the server refuses as too large says to remove an attachment, not to try the same send again", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.route("**/submit", (route) =>
route.fulfill({ status: 413, contentType: "application/json", body: JSON.stringify({ error: "too large" }) })
);
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-send");
await s.page.waitForFunction(() => /remove an attachment/.test(document.getElementById("banner").textContent), null, { timeout: 3000 });
assert.doesNotMatch(await s.page.locator("#banner").innerText(), /try Send again/);
});
test("a Send lost on the way, with the server still up, says the console is there and to send again", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.route("**/submit", (route) => route.abort());
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
await s.page.click("#btn-send");
await s.page.waitForFunction(() => /console is still up/.test(document.getElementById("banner").textContent), null, { timeout: 3000 });
assert.equal(await s.page.locator("#planny").evaluate((n) => n.classList.contains("is-gone")), false, "not called gone");
});
test("an answered finish offer comes back unanswered on a later finish, once the first finish has gone", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
const finishWith = (headline) => s.post({ finish: { headline, command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true } });
+80 -6
View File
@@ -67,7 +67,7 @@ import { renderBriefButton, renderDoc, renderOverview } from "./docs.js";
import { board, renderGitBoard, resetBoard } from "./git-host.js";
import { renderWorkspace, tellFolderIssues } from "./workspace.js";
import { openHelpOn } from "./help-dialog.js";
import { tellApp } from "../app-bridge.js";
import { linkLeavesPage, tellApp } from "../app-bridge.js";
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
import { renderNotepadButton } from "./notepad.js";
@@ -1023,6 +1023,10 @@ let moodNow = null;
let moodVar = 0;
// Sent answers that nothing is collecting (stranded() in selectors.js).
const STRANDED_LINE =
"Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval.";
// The status line's **continue**, under the app: a press asks the app to type
// it into the agent's terminal. Held off for a few seconds after, so a double
// press does not send it twice.
@@ -1145,6 +1149,10 @@ export function renderStatus() {
return say("work", `Starting ${workflowTitle(page.S.workflow)}…`, "", true);
}
// Answers nobody collected outrank a working line: the agent's last word
// was "working", but it is not in `wait` to take them (agentAdrift).
if (stranded()) return say("adrift", STRANDED_LINE, "", false, true);
// Show the AGENT's liveness, not the server's: if the agent's turn crashed
// the server is still happily up, and a plain spinner would lie forever.
if (agentWorking()) {
@@ -1172,9 +1180,7 @@ export function renderStatus() {
if (agentAdrift()) {
return say(
"adrift",
stranded()
? "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval.",
"Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval.",
"",
false,
true
@@ -1789,7 +1795,13 @@ export async function send() {
e.pending = true;
throw e;
}
if (!res.ok) throw new Error(String(res.status));
if (!res.ok) {
const body = await res.json().catch(() => null);
const e = new Error(String(res.status));
e.reason = (body && (body.message || body.error)) || `error ${res.status}`;
e.status = res.status;
throw e;
}
markSent(payload);
banner("Sent. Plan2Code is picking it up now.", "good");
setTimeout(() => banner(null), 4000);
@@ -1801,8 +1813,10 @@ export async function send() {
);
page.pendingBannerUp = true;
page.pendingResult = true;
} else if (err && err.reason) {
banner(refusedLine(err), "warn");
} else {
banner("That did not go through. Nothing was lost, try Send again.", "warn");
await sendLost();
}
} finally {
btn.textContent = "Send to Plan2Code";
@@ -1810,6 +1824,36 @@ export async function send() {
}
}
// A send that never reached an answer: ask the server at once, rather than
// leaving one line for every cause until the page's own timers catch up. No
// server is the lost-contact state now, with its reconnect help; a server
// still there was a blip, and Send is the whole fix.
async function sendLost() {
const up = await fetch("/state", { cache: "no-store" })
.then((res) => res.ok)
.catch(() => false);
if (up) {
banner("That did not go through, but the console is still up. Nothing was lost, press Send again.", "warn");
return;
}
lastContact = 0;
markGone();
// A stream left half open (after the machine slept) still reads as
// connected, so markGone() can leave the page up: the send still needs
// saying it did not go.
if (!page.gone) {
banner("That did not go through. Nothing was lost, try Send again.", "warn");
}
}
// The server said no. A 5xx can pass on a retry; a 4xx is the same refusal
// every time, so it gets no "try again", and the one a person can fix says how.
function refusedLine(err) {
if (err.status === 413) return "That is too big to send in one go. Nothing was lost: remove an attachment, then press Send.";
if (err.status >= 400 && err.status < 500) return `The console turned that send down: ${err.reason}. Nothing was lost.`;
return `The console turned that send down: ${err.reason}. Nothing was lost, try Send again.`;
}
const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", defer: "later" };
// Turn a staged answer into the words the person would have typed in the
@@ -1868,6 +1912,21 @@ let whereResizeTimer = null;
// The listeners that belong to no screen: leaving the page, the session meter's
// pop-over, the footer's label on a resize, Send, Clear, and the page-wide keys.
// A link the console could not hand to a browser is shown, with a Copy
// button, for the person to paste into one.
async function openOutside(href) {
const ok = await fetch("/open-link", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ url: href }),
})
.then((res) => res.ok)
.catch(() => false);
if (ok) return;
const link = el("code", "banner-link", href);
banner("That link could not open from here. Copy it and paste it into your browser: ", "warn", [link, document.createTextNode(" "), copyButton(href, "btn small", link)]);
}
export function wireChrome() {
addEventListener("pagehide", () => {
try {
@@ -1875,6 +1934,21 @@ export function wireChrome() {
} catch {}
});
// Under the app, a link off the page goes to the default browser through
// the console: the app's window opens no new ones, so the click alone would
// do nothing. Capture phase, ahead of any handler on the link itself.
document.addEventListener(
"click",
(e) => {
if (!page.inApp || e.defaultPrevented || !(e.target instanceof Element)) return;
const a = e.target.closest("a[href]");
if (!a || !linkLeavesPage(a.href, location.origin)) return;
e.preventDefault();
openOutside(a.href);
},
true
);
$("meter-pill").addEventListener("click", () => toggleMeterPop());
$("meter-help").addEventListener("click", () => {
toggleMeterPop(false);
+14 -1
View File
@@ -202,7 +202,20 @@ export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page
// itself "working", and the normal state while someone answers is "waiting".
export function agentAdrift() {
if (!page.agentLastSeen || page.gone || finish()) return false;
return Date.now() - Date.parse(page.agentLastSeen) > patience(ADRIFT_MS);
const silent = Date.now() - Date.parse(page.agentLastSeen);
return silent > (page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS));
}
// With answers sent and nothing collecting them, the agent's quiet allowance
// stops counting: those answers are what it is meant to come back for. An
// agent that said it is waiting pings from `wait` every five seconds, so a
// minute of silence means it is not there. One that said it is working (it
// asked and carried on) collects at its next `wait`, so it gets the plain
// three minutes, never the half hour a build task may have asked for.
const UNCOLLECTED_MS = 60 * 1000;
function uncollectedLimit() {
return agentWorking() ? ADRIFT_MS : UNCOLLECTED_MS;
}
// Answers that went nowhere: pressed Send, and nothing has collected them.