Make the console survive locked files and private handles, and start with Activities off

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-05 11:38:59 -08:00
1 parent c52244bee1
commit 2cb174ecf0
17 files changed
+160 -69

No files matched your search

+1 -1
View File
@@ -28,7 +28,7 @@
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class. - **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable. - **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
- **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way. - **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way.
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one. - **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console` (`-<uid>` on Linux and macOS, a 0700 folder with 0600 handles), or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalizes its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows. - **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalizes its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`. - **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together. - **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together.
+7 -6
View File
@@ -550,8 +550,8 @@ Drive has a song for each road, Snake a different one at every level, dealt from
the start of a round so none repeats, and Ghoul Rush a track for each room, played at the start of a round so none repeats, and Ghoul Rush a track for each room, played at
one steady level and fuller in a boss fight), and Light Trails and Flock Dash play five one steady level and fuller in a boss fight), and Light Trails and Flock Dash play five
recorded songs each as background music, each in full, one after another in an recorded songs each as background music, each in full, one after another in an
order shuffled for every run: turn on **Play game music** in **User order shuffled for every run: turn on **Play activity music** in **User
Preferences → Sounds & activities** (it starts off). **Play game sounds** there turns the games' Preferences → Sounds & activities** (it starts off). **Play activity sounds** there turns the games'
sounds (the 3, 2, 1 and the new-best burst included) and their music on or sounds (the 3, 2, 1 and the new-best burst included) and their music on or
off and leaves the page's own cues alone; the **Play sounds** switch above it off and leaves the page's own cues alone; the **Play sounds** switch above it
silences all of it, and a paused or closed game goes quiet at once. A game silences all of it, and a paused or closed game goes quiet at once. A game
@@ -1711,7 +1711,8 @@ When a newer Plan2Code release is out, the dashboard shows an **UPDATE
AVAILABLE** banner at the top. Click it for the details: the version you AVAILABLE** banner at the top. Click it for the details: the version you
have, the new one (linked to its Releases page) and the command that updates have, the new one (linked to its Releases page) and the command that updates
you, `plan2code update`, with a Copy button. It updates everything that was you, `plan2code update`, with a Copy button. It updates everything that was
installed (the skills, the `plan2code` command and any extras you added), with installed (the skills, the `plan2code` command, the app and the status line; the
metrics and bot extras only from a git checkout), with
no menu, and never uninstalls anything. If the `plan2code` command is not no menu, and never uninstalls anything. If the `plan2code` command is not
installed, the dialog also shows the install command, installed, the dialog also shows the install command,
`npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run
@@ -1753,7 +1754,7 @@ The gear button in the top bar opens **User Preferences**, always on its first t
| **System** | Cleanup, and Desktop app (only inside the desktop app) | | **System** | Cleanup, and Desktop app (only inside the desktop app) |
| **Sounds & activities** | Sounds and Activities | | **Sounds & activities** | Sounds and Activities |
On Appearance and Sounds & activities each change saves the moment you make it, and a small **Saved** mark shows beside it. **Close** (or `Esc`) shuts the dialog. **Back to default** resets only the tab on screen: Appearance's four settings (Role back to *Not set*), or every sound and the two Activities switches (Show Activities and Play game sounds); Activities best scores stay. It is not shown on Agents & models or System, which have nothing to reset. On Appearance and Sounds & activities each change saves the moment you make it, and a small **Saved** mark shows beside it. **Close** (or `Esc`) shuts the dialog. **Back to default** resets only the tab on screen: Appearance's four settings (Role back to *Not set*), or every sound and the two Activities switches (Show Activities and Play activity sounds); Activities best scores stay. It is not shown on Agents & models or System, which have nothing to reset.
### Agents & models ### Agents & models
@@ -1789,7 +1790,7 @@ Most people never need this tab: Plan2Code finds the agents installed on the mac
| You closed the tab | Open the link again. Everything is where you left it. After about two minutes with no tab open the link stops working: ask the agent to resume the session for a new one. | | You closed the tab | Open the link again. Everything is where you left it. After about two minutes with no tab open the link stops working: ask the agent to resume the session for a new one. |
| The link stopped working | Tell the agent. It restarts the session and gives you a new link. | | The link stopped working | Tell the agent. It restarts the session and gives you a new link. |
| Your agent session died while you were mid-answer | Press Send anyway. Your answers are written to disk and are never discarded, including when the session is restarted. The next session picks them up. | | Your agent session died while you were mid-answer | Press Send anyway. Your answers are written to disk and are never discarded, including when the session is restarted. The next session picks them up. |
| The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type `continue` in the terminal and it picks your answers up. Answering here still works, and what you send is held for it. | | The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type `continue` in the terminal and it picks your answers up (in the desktop app, the **continue** or **Reconnect to agent** button in the sidebar, beside Send on the Ask tab, and on a saved launch types it for you). Answering here still works, and what you send is held for it. |
| You are not sure anything is connected | The **?** at the top right opens Help. Its *What this page is* tab says what keeps the page alive and whether both halves are talking at that moment, and *When something looks stuck* covers what to check. | | You are not sure anything is connected | The **?** at the top right opens Help. Its *What this page is* tab says what keeps the page alive and whether both halves are talking at that moment, and *When something looks stuck* covers what to check. |
| You would rather use the terminal after all | Say so. Nothing is lost. | | You would rather use the terminal after all | Say so. Nothing is lost. |
@@ -1864,7 +1865,7 @@ exception being the note attachments the agent keeps for a spec, above):
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched | | `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not | | `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them, except a tab you send) | until you delete it through Cleanup, which offers it once its newest file is 30 days old | | `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them, except a tab you send) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width, the Show Activities and Play game sounds switches (`hideActivities`, `activitySounds`), the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` keys: `activityBestSnake`, one per Mini golf course from `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`) and each game's memo (`activityMemo<Id>`: Snake's surprises found, Light Trails' furthest arena, Bug Hunt's bugs, bosses and power-ups found, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run) | always | | `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width, the Show Activities and Play activity sounds switches (`hideActivities`, `activitySounds`), the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` keys: `activityBestSnake`, one per Mini golf course from `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`) and each game's memo (`activityMemo<Id>`: Snake's surprises found, Light Trails' furthest arena, Bug Hunt's bugs, bosses and power-ups found, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run) | always |
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always | | `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session | | `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
| `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents & models), read by the `plan2code` command and the desktop app | always | | `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents & models), read by the `plan2code` command and the desktop app | always |
+4 -4
View File
@@ -1217,7 +1217,7 @@ const COUNT_SOUNDS = () => {
}; };
}; };
test("Play game sounds in User Preferences silences the games and the countdown, Play sounds off grays it out, and Back to default turns it back on", async (t) => { test("Play activity sounds in User Preferences silences the games and the countdown, Play sounds off grays it out, and Back to default turns it back on", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING, init: COUNT_SOUNDS }); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING, init: COUNT_SOUNDS });
const played = () => s.page.evaluate(() => window.__oscillators); const played = () => s.page.evaluate(() => window.__oscillators);
// Starts a fresh round with the 3, 2, 1, which plays a blip, and closes it. // Starts a fresh round with the 3, 2, 1, which plays a blip, and closes it.
@@ -1261,7 +1261,7 @@ test("Play game sounds in User Preferences silences the games and the countdown,
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).activitySounds === true); await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).activitySounds === true);
}); });
test("a game with music has its own Music slider, at its default until moved, kept once moved, and dimmed while Play game music is off", async (t) => { test("a game with music has its own Music slider, at its default until moved, kept once moved, and dimmed while Play activity music is off", async (t) => {
savedLooks(t, { gameMusic: true }); savedLooks(t, { gameMusic: true });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING }); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
const slider = s.page.locator("#activities-music-level"); const slider = s.page.locator("#activities-music-level");
@@ -1285,8 +1285,8 @@ test("a game with music has its own Music slider, at its default until moved, ke
}); });
await openActivities(s, "ghoul"); await openActivities(s, "ghoul");
assert.equal(await boxValue(slider), "80", "kept"); assert.equal(await boxValue(slider), "80", "kept");
assert.equal(await slider.isDisabled(), true, "Play game music off: dimmed"); assert.equal(await slider.isDisabled(), true, "Play activity music off: dimmed");
assert.match(await s.page.locator("#activities-music").getAttribute("title"), /Play game music/, "and says why"); assert.match(await s.page.locator("#activities-music").getAttribute("title"), /Play activity music/, "and says why");
}); });
test("the board is laid out again when the banner appears, so the canvas is never clipped", async (t) => { test("the board is laid out again when the banner appears, so the canvas is never clipped", async (t) => {
+25 -11
View File
@@ -360,7 +360,11 @@ export async function cmdOpen() {
// line, not from the state, and picks the state up on its first request or // line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is // poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there. // on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null; // Looked up under the project the session itself names (as `post` and `wait`
// do), so an agent whose shell moved to another repo finds its server instead
// of starting a second one for the same session.
const sessionProj = state && typeof state.project === "string" && state.project ? state.project : project;
const existing = sid && (args.resume || args.session) ? listHandles(sessionProj).find((h) => h.sid === sid) : null;
// A live pid gets a second, longer look before it is given up on, as `stop` // A live pid gets a second, longer look before it is given up on, as `stop`
// gives one: a server busy right after a post can miss the first, and a // gives one: a server busy right after a post can miss the first, and a
// second server for the same session strands the page on the first. // second server for the same session strands the page on the first.
@@ -369,7 +373,7 @@ export async function cmdOpen() {
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000)) ? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
: Promise.resolve(false); : Promise.resolve(false);
let boot = null; let boot = null;
if (!existing) boot = await startServer(project, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) }); if (!existing) boot = await startServer(sessionProj, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) });
// The dashboard's spec picker reads its inventory straight off the session // The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem // state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -504,14 +508,14 @@ export async function cmdOpen() {
// A handle whose pid is alive but is not ours (the pid was reused) leaves // A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known. // this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, worktree, sid, dir)); let started = boot || (await startServer(sessionProj, worktree, sid, dir));
let handle = await awaitHandle(started); let handle = await awaitHandle(started);
if (!handle && started.handoff) { if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the // The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where // socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain. // the server binds its own port: slower, and certain.
started.kill(); started.kill();
started = await startServer(project, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) }); started = await startServer(sessionProj, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) });
handle = await awaitHandle(started); handle = await awaitHandle(started);
} }
if (!handle) { if (!handle) {
@@ -679,7 +683,7 @@ function isFolder(p) {
async function startServer(project, worktree, sid, dir, { handoff = true, noBrowser = false } = {}) { async function startServer(project, worktree, sid, dir, { handoff = true, noBrowser = false } = {}) {
const token = newToken(); const token = newToken();
const handlePath = handleFile(project, sid); const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath)); ensureDir(path.dirname(handlePath), 0o700);
fs.rmSync(handlePath, { force: true }); fs.rmSync(handlePath, { force: true });
const logFd = fs.openSync(path.join(dir, "server.log"), "a"); const logFd = fs.openSync(path.join(dir, "server.log"), "a");
@@ -778,6 +782,16 @@ function tail(file, lines) {
} }
} }
// A missing browser command raises ENOENT as an event, after the try/catch has
// returned: without a listener it would end `open` before it printed the link.
function quietSpawn(command, args, options) {
// The shell form passes its options in the second place.
const child = Array.isArray(args) ? spawn(command, args, options) : spawn(command, [], args);
child.on("error", () => {});
child.unref();
return child;
}
/** /**
* Best-effort, never fatal. If we cannot open a browser we still printed the URL, * Best-effort, never fatal. If we cannot open a browser we still printed the URL,
* and the URL is the primary channel. * and the URL is the primary channel.
@@ -793,7 +807,7 @@ function openBrowser(url) {
// carries nothing a shell would read. // carries nothing a shell would read.
const custom = process.env.PLAN2CODE_BROWSER; const custom = process.env.PLAN2CODE_BROWSER;
if (custom) { if (custom) {
spawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true }).unref(); quietSpawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true });
return; return;
} }
@@ -801,16 +815,16 @@ function openBrowser(url) {
if (plat === "win32") { if (plat === "win32") {
// The empty "" is the mandatory window-title argument: omit it and // The empty "" is the mandatory window-title argument: omit it and
// `start` treats a quoted URL as the title and opens nothing. // `start` treats a quoted URL as the title and opens nothing.
spawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], { quietSpawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
windowsVerbatimArguments: true, windowsVerbatimArguments: true,
detached: true, detached: true,
stdio: "ignore", stdio: "ignore",
windowsHide: true, windowsHide: true,
}).unref(); });
return; return;
} }
if (plat === "darwin") { if (plat === "darwin") {
spawn("open", [url], { detached: true, stdio: "ignore" }).unref(); quietSpawn("open", [url], { detached: true, stdio: "ignore" });
return; return;
} }
// Linux and friends. WSL first: xdg-open there either is absent or opens a // Linux and friends. WSL first: xdg-open there either is absent or opens a
@@ -818,11 +832,11 @@ function openBrowser(url) {
if (isWsl()) { if (isWsl()) {
const exe = findAgent({ command: "wslview" }).state === "found" ? "wslview" : "powershell.exe"; const exe = findAgent({ command: "wslview" }).state === "found" ? "wslview" : "powershell.exe";
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`]; const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref(); quietSpawn(exe, argsFor, { detached: true, stdio: "ignore" });
return; return;
} }
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless
spawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" }).unref(); quietSpawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" });
} catch { } catch {
/* never fatal */ /* never fatal */
} }
+8 -8
View File
@@ -2,7 +2,7 @@
// //
// Two directories with deliberately different durability: // Two directories with deliberately different durability:
// //
// runtime handle os.tmpdir()/plan2code-console/<cwd-hash>/<sid>.json // runtime handle os.tmpdir()/plan2code-console[-<uid>]/<cwd-hash>/<sid>.json (0700 folder, 0600 file: it holds the session token)
// port, pid, token, url. Losing it on reboot is correct, // port, pid, token, url. Losing it on reboot is correct,
// because the server is gone too. (Jupyter's jpserver-<pid>.json pattern.) // because the server is gone too. (Jupyter's jpserver-<pid>.json pattern.)
// //
@@ -59,7 +59,7 @@ export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// session someone is actually using. // session someone is actually using.
export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME
? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime") ? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime")
: path.join(os.tmpdir(), "plan2code-console"); : path.join(os.tmpdir(), "plan2code-console" + (typeof process.getuid === "function" ? "-" + process.getuid() : ""));
export const SCHEMA = 1; export const SCHEMA = 1;
@@ -81,8 +81,8 @@ export function parseArgs(argv) {
/* ------------------------------------------------------------------- fs */ /* ------------------------------------------------------------------- fs */
export function ensureDir(dir) { export function ensureDir(dir, mode) {
fs.mkdirSync(dir, { recursive: true }); fs.mkdirSync(dir, mode === undefined ? { recursive: true } : { recursive: true, mode });
return dir; return dir;
} }
@@ -91,21 +91,21 @@ export function ensureDir(dir) {
// The retry loop is not paranoia: on Windows, antivirus and the search indexer // The retry loop is not paranoia: on Windows, antivirus and the search indexer
// hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent, // hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent,
// unreproducible on demand, and looks exactly like a logic bug. Retry from day one. // unreproducible on demand, and looks exactly like a logic bug. Retry from day one.
export function writeJsonAtomic(file, data) { export function writeJsonAtomic(file, data, mode) {
const body = JSON.stringify(data, null, 2); const body = JSON.stringify(data, null, 2);
writeTextAtomic(file, body); writeTextAtomic(file, body, mode);
return body; return body;
} }
// The same write for plain text, as UTF-8 (a Buffer is written as is): a temp // The same write for plain text, as UTF-8 (a Buffer is written as is): a temp
// file beside the target, fsync, then a rename, retried while Windows still // file beside the target, fsync, then a rename, retried while Windows still
// holds the old file. // holds the old file.
export function writeTextAtomic(file, text) { export function writeTextAtomic(file, text, mode) {
const tmp = file + "." + process.pid + ".tmp"; const tmp = file + "." + process.pid + ".tmp";
let lastErr; let lastErr;
for (let attempt = 0; attempt < 4; attempt++) { for (let attempt = 0; attempt < 4; attempt++) {
try { try {
const fd = fs.openSync(tmp, "w"); const fd = mode === undefined ? fs.openSync(tmp, "w") : fs.openSync(tmp, "w", mode);
try { try {
fs.writeFileSync(fd, text, "utf8"); fs.writeFileSync(fd, text, "utf8");
fs.fsyncSync(fd); fs.fsyncSync(fd);
+16 -1
View File
@@ -130,7 +130,22 @@ export function markHandoffUsed(id, now = clock()) {
const file = path.join(handoffsDir(), id + ".json"); const file = path.join(handoffsDir(), id + ".json");
const tmp = `${file}.${process.pid}.tmp`; const tmp = `${file}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n"); fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n");
fs.renameSync(tmp, file); // Windows scanners hold transient locks: retry the rename, and never leave the temp file.
for (let attempt = 0; ; attempt++) {
try {
fs.renameSync(tmp, file);
break;
} catch (err) {
const transient = err.code === "EPERM" || err.code === "EBUSY" || err.code === "EACCES";
if (!transient || attempt >= 3) {
try {
fs.rmSync(tmp, { force: true });
} catch {}
throw err;
}
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 40 * (attempt + 1));
}
}
return next; return next;
} }
+18
View File
@@ -262,6 +262,24 @@ function recoverIndex(dir) {
function prepare(dir, folder) { function prepare(dir, folder) {
migrate(dir, folder); migrate(dir, folder);
let index = readIndex(dir); let index = readIndex(dir);
if (!index && fs.existsSync(path.join(dir, INDEX_FILE))) {
// A scanner's brief lock reads as "damaged" through readJson: wait it out, and
// refuse the write (rather than rebuild every tab) while the file stays locked.
let lastErr = null;
for (let attempt = 0; attempt < 4 && !index; attempt++) {
try {
fs.readFileSync(path.join(dir, INDEX_FILE));
lastErr = null;
index = readIndex(dir);
break;
} catch (err) {
lastErr = err;
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
sleepSync(40 * (attempt + 1));
}
}
if (!index && lastErr && (lastErr.code === "EPERM" || lastErr.code === "EBUSY" || lastErr.code === "EACCES")) throw lastErr;
}
if (!index) { if (!index) {
index = fs.existsSync(path.join(dir, INDEX_FILE)) ? recoverIndex(dir) : { order: [], last: null, tabs: {} }; index = fs.existsSync(path.join(dir, INDEX_FILE)) ? recoverIndex(dir) : { order: [], last: null, tabs: {} };
writeIndex(dir, index); writeIndex(dir, index);
+11 -11
View File
@@ -3099,12 +3099,12 @@
scores</strong>, at the bottom of the window, clears them all after a scores</strong>, at the bottom of the window, clears them all after a
second click to confirm. second click to confirm.
</p> </p>
<h4>Hiding it</h4> <h4>Showing and hiding it</h4>
<p> <p>
Don't want the die? Untick <strong>Show Activities</strong> in User The die is off until you tick <strong>Show Activities</strong> in User
Preferences (the gear) and it is gone from every screen. To play Preferences (the gear); untick it again and it is gone from every screen. To play
without sound, untick <strong>Play game sounds</strong> beside it. without sound, untick <strong>Play activity sounds</strong> beside it.
A game with music (turn on <strong>Play game music</strong> there) has A game with music (turn on <strong>Play activity music</strong> there) has
its own <strong>Music</strong> slider under the board for how loud it plays. its own <strong>Music</strong> slider under the board for how loud it plays.
</p> </p>
<p> <p>
@@ -3409,8 +3409,8 @@
<li> <li>
<strong>Activities</strong>: <strong>Show Activities</strong> puts <strong>Activities</strong>: <strong>Show Activities</strong> puts
the die in the top bar, which opens small games to play while you the die in the top bar, which opens small games to play while you
wait. Untick it to hide the die on every screen. wait. It starts unticked; untick it again to hide the die on every screen.
<strong>Play game sounds</strong> turns the games' sounds on or <strong>Play activity sounds</strong> turns the games' sounds on or
off, leaving every other sound as it is; with Play sounds off, the off, leaving every other sound as it is; with Play sounds off, the
games are silent too. games are silent too.
</li> </li>
@@ -3679,10 +3679,10 @@
</fieldset> </fieldset>
<fieldset data-section="activities" class="modal-ranges looks-activities"> <fieldset data-section="activities" class="modal-ranges looks-activities">
<legend>Activities</legend> <legend>Activities</legend>
<label><input type="checkbox" id="looks-activities" checked /> <span>Show Activities</span></label> <label><input type="checkbox" id="looks-activities" /> <span>Show Activities</span></label>
<label><input type="checkbox" id="looks-activity-sounds" checked /> <span>Play game sounds</span></label> <label><input type="checkbox" id="looks-activity-sounds" checked /> <span>Play activity sounds</span></label>
<label><input type="checkbox" id="looks-game-music" /> <span>Play game music</span></label> <label><input type="checkbox" id="looks-game-music" /> <span>Play activity music</span></label>
<p class="help">The die in the top bar opens small games to play while you wait. Play game sounds turns the games' sounds on or off, and Play game music their music; Play sounds, above, silences them too.</p> <p class="help">The die in the top bar opens small games to play while you wait. Play activity sounds turns the games' sounds on or off, and Play activity music their music; Play sounds, above, silences them too.</p>
</fieldset> </fieldset>
</section> </section>
</div> </div>
+2 -2
View File
@@ -31,11 +31,11 @@ export const DEFAULT_LOOKS = {
...soundPrefs(null), ...soundPrefs(null),
width: DEFAULT_CARD_WIDTH, width: DEFAULT_CARD_WIDTH,
hideUnavailable: true, hideUnavailable: true,
// Activities: the top bar's die, whether its games play sounds (under Play // Activities: the top bar's die (hidden until someone turns on Show Activities), whether its games play sounds (under Play
// sounds, which silences them too), the game last picked, and one best score // sounds, which silences them too), the game last picked, and one best score
// per listed game (activityBestSnake) or, for a game with courses, per // per listed game (activityBestSnake) or, for a game with courses, per
// course (activityBestGolfPirate), each a flat key for cleanLooks(). // course (activityBestGolfPirate), each a flat key for cleanLooks().
hideActivities: false, hideActivities: true,
activitySounds: true, activitySounds: true,
// Whether a game plays its music too (chiptune or recorded songs): off until asked for. // Whether a game plays its music too (chiptune or recorded songs): off until asked for.
gameMusic: false, gameMusic: false,
+3 -3
View File
@@ -22,7 +22,7 @@ import { hushMusic, music as playMusic } from "../music.js";
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
// Every sound the window and its games make goes through these two, so // Every sound the window and its games make goes through these two, so
// Preferences' Play game sounds silences them all (and Play sounds, which // Preferences' Play activity sounds silences them all (and Play sounds, which
// tones.js checks, does too). // tones.js checks, does too).
const tone = (...args) => { const tone = (...args) => {
if (looks.activitySounds) playTone(...args); if (looks.activitySounds) playTone(...args);
@@ -30,7 +30,7 @@ const tone = (...args) => {
const hum = (...args) => { const hum = (...args) => {
if (looks.activitySounds) playHum(...args); if (looks.activitySounds) playHum(...args);
}; };
// And the music, which also needs Play game music, at the game's own // And the music, which also needs Play activity music, at the game's own
// music volume (the window's Music slider). A song's "playing" or "ended" // music volume (the window's Music slider). A song's "playing" or "ended"
// goes back to the game, which moves on to its next song on "ended". // goes back to the game, which moves on to its next song on "ended".
const musicFor = (entry) => (name, intensity, options) => { const musicFor = (entry) => (name, intensity, options) => {
@@ -38,7 +38,7 @@ const musicFor = (entry) => (name, intensity, options) => {
return undefined; return undefined;
}; };
const MUSIC_TITLE = "This game's music volume"; const MUSIC_TITLE = "This game's music volume";
const MUSIC_OFF_TITLE = "Turn on Play game music in User Preferences to hear it"; const MUSIC_OFF_TITLE = "Turn on Play activity music in User Preferences to hear it";
// Quiets every held sound and the music: the window stopped ticking a game. // Quiets every held sound and the music: the window stopped ticking a game.
function hushTones() { function hushTones() {
+6 -1
View File
@@ -391,7 +391,12 @@ export function renderCard(item) {
const skip = el("button", "btn tiny", skipped ? "Do not skip" : "Skip this one"); const skip = el("button", "btn tiny", skipped ? "Do not skip" : "Skip this one");
skip.type = "button"; skip.type = "button";
skip.style.marginTop = "16px"; skip.style.marginTop = "16px";
skip.addEventListener("click", () => (skipped ? stage(item.id, null) : skipAndMoveOn(item.id))); skip.addEventListener("click", () => {
if (!skipped) return skipAndMoveOn(item.id);
// Keep a note typed with the skip: the box still shows it, so the send must carry it.
const kept = page.local.staged[item.id];
stage(item.id, kept && kept.text ? { type: "answer", kind: item.kind, text: kept.text } : null);
});
card.appendChild(skip); card.appendChild(skip);
if (page.local.skipFlash === item.id) { if (page.local.skipFlash === item.id) {
card.classList.add("is-skip-flash"); card.classList.add("is-skip-flash");
+3 -3
View File
@@ -625,7 +625,7 @@ async function copyHandoffText(text, id, label) {
// CLI reads the stored skill and spec, marks the handoff used and falls back // CLI reads the stored skill and spec, marks the handoff used and falls back
// to Quick Task if either is gone. // to Quick Task if either is gone.
async function pickUpHandoff(h) { async function pickUpHandoff(h) {
if (page.gone || page.pendingResult || page.local.launching || finish()) return; if (page.gone || page.pendingResult || page.local.launching || page.launchScoping || finish()) return;
page.launchScoping = true; page.launchScoping = true;
await hooks.syncWorkspaceScope(h.spec || ""); await hooks.syncWorkspaceScope(h.spec || "");
try { try {
@@ -1091,7 +1091,7 @@ export function renderConfirm(main, entry) {
// marks the action as being about the session, and it reaches the agent // marks the action as being about the session, and it reaches the agent
// through the same wait loop. The dashboard reads `skill` off it. // through the same wait loop. The dashboard reads `skill` off it.
export async function launchSkill(entry) { export async function launchSkill(entry) {
if (page.gone || page.pendingResult || page.local.launching || finish()) return; if (page.gone || page.pendingResult || page.local.launching || page.launchScoping || finish()) return;
const target = launchTarget(entry, selSpec()); const target = launchTarget(entry, selSpec());
// The card was clickable, so this should never fire — but a spec picked in // The card was clickable, so this should never fire — but a spec picked in
// one tab could have shifted the ground under a stale render in another. // one tab could have shifted the ground under a stale render in another.
@@ -1351,7 +1351,7 @@ export function wireDashboard() {
$("delete-name").addEventListener("keydown", (e) => { $("delete-name").addEventListener("keydown", (e) => {
if (e.key === "Enter") { if (e.key === "Enter") {
e.preventDefault(); e.preventDefault();
deleteStep(); if (!$("delete-go").disabled) deleteStep();
} }
}); });
// `close` is queued, so it can land after the dialog was opened again for // `close` is queued, so it can land after the dialog was opened again for
+1 -1
View File
@@ -899,7 +899,7 @@ export function renderStopping() {
extra.replaceChildren(); extra.replaceChildren();
if (stuck) { if (stuck) {
extra.appendChild( extra.appendChild(
el( textWithCode(
"p", "p",
"stop-note", "stop-note",
page.inApp page.inApp
+2 -1
View File
@@ -101,7 +101,8 @@ function posePane(main, cls, workflow) {
const pane = el("div", cls); const pane = el("div", cls);
pane.dataset.pose = pose; pane.dataset.pose = pose;
pane.appendChild(startStage(workflow)); pane.appendChild(startStage(workflow));
if (held) main.insertBefore(pane, held); // The old pane (another pose) is replaced, not left beside the new one.
if (held && held.parentNode === main) held.replaceWith(pane);
else main.appendChild(pane); else main.appendChild(pane);
return pane; return pane;
} }
+27 -11
View File
@@ -132,6 +132,14 @@ const ROUTES = [
{ path: "/bye", origin: true, run: bye }, { path: "/bye", origin: true, run: bye },
]; ];
// events.ndjson is an advisory log: a transient lock or a full disk must not
// take a route (or the detached server) down after the real write landed.
function noteEvent(dir, event) {
try {
appendEvent(dir, event);
} catch {}
}
export function handle(req, res, ctx) { export function handle(req, res, ctx) {
const port = ctx.port(); const port = ctx.port();
const url = new URL(req.url, `http://127.0.0.1:${port}`); const url = new URL(req.url, `http://127.0.0.1:${port}`);
@@ -149,7 +157,15 @@ export function handle(req, res, ctx) {
if (route.path !== undefined ? pathname !== route.path : !route.match(pathname, req)) continue; if (route.path !== undefined ? pathname !== route.path : !route.match(pathname, req)) continue;
if (route.method && req.method !== route.method) continue; if (route.method && req.method !== route.method) continue;
if (route.origin && !originOk(req, port)) return json(res, 403, { error: "bad origin" }); if (route.origin && !originOk(req, port)) return json(res, 403, { error: "bad origin" });
return route.run(req, res, ctx, url); try {
return route.run(req, res, ctx, url);
} catch (e) {
if (!res.headersSent) return json(res, 500, { error: "server error" });
try {
res.end();
} catch {}
return undefined;
}
} }
return json(res, 404, { error: "not found" }); return json(res, 404, { error: "not found" });
} }
@@ -540,7 +556,7 @@ function subagentsPost(req, res, ctx) {
} }
if (unchanged) return json(res, 200, { ok: true, setting: current }); if (unchanged) return json(res, 200, { ok: true, setting: current });
const setting = readSubagentSetting(ctx.dir); const setting = readSubagentSetting(ctx.dir);
appendEvent(ctx.dir, { type: "subagents", on, revision: setting.revision }); noteEvent(ctx.dir, { type: "subagents", on, revision: setting.revision });
ctx.pushState(); ctx.pushState();
return json(res, 200, { ok: true, setting }); return json(res, 200, { ok: true, setting });
}); });
@@ -567,7 +583,7 @@ function prHost(req, res, ctx) {
} catch (e) { } catch (e) {
return json(res, 500, { error: String(e.message) }); return json(res, 500, { error: String(e.message) });
} }
appendEvent(ctx.dir, { type: "pr-host", host, kind }); noteEvent(ctx.dir, { type: "pr-host", host, kind });
return json(res, 200, { ok: true }); return json(res, 200, { ok: true });
}); });
} }
@@ -1184,7 +1200,7 @@ function upload(req, res, ctx) {
const saved = store(buf, "jpg"); const saved = store(buf, "jpg");
if (!saved) return; if (!saved) return;
const { id, file } = saved; const { id, file } = saved;
appendEvent(ctx.dir, { type: "upload", id, kind: "image", bytes: buf.length }); noteEvent(ctx.dir, { type: "upload", id, kind: "image", bytes: buf.length });
return json(res, 200, { return json(res, 200, {
ok: true, ok: true,
id, id,
@@ -1213,7 +1229,7 @@ function upload(req, res, ctx) {
const saved = store(buf, ext); const saved = store(buf, ext);
if (!saved) return; if (!saved) return;
const { id, file } = saved; const { id, file } = saved;
appendEvent(ctx.dir, { type: "upload", id, kind: "file", bytes: buf.length }); noteEvent(ctx.dir, { type: "upload", id, kind: "file", bytes: buf.length });
return json(res, 200, { ok: true, id, kind: "file", path: file, name, size: buf.length }); return json(res, 200, { ok: true, id, kind: "file", path: file, name, size: buf.length });
}); });
} }
@@ -1301,7 +1317,7 @@ function uploads(req, res, ctx, url) {
} catch (e) { } catch (e) {
return json(res, 500, { error: String(e.message) }); return json(res, 500, { error: String(e.message) });
} }
appendEvent(ctx.dir, { type: "upload-delete", id: m[1] }); noteEvent(ctx.dir, { type: "upload-delete", id: m[1] });
res.writeHead(204, baseHeaders()); res.writeHead(204, baseHeaders());
return res.end(); return res.end();
} }
@@ -1437,7 +1453,7 @@ function submit(req, res, ctx) {
}); });
} }
if (refused) return json(res, 500, { error: refused }); if (refused) return json(res, 500, { error: refused });
appendEvent(ctx.dir, { type: "submit", rev: ctx.rev, count: body.actions.length }); noteEvent(ctx.dir, { type: "submit", rev: ctx.rev, count: body.actions.length });
if (written) { if (written) {
// Account for our own write here rather than letting the watcher find // Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is // it: the watcher reads a changed state.json as proof the AGENT is
@@ -1489,7 +1505,7 @@ function chat(req, res, ctx) {
workflow: state.workflow, workflow: state.workflow,
reason: "button", reason: "button",
}); });
appendEvent(ctx.dir, { type: "chat-reset", reason: "button" }); noteEvent(ctx.dir, { type: "chat-reset", reason: "button" });
ctx.rev++; ctx.rev++;
ctx.pushState(); ctx.pushState();
return json(res, 200, { ok: true, seq: entry.seq, conversation: entry.conversation }); return json(res, 200, { ok: true, seq: entry.seq, conversation: entry.conversation });
@@ -1527,7 +1543,7 @@ function chat(req, res, ctx) {
: undefined, : undefined,
files: body.files ? body.files.map((f) => ({ path: f.path, name: cleanLabel(f.name, "file") })) : undefined, files: body.files ? body.files.map((f) => ({ path: f.path, name: cleanLabel(f.name, "file") })) : undefined,
}); });
appendEvent(ctx.dir, { type: "chat", seq: entry.seq }); noteEvent(ctx.dir, { type: "chat", seq: entry.seq });
ctx.rev++; ctx.rev++;
ctx.pushState(); ctx.pushState();
return json(res, 200, { ok: true, seq: entry.seq, conversation: current }); return json(res, 200, { ok: true, seq: entry.seq, conversation: current });
@@ -1564,7 +1580,7 @@ function chatDecision(req, res, ctx) {
decision: body.decision, decision: body.decision,
text: text || undefined, text: text || undefined,
}); });
appendEvent(ctx.dir, { type: "chat-decision", decision: body.decision }); noteEvent(ctx.dir, { type: "chat-decision", decision: body.decision });
ctx.rev++; ctx.rev++;
ctx.pushState(); ctx.pushState();
return json(res, 200, { ok: true, seq: entry.seq }); return json(res, 200, { ok: true, seq: entry.seq });
@@ -1734,7 +1750,7 @@ function cancel(req, res, ctx) {
return json(res, 500, { error: String(e.message) }); return json(res, 500, { error: String(e.message) });
} }
if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." }); if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." });
appendEvent(ctx.dir, { type: "cancel", rev: ctx.rev }); noteEvent(ctx.dir, { type: "cancel", rev: ctx.rev });
ctx.broadcast("cancelled", { rev: ctx.rev }); ctx.broadcast("cancelled", { rev: ctx.rev });
return json(res, 200, { ok: true }); return json(res, 200, { ok: true });
} }
+18 -4
View File
@@ -529,11 +529,16 @@ setInterval(() => {
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS): // Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
// exiting would strand the tab and the send it holds. // exiting would strand the tab and the send it holds.
if (idle > IDLE_MS && !resultFlags().pending) { if (idle > IDLE_MS && !resultFlags().pending) {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle }); // The log is advisory: a failed append must never keep an orphan server alive.
try {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
} catch {}
process.exit(0); process.exit(0);
} }
if (Date.now() - STARTED > MAX_LIFE_MS) { if (Date.now() - STARTED > MAX_LIFE_MS) {
appendEvent(DIR, { type: "exit", reason: "max-life" }); try {
appendEvent(DIR, { type: "exit", reason: "max-life" });
} catch {}
process.exit(0); process.exit(0);
} }
}, 20000).unref(); }, 20000).unref();
@@ -544,6 +549,14 @@ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
} catch {} } catch {}
} }
// A throw inside a request callback (a read or write failing on a locked file)
// must not end the detached server: note it and carry on. The page retries.
process.on("uncaughtException", (e) => {
try {
appendEvent(DIR, { type: "error", message: String(e?.message || e).slice(0, 200) });
} catch {}
});
// Every exit that gets to run code takes its handle file with it, so a pid // Every exit that gets to run code takes its handle file with it, so a pid
// left behind in the runtime dir cannot later be mistaken for this server once // left behind in the runtime dir cannot later be mistaken for this server once
// the number is reused. Only while the file still names THIS process: a // the number is reused. Only while the file still names THIS process: a
@@ -602,8 +615,9 @@ function onListening(port) {
stateDir: DIR, stateDir: DIR,
startedAt: nowIso(), startedAt: nowIso(),
}; };
ensureDir(path.dirname(handleFile(PROJECT, SID))); // The handle holds the session token: private to this user on a shared /tmp.
writeJsonAtomic(handleFile(PROJECT, SID), handle); ensureDir(path.dirname(handleFile(PROJECT, SID)), 0o700);
writeJsonAtomic(handleFile(PROJECT, SID), handle, 0o600);
appendEvent(DIR, { type: "listening", port, pid: process.pid }); appendEvent(DIR, { type: "listening", port, pid: process.pid });
checkState(); checkState();
// A resume through a fresh server still starts a new conversation on a hop. // A resume through a fresh server still starts a new conversation on a hop.
+8 -1
View File
@@ -231,7 +231,14 @@ export function serverWorkspace(ctx) {
} }
function saveWorkspace(ws) { function saveWorkspace(ws) {
writeWorkspace(dir, ws); try {
writeWorkspace(dir, ws);
} catch (e) {
// The caller changed the cached object before saving: drop it, so the next
// read starts from what is on disk and a retry is not told "duplicate".
workspaceSeen = { stamp: null, ws: null };
throw e;
}
workspaceSeen = { stamp: fileStamp(WORKSPACE_PATH), ws }; workspaceSeen = { stamp: fileStamp(WORKSPACE_PATH), ws };
} }