diff --git a/.agents-docs/AGENTS-architecture-console-design.md b/.agents-docs/AGENTS-architecture-console-design.md index 6cc851c..9453b15 100644 --- a/.agents-docs/AGENTS-architecture-console-design.md +++ b/.agents-docs/AGENTS-architecture-console-design.md @@ -66,6 +66,6 @@ Key design points: - **Starting ticks are staged by the page, never answered by the server.** A `multi` row with `ticked: true` is seeded into the person's staged answer once (`seedStaged`, marked in `page.local.seeded`); an `answer` on the item would settle the card before anyone saw it, and a staged answer already flows through Send, drafts, the settled record and the reply words. - **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used. -Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill. +Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-shape`, `-git`, `-git-board`, `-qa`, `-speed`, `-hardening`, `-embed`, `-relative-urls`, `-handoffs`, `-in-app`, `-loop`, `-notepad`, `-pointers`, `-skills`, `-spec-states`, `-state`, `-tones`), plus the `-page-*` browser suites and the per-game `-activities*` suites. Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill. **Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in [the console file](./AGENTS-architecture-console.md), a `public/` file in [the page file](./AGENTS-architecture-console-page.md), a game file in [Activities](./AGENTS-architecture-activities.md) or the Ghoul Rush files), which the docs-table test (same file) checks. diff --git a/package.json b/package.json index 4b273c8..ed3e5ed 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,7 @@ "pretest": "node scripts/fix-line-endings.mjs", "test:fast": "node scripts/test-fast.mjs", "test:page": "node scripts/run-page-tests.mjs", - "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs", + "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-agent-lookup.mjs scripts/test-agents-file.mjs scripts/test-app-meter.mjs scripts/test-browser-helper.mjs scripts/test-check-console-openings.mjs scripts/test-check-doc-size.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-test-lanes.mjs scripts/test-check-versions.mjs scripts/test-console-stub.mjs scripts/test-console-wire-budgets.mjs scripts/test-getting-started.mjs scripts/test-git-repo.mjs scripts/test-install-bench.mjs scripts/test-install-e2e.mjs scripts/test-install-refs.mjs scripts/test-install-update.mjs scripts/test-launcher.mjs scripts/test-line-endings.mjs scripts/test-publish-install-refs.mjs scripts/test-script-changelog.mjs scripts/test-script-changes.mjs scripts/test-script-coverage.mjs scripts/test-script-dead-code.mjs scripts/test-script-deps.mjs scripts/test-script-finalize.mjs scripts/test-script-git.mjs scripts/test-script-lessons.mjs scripts/test-script-pathfinder.mjs scripts/test-script-pr-prep.mjs scripts/test-script-run-check.mjs scripts/test-script-test-commands.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-xray.mjs scripts/test-set-version.mjs scripts/test-skill-scripts.mjs scripts/test-skill-test-runs.mjs scripts/test-spec-carry-page.mjs scripts/test-spec-carry.mjs scripts/test-standalone-check.mjs scripts/test-ui-prototype-page.mjs scripts/test-us-english.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-card-rows.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-diff-parse.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-git.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-learning.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-notepad.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-changes.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-layout.mjs scripts/test-web-console-page-learning.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-review-loop.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-setup.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-pointers.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-relative-urls.mjs scripts/test-web-console-review-loop.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-shape.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-source.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-workspace.mjs", "test:games": "node scripts/node-test.mjs scripts/test-web-console-activities-bounce-arcade.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-page-activities.mjs" }, "devDependencies": { diff --git a/scripts/test-lanes.json b/scripts/test-lanes.json index c3fded2..6efba4c 100644 --- a/scripts/test-lanes.json +++ b/scripts/test-lanes.json @@ -43,6 +43,7 @@ "test-web-console-diff-parse.mjs", "test-web-console-git-board.mjs", "test-web-console-prototypes.mjs", + "test-web-console-relative-urls.mjs", "test-web-console-send-state.mjs", "test-web-console-shape.mjs", "test-web-console-skills.mjs", diff --git a/scripts/test-spec-carry-page.mjs b/scripts/test-spec-carry-page.mjs index aa1796a..e726cfa 100644 --- a/scripts/test-spec-carry-page.mjs +++ b/scripts/test-spec-carry-page.mjs @@ -52,6 +52,6 @@ test("it asks once per page", async () => { await load(); await load(); assert.equal(calls.length, 1); - assert.deepEqual(calls[0], ["/spec-carry", "POST"]); + assert.deepEqual(calls[0], ["spec-carry", "POST"]); assert.equal(typeof loadSpecCarry, "function"); }); diff --git a/scripts/test-web-console-activities.mjs b/scripts/test-web-console-activities.mjs index a87766d..9bb767b 100644 --- a/scripts/test-web-console-activities.mjs +++ b/scripts/test-web-console-activities.mjs @@ -280,7 +280,7 @@ test("the list names Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Sta assert.equal(ACTIVITIES[12].title, "Flock Dash"); for (const a of ACTIVITIES) { assert.ok(Object.isFrozen(a), `${a.id} is frozen`); - assert.equal(a.module, a.id === "ghoul" ? "/activities/ghoul-rush/ghoul.js" : `/activities/${a.id}.js`); + assert.equal(a.module, a.id === "ghoul" ? "activities/ghoul-rush/ghoul.js" : `activities/${a.id}.js`); assert.equal(typeof a.title, "string"); assert.ok(typeof a.blurb === "string" && a.blurb.length > 10, `${a.id} has a line for its picker card`); } diff --git a/scripts/test-web-console-embed.mjs b/scripts/test-web-console-embed.mjs index 06c3c1f..fd21e7c 100644 --- a/scripts/test-web-console-embed.mjs +++ b/scripts/test-web-console-embed.mjs @@ -121,6 +121,6 @@ test("the page-closed signal is a keepalive fetch, which carries the page's orig const core = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "core.js"), "utf8"); const wire = core.slice(core.indexOf("export function wireChrome()")); const pagehide = wire.slice(0, wire.indexOf("});")); - assert.match(pagehide, /fetch\("\/bye", \{ method: "POST", keepalive: true \}\)/, pagehide); + assert.match(pagehide, /fetch\("bye", \{ method: "POST", keepalive: true \}\)/, pagehide); assert.doesNotMatch(core, /navigator\.sendBeacon\(/, "no beacon call left anywhere in the page's core"); }); diff --git a/scripts/test-web-console-git.mjs b/scripts/test-web-console-git.mjs index 23019af..c39a6cf 100644 --- a/scripts/test-web-console-git.mjs +++ b/scripts/test-web-console-git.mjs @@ -589,7 +589,7 @@ test("git board: the page draws it from git-board.js, with no inline styles", () const dir = path.join(path.dirname(CONSOLE_CLI), "public"); const html = fs.readFileSync(path.join(dir, "index.html"), "utf8"); const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8"); - for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`); + for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`); const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8"); assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/); assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener"); diff --git a/scripts/test-web-console-logic.mjs b/scripts/test-web-console-logic.mjs index 7f4f949..178618a 100644 --- a/scripts/test-web-console-logic.mjs +++ b/scripts/test-web-console-logic.mjs @@ -2297,7 +2297,7 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi assert.ok(pill, "the pill sits in .ident"); assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"')); for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) { - assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`); + assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`); } // The CSP refuses style attributes and inline script: the new markup has neither. const added = [ diff --git a/scripts/test-web-console-notepad.mjs b/scripts/test-web-console-notepad.mjs index cb08552..549c261 100644 --- a/scripts/test-web-console-notepad.mjs +++ b/scripts/test-web-console-notepad.mjs @@ -144,14 +144,14 @@ test("pictures: JPEG only, listed oldest first, with thumbnails when sent", () = const first = addImage(folder, tab, JPEG); const second = addImage(folder, tab, JPEG); assert.match(first.id, IMAGE_ID_RE); - assert.equal(first.url, `/notepad/images/${tab}/${first.id}.jpg`); + assert.equal(first.url, `notepad/images/${tab}/${first.id}.jpg`); // Make the order unambiguous: the first is older. const older = new Date(Date.now() - 60_000); fs.utimesSync(path.join(tabDir(folder, tab), "images", first.id + ".jpg"), older, older); addThumb(folder, tab, second.id, JPEG); assert.deepEqual(readNotepad(folder).images, [ { id: first.id, url: first.url, thumb: null }, - { id: second.id, url: second.url, thumb: `/notepad/images/${tab}/${second.id}.thumb.jpg` }, + { id: second.id, url: second.url, thumb: `notepad/images/${tab}/${second.id}.thumb.jpg` }, ]); }); @@ -509,8 +509,8 @@ test("the first shape reads as one Notes tab, and the read writes nothing", () = [U1, U2], "oldest first", ); - assert.equal(read.images[0].url, `/notepad/images/${LEGACY_TAB_ID}/${U1}.jpg`); - assert.equal(read.images[0].thumb, `/notepad/images/${LEGACY_TAB_ID}/${U1}.thumb.jpg`); + assert.equal(read.images[0].url, `notepad/images/${LEGACY_TAB_ID}/${U1}.jpg`); + assert.equal(read.images[0].thumb, `notepad/images/${LEGACY_TAB_ID}/${U1}.thumb.jpg`); assert.equal(read.images[1].thumb, null); assert.deepEqual(listTabs(folder), { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID }); assert.equal(readNotepad(folder, LEGACY_TAB_ID).text, "old note\n"); @@ -564,7 +564,7 @@ test("any first write migrates: a picture, a new tab, and an old picture can be const f2 = freshFolder("legacy"); legacyNotepad(f2); const added = addImage(f2, LEGACY_TAB_ID, JPEG); - assert.equal(added.url, `/notepad/images/${LEGACY_TAB_ID}/${added.id}.jpg`); + assert.equal(added.url, `notepad/images/${LEGACY_TAB_ID}/${added.id}.jpg`); assert.equal(readNotepad(f2).images.length, 3); // A first-shape notepad with a picture and no note still migrates. const f3 = freshFolder("legacy"); @@ -718,7 +718,10 @@ test("pictures through the routes: upload, thumb, fetch, delete and every refusa const up = await postJpeg(s, "/notepad/image", JPEG); assert.equal(up.status, 200); - const { id, url } = await up.json(); + const { id, url: link } = await up.json(); + assert.doesNotMatch(link, /^\//, "page-relative"); + // The page at / asks for it here. + const url = `/${link}`; assert.match(id, IMAGE_ID_RE); const unknownThumb = await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG); @@ -853,7 +856,7 @@ test("GET /notepad answers a notepad still in the first shape as a Notes tab, an assert.equal(res.body.text, "old note\n"); assert.equal(res.body.images.length, 2); assert.deepEqual(treeOf(dir), before, "the read wrote nothing"); - const img = await fetch(`${s.base}${res.body.images[0].url}`, { headers: { cookie: s.cookie, connection: "close" } }); + const img = await fetch(`${s.base}/${res.body.images[0].url}`, { headers: { cookie: s.cookie, connection: "close" } }); assert.equal(img.status, 200, "the picture is served from where it still is"); // The unchanged page's save, with no tab named, lands in Notes and migrates. assert.equal((await s.send("/notepad/text", { text: "page save" })).status, 200); @@ -1004,16 +1007,18 @@ test("pictures through ?tab=: upload, thumb, fetch and delete, each under the ta const up = await postJpeg(s, `/notepad/image?tab=${a}`, JPEG); assert.equal(up.status, 200); const { id, url } = await up.json(); - assert.equal(url, `/notepad/images/${a}/${id}.jpg`); + assert.equal(url, `notepad/images/${a}/${id}.jpg`); + // Page-relative: the page at / asks for it here. + const served = `/${url}`; assert.equal((await postJpeg(s, `/notepad/thumb?tab=${a}&id=${id}`, JPEG)).status, 200); - assert.equal((await get(url)).status, 200); + assert.equal((await get(served)).status, 200); assert.equal((await get(`/notepad/images/${a}/${id}.thumb.jpg`)).status, 200); // Not under another tab, not in the old shape, not under a tab that is not there. assert.equal((await get(`/notepad/images/${b}/${id}.jpg`)).status, 404); assert.equal((await get(`/notepad/images/${id}.jpg`)).status, 404); assert.equal((await get(`/notepad/images/ffffffffffff/${id}.jpg`)).status, 404); assert.deepEqual((await getJson(s, `/notepad?tab=${b}`)).body.images, []); - assert.equal((await getJson(s, `/notepad?tab=${a}`)).body.images[0].thumb, `/notepad/images/${a}/${id}.thumb.jpg`); + assert.equal((await getJson(s, `/notepad?tab=${a}`)).body.images[0].thumb, `notepad/images/${a}/${id}.thumb.jpg`); // A picture or thumb for a tab that is not there, and a delete from the wrong tab. const stray = await postJpeg(s, "/notepad/image?tab=ffffffffffff", JPEG); assert.equal(stray.status, 404); @@ -1022,12 +1027,12 @@ test("pictures through ?tab=: upload, thumb, fetch and delete, each under the ta assert.equal((await postJpeg(s, `/notepad/image?tab=nope`, JPEG)).status, 404); assert.equal((await s.send(`/notepad/image/delete?tab=${b}`, { id })).status, 404, "tab B does not hold it"); assert.equal((await s.send(`/notepad/image/delete?tab=ffffffffffff`, { id })).status, 404); - assert.equal((await get(url)).status, 200, "still there"); + assert.equal((await get(served)).status, 200, "still there"); assert.equal((await s.send(`/notepad/image/delete?tab=${a}`, { id })).status, 200); - assert.equal((await get(url)).status, 404); + assert.equal((await get(served)).status, 404); // With no tab named, the picture goes to the last tab used. const unnamed = await (await postJpeg(s, "/notepad/image", JPEG)).json(); - assert.equal(unnamed.url.split("/")[3], b); + assert.equal(unnamed.url.split("/")[2], b); assert.equal((await s.send("/notepad/image/delete", { id: unnamed.id })).status, 200); assert.deepEqual(await (await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG)).json(), { error: "not-found" }); }); diff --git a/scripts/test-web-console-page-notepad.mjs b/scripts/test-web-console-page-notepad.mjs index 4793331..6c519c3 100644 --- a/scripts/test-web-console-page-notepad.mjs +++ b/scripts/test-web-console-page-notepad.mjs @@ -579,7 +579,7 @@ test("each tab keeps its own text and pictures, and switching never saves into t await tabNamed(s, "Ideas").click(); await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1); const src = await s.page.locator("#notepad-strip img").getAttribute("src"); - assert.match(src, new RegExp(`^/notepad/images/${ideas}/`), "the picture's address names its tab"); + assert.match(src, new RegExp(`^notepad/images/${ideas}/`), "the picture's address names its tab"); // A save that cannot reach the server keeps you on the tab, with why. await s.page.route("**/notepad/text*", (route) => route.abort()); @@ -1009,7 +1009,8 @@ test("the preview opens at the clicked picture, steps and wraps, and Esc closes const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); await openNotepad(s); for (const color of ["#c33", "#3c3", "#33c"]) await addViaButton(s, color); - const urls = stored(s).map((img) => img.url); + // Page-relative: the page at / shows each one here. + const urls = stored(s).map((img) => `/${img.url}`); const shown = () => s.page.evaluate(() => ({ src: new URL(document.getElementById("picview-img").src).pathname, diff --git a/scripts/test-web-console-qa.mjs b/scripts/test-web-console-qa.mjs index f8e2fc0..b4ec9c7 100644 --- a/scripts/test-web-console-qa.mjs +++ b/scripts/test-web-console-qa.mjs @@ -432,7 +432,7 @@ test("kept attachments are served read-only from the session's spec, by their ex assert.match(kept, /realpathSync/); assert.match(kept, /path\.dirname\(real\)\.toLowerCase\(\) !== realDir\.toLowerCase\(\)/, "only files directly in attachments/"); const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8"); - assert.match(render, /return "\/attachments\/" \+ kept\[1\]\.toLowerCase\(\)/); + assert.match(render, /return "attachments\/" \+ kept\[1\]\.toLowerCase\(\)/); assert.match(render, /function isComment\(t\)/, "HTML comments are not shown"); assert.match(render, /"!": \{ mark: "!", label: "blocked"/, "a blocked task gets its marker"); }); diff --git a/scripts/test-web-console-relative-urls.mjs b/scripts/test-web-console-relative-urls.mjs new file mode 100644 index 0000000..ab13e1a --- /dev/null +++ b/scripts/test-web-console-relative-urls.mjs @@ -0,0 +1,182 @@ +// Web console tests, the page's URLs: every URL the page uses is page-relative. +// The macOS app's frame gets no cookie, so it signs in by a path prefix +// (`/f//`, routes.mjs) and the page is served under it there, while a +// browser tab has it at `/`. A relative `state` reaches the server either +// way; a slash-leading `/state` drops the prefix and gets a 403, in the macOS +// app only, so no other test would notice. This guard reads the page's source +// (and the links the server hands it) and names each slash-leading one. +// Run with: node --test scripts/test-web-console-relative-urls.mjs + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { ROOT } from "./web-console-test-helpers.mjs"; + +const CONSOLE_DIR = path.join(ROOT, "src", "web-console"); +const PUBLIC_DIR = path.join(CONSOLE_DIR, "public"); + +const WHY = "the macOS app serves the page under /f//, so a slash-leading URL misses the prefix and gets a 403 there; drop the leading slash"; + +// Slash-leading text that is not a URL. Any literal opening `/plan2code` is a +// slash command (no route starts so); anything else is named here, by file +// and exact literal, with its reason. +const SLASH_COMMAND = /^.\/plan2code(?![\w/])|^.\/plan2code-/; +const TEXT = new Map([ + ["answers.js", new Set(["`/${offer.skill}`"])], // a skill offer's slash command + ["diff-parse.js", new Set(['"/dev/null"'])], // git's name for no file in a diff header, compared, never fetched + ["loop-parts.js", new Set(['"/api/webhooks/"'])], // a path test on a Discord address the person typed + ["skills.js", new Set(['"/"'])], // `"/" + entry.skill`, a skill's slash command +]); + +// Every page file the rule reads: scripts, the page and stylesheets under +// public/, vendored code aside, as paths relative to it with forward slashes. +function pageFiles(rel = "") { + const out = []; + for (const e of fs.readdirSync(path.join(PUBLIC_DIR, rel), { withFileTypes: true })) { + const p = rel ? `${rel}/${e.name}` : e.name; + if (e.isDirectory()) { + if (p !== "vendor") out.push(...pageFiles(p)); + } else if (/\.(js|html|css)$/.test(e.name)) out.push(p); + } + return out; +} + +/** + * Each string literal in `text` (double quotes, single quotes or backticks) + * that makes a slash-leading URL, as `{ line, literal }`, in three shapes: + * text opening with `/` and a path character (a letter, digit, `_`, `.`, `-` + * or `${`); a lone `"/"` that starts an expression joined on with `+` + * (`fetch("/" + route)`; one joined in the middle of a path is fine); and + * markup in a string whose `src`, `href` or like attribute opens with `/` + * (`` `` ``). A comment line and anything after a `//` outside + * a string are skipped; `//` opening a string is the protocol-relative case, + * which render.js blocks on its own. Quotes are tracked one line at a time, so + * a template literal that spans lines, or a regex literal holding a quote, + * can put the scan out of step for the rest of that line: a URL there goes + * unflagged, and only the frame page test, which loads the dashboard alone, + * would catch it at run time. + */ +function scriptUrls(text) { + const hits = []; + text.split("\n").forEach((line, i) => { + const t = line.trim(); + if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return; + for (let j = 0; j < line.length; j++) { + const c = line[j]; + if (c === "/" && line[j + 1] === "/") break; + if (c !== '"' && c !== "'" && c !== "`") continue; + let k = j + 1; + while (k < line.length && line[k] !== c) k += line[k] === "\\" ? 2 : 1; + const body = line.slice(j + 1, k); + const opens = body[0] === "/" && /[A-Za-z0-9_.$-]/.test(body[1] || ""); + const joined = body === "/" && /^\s*\+/.test(line.slice(k + 1)) && STARTS_EXPRESSION.test(line.slice(0, j)); + if (opens || joined || ATTRIBUTE_URL.test(body)) hits.push({ line: i + 1, literal: line.slice(j, k + 1) }); + j = k; + } + }); + return hits; +} + +// What may come right before an expression's first operand: nothing, an +// opening bracket, a separator, an operator or `return`. +const STARTS_EXPRESSION = /(?:^|[([{,=:?!&|>]|\breturn)\s*$/; + +// An attribute that holds a URL, opening with `/` (but not `//`), in markup a +// script builds, quoted or not and with its quote escaped or not. +const ATTRIBUTE_URL = /\b(?:src|srcset|href|action|poster|data)=\\?["']?\/(?![/\\])/; + +/** Each `src`, `srcset`, `href`, `action`, `poster` or `data` value opening with `/`, in either quotes. */ +function htmlUrls(text) { + return text + .split("\n") + .flatMap((l, i) => + [...l.matchAll(/\b(?:src|srcset|href|action|poster|data)=(?:"(\/[^"]*)"|'(\/[^']*)')/g)].map((m) => ({ line: i + 1, literal: m[1] ?? m[2] })) + ); +} + +/** Each `url(/...)` or `@import "/..."`. */ +function cssUrls(text) { + return text + .split("\n") + .flatMap((l, i) => [...l.matchAll(/url\(\s*["']?(\/[^)"']*)|@import\s+["'](\/[^"']*)/g)].map((m) => ({ line: i + 1, literal: m[1] || m[2] }))); +} + +// A link the server builds for the page: a slash-leading literal given to a +// name holding `url`, `href` or `src` (`url: "/uploads/..."`, `imageUrl = (...) => "/..."`). +const SERVER_LINK = /\b\w*(?:url|href|src)\w*\s*[:=]\s*(?:\([^)]*\)\s*=>\s*)?["'`]\/(?!\/)/i; + +function pageOffenders() { + const out = []; + for (const f of pageFiles()) { + const text = fs.readFileSync(path.join(PUBLIC_DIR, f), "utf8"); + if (f.endsWith(".html")) { + out.push(...htmlUrls(text).map((h) => ({ file: f, ...h }))); + continue; + } + if (f.endsWith(".css")) { + out.push(...cssUrls(text).map((h) => ({ file: f, ...h }))); + continue; + } + for (const h of scriptUrls(text)) { + if (SLASH_COMMAND.test(h.literal) || TEXT.get(f)?.has(h.literal)) continue; + out.push({ file: f, ...h }); + } + } + return out.map((h) => `public/${h.file}:${h.line} ${h.literal}`); +} + +test("the scanner finds slash-leading literals and leaves comments, other schemes and slash commands alone", () => { + const found = (src) => scriptUrls(src).map((h) => h.literal); + assert.deepEqual(found('fetch("/state");'), ['"/state"']); + assert.deepEqual(found("x('/looks', `/${a}.mp3`)"), ["'/looks'", "`/${a}.mp3`"]); + assert.deepEqual(found('a("state"); b("https://x/y"); c("//cdn"); d("/");'), []); + assert.deepEqual(found('// fetch("/state")'), []); + assert.deepEqual(found(' * see "/state"'), []); + assert.deepEqual(found('go(); // then "/state"'), []); + assert.deepEqual(found('q("a\\"/b", "/c")'), ['"/c"']); + // A slash joined on at the start of an expression, and markup holding one. + assert.deepEqual(found('fetch("/" + route); x = "/" + y; return "/" + z;'), ['"/"', '"/"', '"/"']); + assert.deepEqual(found('a("notepad/images/" + tab + "/" + id); b(sep ? "/" : "")'), []); + assert.deepEqual(found('box.innerHTML = ``;'), ['``']); + assert.deepEqual(found("h = ''; s = \"\";").length, 2); + assert.deepEqual(found('h = ``'), []); + assert.ok(SLASH_COMMAND.test('"/plan2code"') && SLASH_COMMAND.test('"/plan2code-review"')); + assert.ok(!SLASH_COMMAND.test('"/plan2codex"') && !SLASH_COMMAND.test('"/plan2code/x"')); + assert.deepEqual(htmlUrls(''), [{ line: 1, literal: "/app.css" }]); + assert.deepEqual(htmlUrls(""), [ + { line: 1, literal: "/x.png" }, + { line: 1, literal: "/y.png 2x" }, + ]); + assert.deepEqual(cssUrls("a { background: url(/x.png) } @import \"/y.css\";"), [ + { line: 1, literal: "/x.png" }, + { line: 1, literal: "/y.css" }, + ]); + assert.ok(SERVER_LINK.test('url: "/uploads/" + id')); + assert.ok(SERVER_LINK.test('const imageUrl = (tab, id) => "/notepad/images/" + tab')); + assert.ok(!SERVER_LINK.test('url: "uploads/" + id') && !SERVER_LINK.test('{ path: "/state", run }')); +}); + +test("every URL in the page is page-relative", () => { + const offenders = pageOffenders(); + assert.deepEqual(offenders, [], `${offenders.length} slash-leading URL(s) in the page (${WHY}):\n${offenders.join("\n")}`); +}); + +test("every link the server hands the page is page-relative", () => { + const offenders = []; + for (const f of fs.readdirSync(CONSOLE_DIR).filter((n) => n.endsWith(".mjs"))) { + fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8") + .split("\n") + .forEach((l, i) => { + if (!l.trim().startsWith("//") && SERVER_LINK.test(l)) offenders.push(`${f}:${i + 1} ${l.trim()}`); + }); + } + assert.deepEqual(offenders, [], `slash-leading link(s) the server builds for the page (${WHY}):\n${offenders.join("\n")}`); +}); + +test("every name the rule lets through is still in its file", () => { + for (const [file, literals] of TEXT) { + const found = new Set(scriptUrls(fs.readFileSync(path.join(PUBLIC_DIR, file), "utf8")).map((h) => h.literal)); + for (const literal of literals) assert.ok(found.has(literal), `${file} no longer has ${literal}: drop it from TEXT`); + } +}); diff --git a/scripts/test-web-console-server.mjs b/scripts/test-web-console-server.mjs index ed52eb9..57faefb 100644 --- a/scripts/test-web-console-server.mjs +++ b/scripts/test-web-console-server.mjs @@ -83,7 +83,7 @@ test("the page carries its first state, title and badge, so the first paint need assert.ok(html.includes(`

Lunch </script><script>alert(1)</script> $& $' app

`)); assert.ok(html.includes('Building')); assert.ok(html.includes("Starting Implement"), "the static starting screen names the skill"); - assert.ok(html.includes('rel="modulepreload" href="/app.js"')); + assert.ok(html.includes('rel="modulepreload" href="app.js"')); cli(["stop", "--session", res.json.sid, "--force"]); }); diff --git a/scripts/test-web-console-session.mjs b/scripts/test-web-console-session.mjs index 41385ce..66606ec 100644 --- a/scripts/test-web-console-session.mjs +++ b/scripts/test-web-console-session.mjs @@ -685,8 +685,8 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at assert.deepEqual([...bytes.slice(0, 4)], [0x89, 0x50, 0x4e, 0x47]); const html = await (await fetch(baseUrl + "/", { headers: { cookie: cookieFor(baseUrl, token) } })).text(); - assert.ok(html.includes('href="/favicon.svg"')); - assert.ok(html.includes('href="/favicon.png"')); + assert.ok(html.includes('href="favicon.svg"')); + assert.ok(html.includes('href="favicon.png"')); assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/); }); @@ -1006,7 +1006,7 @@ test("an upload is stored under a server-chosen name inside the session's upload const uploads = path.join(fs.realpathSync.native(session), "uploads"); assert.equal(path.dirname(file).toLowerCase(), uploads.toLowerCase()); assert.equal(path.basename(file), id + ".jpg"); - assert.equal(url, `/uploads/${id}.jpg`); + assert.equal(url, `uploads/${id}.jpg`); assert.equal(name, "../../evil name.png", "the name comes back as a label"); assert.equal(res.json.kind, "image"); assert.equal(res.json.size, JPEG.length); @@ -1035,7 +1035,8 @@ test("an upload that is not a JPEG, or is too large, is refused", async () => { }); test("an upload is served back by its own url, and nothing else under /uploads/ is", async () => { - const { url } = (await uploadJpeg()).json; + // Page-relative: the page at / asks for it here. + const url = `/${(await uploadJpeg()).json.url}`; const res = await raw("GET", url); assert.equal(res.status, 200); assert.equal(res.headers["content-type"], "image/jpeg"); @@ -1048,7 +1049,8 @@ test("an upload is served back by its own url, and nothing else under /uploads/ }); test("deleting an upload removes its file, once, and only from this origin", async () => { - const { url, path: file } = (await uploadJpeg()).json; + const { url: link, path: file } = (await uploadJpeg()).json; + const url = `/${link}`; assert.equal((await raw("DELETE", url, undefined, { origin: "http://evil.example.com" })).status, 403); assert.ok(fs.existsSync(file)); assert.equal((await raw("DELETE", url)).status, 204); diff --git a/scripts/test-web-console-source.mjs b/scripts/test-web-console-source.mjs index af6d460..a93dcff 100644 --- a/scripts/test-web-console-source.mjs +++ b/scripts/test-web-console-source.mjs @@ -516,7 +516,7 @@ test("prefs: the new modules are served and preloaded, and Preferences' styles l "screens/agents/agents-form.js", ]) { assert.ok(SERVABLE.has(m), `${m} is servable`); - assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`); + assert.ok(html.includes(`rel="modulepreload" href="${m}"`), `the page preloads ${m}`); } for (const sheet of ["styles/prefs.css", "styles/agents.css"]) { const css = publicSource(sheet); diff --git a/scripts/test-web-console-tones.mjs b/scripts/test-web-console-tones.mjs index bfc6997..ce0e7cb 100644 --- a/scripts/test-web-console-tones.mjs +++ b/scripts/test-web-console-tones.mjs @@ -497,7 +497,7 @@ test("music: a song plays from its file, fades in toward its level, says when it withSongs(async () => { const [name] = TRAILS_TRACKS; assert.equal(music(name, 1, 1, { restart: true }), "playing"); - const el = FakeAudio.made.find((a) => a.src === `/${trailsSfx.songs[name]}`); + const el = FakeAudio.made.find((a) => a.src === trailsSfx.songs[name]); assert.ok(el, "an element for the song's file"); assert.ok(!el.paused && el.plays === 1, "it plays"); for (let i = 0; i < 20; i++) { @@ -520,7 +520,7 @@ test("music: a song no longer asked for fades out and pauses where it was, and a withSongs(async () => { const [first, second] = TRAILS_TRACKS; music(first, 1, 0.5); - const el = FakeAudio.made.findLast((a) => a.src === `/${trailsSfx.songs[first]}`); + const el = FakeAudio.made.findLast((a) => a.src === trailsSfx.songs[first]); const loads = el.loads; await sleep(800); assert.ok(el.paused, "paused once it stops being asked for"); @@ -544,7 +544,7 @@ test("music: a song plays nothing while Play sounds is off, at a volume of 0, or assert.equal(music(name, 1, 0), undefined); globalThis.Audio = undefined; assert.equal(music(name, 1, 1), undefined); - assert.ok(FakeAudio.made.filter((a) => a.src === `/${trailsSfx.songs[name]}`).every((a) => a.paused), "nothing plays"); + assert.ok(FakeAudio.made.filter((a) => a.src === trailsSfx.songs[name]).every((a) => a.paused), "nothing plays"); })); test("music: every Sunset Drive road has a song, and every song is a real track", () => { diff --git a/src/web-console/notepads.mjs b/src/web-console/notepads.mjs index b0ae71a..d7a56c3 100644 --- a/src/web-console/notepads.mjs +++ b/src/web-console/notepads.mjs @@ -364,7 +364,9 @@ function imageEntries(dirs) { return [...seen.values()].sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); } -const imageUrl = (tab, id, thumb) => "/notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg"; +// Page-relative, as every link the page uses is: the macOS app's frame has the +// page under a path prefix (routes.mjs, takeFramePrefix). +const imageUrl = (tab, id, thumb) => "notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg"; /** * The tabs, as `[{ id, name, sent? }]` in order (`sent` only on a tab sent diff --git a/src/web-console/public/activities.js b/src/web-console/public/activities.js index cb649bc..d5506ce 100644 --- a/src/web-console/public/activities.js +++ b/src/web-console/public/activities.js @@ -29,7 +29,7 @@ // per game. Adding a game is one file and one line here. No DOM access and no imports: the page and `node --test` both // import this file. -const entry = (id, title, blurb, more = {}) => Object.freeze({ id, title, blurb, module: `/activities/${id}.js`, ...more }); +const entry = (id, title, blurb, more = {}) => Object.freeze({ id, title, blurb, module: `activities/${id}.js`, ...more }); export const ACTIVITIES = Object.freeze([ entry("snake", "Snake", "Eat, grow and dodge. Every level brings something new.", { music: 70 }), @@ -43,7 +43,7 @@ export const ACTIVITIES = Object.freeze([ entry("fuse", "Hot Potato", "Pass the bomb before it blows. Last one standing wins."), entry("hop", "Crossing Rush", "Hop through traffic and rivers. Race your rivals to the top."), entry("bounce", "Bounce Road", "Toy-car mayhem: jump, stomp, fire rockets and beat five bosses. No two runs alike.", { music: 70 }), - entry("ghoul", "Ghoul Rush", "Run and gun through a pitch-dark haunted house. Keep moving.", { music: 65, module: "/activities/ghoul-rush/ghoul.js" }), + entry("ghoul", "Ghoul Rush", "Run and gun through a pitch-dark haunted house. Keep moving.", { music: 65, module: "activities/ghoul-rush/ghoul.js" }), entry("flock", "Flock Dash", "Lead your flock through the sunset sky. Dodge everything, keep the line.", { music: 70 }), ]); diff --git a/src/web-console/public/diff-view.js b/src/web-console/public/diff-view.js index 377eb88..9d212ee 100644 --- a/src/web-console/public/diff-view.js +++ b/src/web-console/public/diff-view.js @@ -65,7 +65,7 @@ async function askAgain(button, status, reply) { button.disabled = true; button.textContent = "Asking…"; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [{ i: "__changes", type: "changes" }], reply }), diff --git a/src/web-console/public/doc-files.js b/src/web-console/public/doc-files.js index 7f96785..a72acca 100644 --- a/src/web-console/public/doc-files.js +++ b/src/web-console/public/doc-files.js @@ -14,7 +14,7 @@ export function blockBody(b, doc) { if (typeof b.image !== "string") return md(b.md, "md"); const fig = el("figure", "doc-figure"); const img = el("img", "doc-img"); - img.src = "/shots/" + b.image.split("/").pop(); + img.src = "shots/" + b.image.split("/").pop(); // The caption already says it: an alt repeating it is read twice, and shows // twice in an export whose picture would not load. img.alt = ""; @@ -126,8 +126,9 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; } // Only this session's uploaded images may ride along in a saved file: any other // address on this origin (/state, say) would copy session data into something // meant to be shared. A remote image keeps its own address; anything else on -// this origin becomes its alt text. -const INLINE_UPLOAD = /^\/(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i; +// this origin becomes its alt text. Matched on the path below the page's own +// folder: `/` in a browser tab, the frame's prefix in the macOS app. +const INLINE_UPLOAD = /^(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i; function imageToAlt(img) { const alt = img.getAttribute("alt") || ""; @@ -148,7 +149,9 @@ async function inlineImage(img) { img.setAttribute("src", url.href); return; } - if (!INLINE_UPLOAD.test(url.pathname) || url.search) return imageToAlt(img); + const folder = new URL(".", location.href).pathname; + const below = url.pathname.startsWith(folder) ? url.pathname.slice(folder.length) : ""; + if (!INLINE_UPLOAD.test(below) || url.search) return imageToAlt(img); try { const res = await fetch(url); if (!res.ok) throw new Error(String(res.status)); diff --git a/src/web-console/public/favicon.js b/src/web-console/public/favicon.js index ed56115..4063318 100644 --- a/src/web-console/public/favicon.js +++ b/src/web-console/public/favicon.js @@ -69,8 +69,8 @@ export function setFavicon(state) { const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]'); const pngLink = document.querySelector('link[rel="icon"][type="image/png"]'); if (state === "plain") { - if (svgLink) svgLink.href = "/favicon.svg"; - if (pngLink) pngLink.href = "/favicon.png"; + if (svgLink) svgLink.href = "favicon.svg"; + if (pngLink) pngLink.href = "favicon.png"; return; } const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state)); diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 0b96139..fc2f638 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -5,74 +5,74 @@ Plan2Code Console - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
@@ -4653,6 +4653,6 @@ - + diff --git a/src/web-console/public/looks.js b/src/web-console/public/looks.js index f7f57df..fa9215d 100644 --- a/src/web-console/public/looks.js +++ b/src/web-console/public/looks.js @@ -139,7 +139,7 @@ export async function syncLooks() { if (boot && "looks" in boot) saved = boot.looks ? { looks: boot.looks } : null; else { try { - const res = await fetch("/looks"); + const res = await fetch("looks"); if (res.ok) saved = await res.json(); } catch {} } @@ -184,7 +184,7 @@ function pushLooks() { undo(); return { ok: false, error: error || "Could not save." }; }; - return fetch("/looks", { + return fetch("looks", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), diff --git a/src/web-console/public/md-field.js b/src/web-console/public/md-field.js index de5015d..e725b6b 100644 --- a/src/web-console/public/md-field.js +++ b/src/web-console/public/md-field.js @@ -61,7 +61,7 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe host.className = "md-host" + (className ? " " + className : ""); if (id) host.id = id; const root = host.attachShadow({ mode: "open" }); - const sheets = ["/notepad-editor.css", "/md-field.css"].map((href) => { + const sheets = ["notepad-editor.css", "md-field.css"].map((href) => { const link = document.createElement("link"); link.rel = "stylesheet"; link.href = href; diff --git a/src/web-console/public/music.js b/src/web-console/public/music.js index c09a1dc..0378804 100644 --- a/src/web-console/public/music.js +++ b/src/web-console/public/music.js @@ -413,7 +413,7 @@ let songTicker = null; function songElement(name) { if (!songAudio.has(name)) { - const el = new Audio(`/${SONGS[name]}`); + const el = new Audio(SONGS[name]); el.preload = "auto"; el.volume = 0; songAudio.set(name, el); diff --git a/src/web-console/public/notepad-editor.js b/src/web-console/public/notepad-editor.js index 4ec8599..4b7b75a 100644 --- a/src/web-console/public/notepad-editor.js +++ b/src/web-console/public/notepad-editor.js @@ -208,7 +208,7 @@ export function makeCodeMirrorEditor(parent, { onChange, label }) { const root = host.attachShadow({ mode: "open" }); const sheet = document.createElement("link"); sheet.rel = "stylesheet"; - sheet.href = "/notepad-editor.css"; + sheet.href = "notepad-editor.css"; const mount = document.createElement("div"); mount.className = "notepad-cm"; root.append(sheet, mount); diff --git a/src/web-console/public/render.js b/src/web-console/public/render.js index 87a1c59..38b9390 100644 --- a/src/web-console/public/render.js +++ b/src/web-console/public/render.js @@ -73,7 +73,7 @@ function safeHref(href) { if (!href) return null; const trimmed = String(href).trim(); const kept = KEPT_ATTACHMENT.exec(trimmed); - if (kept) return "/attachments/" + kept[1].toLowerCase(); + if (kept) return "attachments/" + kept[1].toLowerCase(); // Blocks javascript: and data: hrefs before they can reach the DOM, and a // protocol-relative `//host` (or `/\host`), which leaves the page for another site. return SAFE_PROTOCOL.test(trimmed) ? trimmed : null; diff --git a/src/web-console/public/screens/activities.js b/src/web-console/public/screens/activities.js index 260cbae..5b0fc7e 100644 --- a/src/web-console/public/screens/activities.js +++ b/src/web-console/public/screens/activities.js @@ -654,7 +654,9 @@ async function loadGame(entry) { if (games.has(entry.id)) return games.get(entry.id); if (!loading.has(entry.id)) { const made = (async () => { - const def = entry.game || (await import(entry.module)).default; + // `module` is page-relative, as every URL the page uses is, and import() + // takes no bare path: resolved against the page, as fetch() would. + const def = entry.game || (await import(new URL(entry.module, document.baseURI).href)).default; defs.set(entry.id, def); if (def.lowerIsBetter) lowerIsBetter.add(entry.id); else lowerIsBetter.delete(entry.id); diff --git a/src/web-console/public/screens/agents-view.js b/src/web-console/public/screens/agents-view.js index 770db1d..f93d885 100644 --- a/src/web-console/public/screens/agents-view.js +++ b/src/web-console/public/screens/agents-view.js @@ -306,7 +306,7 @@ export function mountAgentsView(container, opts = {}) { let state = ctx.templateState.get(command) || "unknown"; if (state === "unknown") { try { - const res = await fetch("/agents/test", { + const res = await fetch("agents/test", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ command }), @@ -337,7 +337,7 @@ export function mountAgentsView(container, opts = {}) { rows.map(async (row) => { let state = "unknown"; try { - const res = await fetch("/agents/test", { + const res = await fetch("agents/test", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ command: row.command }), @@ -355,7 +355,7 @@ export function mountAgentsView(container, opts = {}) { // The command's Test: where it would run from. Never saves. async function testCommand(command) { try { - const res = await fetch("/agents/test", { + const res = await fetch("agents/test", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ command }), @@ -373,7 +373,7 @@ export function mountAgentsView(container, opts = {}) { // press is the one failure the status line gets. async function useFromHere(entry) { try { - const res = await fetch("/agents/use-path", { + const res = await fetch("agents/use-path", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id: entry.id }), @@ -436,7 +436,7 @@ export function mountAgentsView(container, opts = {}) { const modelIds = [...ctx.saved.shipped[cli], ...sent].map((m) => m.id); const payload = { models: { ...ctx.saved.user, [cli]: sent } }; if (ctx.modelsLoaded) payload.strengths = strengthsToSend(cli, key, modelIds); - const { res, body } = await postJson("/models", payload); + const { res, body } = await postJson("models", payload); if (!res.ok) { formMark({ ok: false, error: body.error || "Could not save." }); return false; @@ -465,7 +465,7 @@ export function mountAgentsView(container, opts = {}) { const agents = ctx.saved.agents.map((a) => cleanAgent(a)); agents.splice(at, isNew ? 0 : 1, cleanAgent(draft)); try { - const { res, body } = await postJson("/agents", replace ? { agents, replace: true } : { agents }); + const { res, body } = await postJson("agents", replace ? { agents, replace: true } : { agents }); if (res.status === 409) { ctx.formError = { field: null, error: body.error || "Not saved." }; ctx.formReplace = Array.isArray(body.warnings) ? body.warnings : []; @@ -504,7 +504,7 @@ export function mountAgentsView(container, opts = {}) { return false; }; try { - const { res, body } = await postJson("/models", { models: ctx.saved.user, strengths: strengthsToSend(id, key, modelIds) }); + const { res, body } = await postJson("models", { models: ctx.saved.user, strengths: strengthsToSend(id, key, modelIds) }); if (!res.ok) return strengthsFailed(body.error || "Saved, but the strengths could not be."); ctx.saved.strengths.user = body.strengths || {}; } catch { @@ -526,7 +526,7 @@ export function mountAgentsView(container, opts = {}) { const agents = ctx.saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent); ctx.confirming = false; try { - const { res, body } = await postJson("/agents", { agents }); + const { res, body } = await postJson("agents", { agents }); if (!res.ok) { ctx.formError = { field: null, error: body.error || "Could not delete." }; drawForm(ctx); @@ -592,8 +592,8 @@ export function mountAgentsView(container, opts = {}) { ctx.formReplace = null; ctx.confirming = false; const [agents, models] = await Promise.all([ - fetch("/agents").then((r) => (r.ok ? r.json() : null)).catch(() => null), - mode === "setup" ? Promise.resolve(null) : fetch("/models").then((r) => (r.ok ? r.json() : null)).catch(() => null), + fetch("agents").then((r) => (r.ok ? r.json() : null)).catch(() => null), + mode === "setup" ? Promise.resolve(null) : fetch("models").then((r) => (r.ok ? r.json() : null)).catch(() => null), ]); if (seq !== loadSeq) return; const problems = []; diff --git a/src/web-console/public/screens/ask.js b/src/web-console/public/screens/ask.js index 6217276..72f57e8 100644 --- a/src/web-console/public/screens/ask.js +++ b/src/web-console/public/screens/ask.js @@ -592,7 +592,7 @@ async function postChat(pend) { let res = null; let body = {}; try { - res = await fetch("/chat", { + res = await fetch("chat", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ @@ -641,7 +641,7 @@ async function newConversation() { let res = null; let body = {}; try { - res = await fetch("/chat", { + res = await fetch("chat", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ reset: true, conversation: askConversation() }), @@ -674,7 +674,7 @@ async function decideChat(re, decision, text) { let ok = false; let body = {}; try { - const res = await fetch("/chat/decision", { + const res = await fetch("chat/decision", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }), @@ -1176,7 +1176,7 @@ export async function saveSubagents() { }; save.disabled = true; status.textContent = ""; - const res = await postJson("/subagents", body); + const res = await postJson("subagents", body); save.disabled = false; // The next state frame redraws the button. if (res.status === 200) { diff --git a/src/web-console/public/screens/cleanup.js b/src/web-console/public/screens/cleanup.js index 2e3d124..2373005 100644 --- a/src/web-console/public/screens/cleanup.js +++ b/src/web-console/public/screens/cleanup.js @@ -141,7 +141,7 @@ async function scanCleanup() { $("cleanup-scan").disabled = true; $("cleanup-delete").disabled = true; setCleanupStatus("Looking…", false); - const { status, body } = await postJson("/cleanup", { scan: true }); + const { status, body } = await postJson("cleanup", { scan: true }); if (gen !== cleanupGen) return; $("cleanup-scan").disabled = false; $("cleanup-delete").disabled = false; @@ -169,7 +169,7 @@ async function deleteCleanup() { $("cleanup-scan").disabled = true; setCleanupStatus("Deleting…", false); cleanupBusy = true; - const { status, body } = await postJson("/cleanup", { delete: ids }).finally(() => { + const { status, body } = await postJson("cleanup", { delete: ids }).finally(() => { cleanupBusy = false; }); if (gen !== cleanupGen) return; diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index 49ab004..28c177e 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -234,7 +234,7 @@ function fillNoteBox() { async function seedNoteBox(item, ns) { const tab = encodeURIComponent(ns.tab); try { - const res = await fetch("/notepad?tab=" + tab, { cache: "no-store" }); + const res = await fetch("notepad?tab=" + tab, { cache: "no-store" }); if (res.status === 404) { banner("That Notebook tab is gone; the box starts empty.", "warn"); return; @@ -251,7 +251,7 @@ async function seedNoteBox(item, ns) { const files = await Promise.all( (ns.pictures || []).map(async (id) => { try { - const r = await fetch("/notepad/images/" + tab + "/" + encodeURIComponent(id) + ".jpg", { cache: "no-store" }); + const r = await fetch("notepad/images/" + tab + "/" + encodeURIComponent(id) + ".jpg", { cache: "no-store" }); return r.ok ? new File([await r.blob()], id + ".jpg", { type: "image/jpeg" }) : null; } catch { return null; @@ -264,7 +264,7 @@ async function seedNoteBox(item, ns) { async function pushDraft() { try { - await fetch("/draft", { + await fetch("draft", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ staged: page.local.staged, drafts: page.local.drafts, images: page.local.images, seeded: page.local.seeded }), @@ -284,7 +284,7 @@ function agentStale() { export async function loadState() { try { - const res = await fetch("/state", { cache: "no-store" }); + const res = await fetch("state", { cache: "no-store" }); if (!res.ok) throw new Error(String(res.status)); const body = await res.json(); // The same rev is the same state: adopting it again would redraw the page @@ -759,7 +759,7 @@ function markGone() { export function connect() { esErrors = 0; try { - es = new EventSource(lastHave ? "/events?have=" + encodeURIComponent(lastHave) : "/events"); + es = new EventSource(lastHave ? "events?have=" + encodeURIComponent(lastHave) : "events"); } catch { es = null; return startPolling(); @@ -846,7 +846,7 @@ function retryStream() { // whether the agent is, whether a state frame went missing, and whether a // send is still waiting to be picked up. export function checkIn() { - fetch("/ping", { method: "POST" }) + fetch("ping", { method: "POST" }) .then((r) => (r.ok ? r.json() : null)) .then((body) => { if (!body) return; @@ -2194,7 +2194,7 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) { const ns = page.local.noteSent; if (ns && sentIds.has(ns.item)) { page.local.noteSent = null; - fetch("/notepad/tab/sent", { + fetch("notepad/tab/sent", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id: ns.tab, workflow: ns.workflow, ...(ns.spec ? { spec: ns.spec } : {}) }), @@ -2223,7 +2223,7 @@ export async function askSuggestions(itemId) { const text = note ? note.text : ""; const images = note ? note.images : []; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ @@ -2275,7 +2275,7 @@ export async function send() { $("send-nudge").hidden = true; btn.textContent = "Sending…"; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions, reply: replyLines.join("\n") }), @@ -2327,7 +2327,7 @@ export async function send() { // 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" }) + const up = await fetch("state", { cache: "no-store" }) .then((res) => res.ok) .catch(() => false); if (up) { @@ -2489,7 +2489,7 @@ let whereResizeTimer = null; // 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", { + const ok = await fetch("open-link", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ url: href }), @@ -2507,7 +2507,7 @@ export function wireChrome() { // with `referrer-policy: no-referrer` with `Origin: null`, which /bye's // origin check refuses. try { - fetch("/bye", { method: "POST", keepalive: true }).catch(() => {}); + fetch("bye", { method: "POST", keepalive: true }).catch(() => {}); } catch {} // A page that goes away leaves no dot on the app's taskbar behind it. tellAttention("plain"); diff --git a/src/web-console/public/screens/dashboard.js b/src/web-console/public/screens/dashboard.js index c4f2dbd..dab32f7 100644 --- a/src/web-console/public/screens/dashboard.js +++ b/src/web-console/public/screens/dashboard.js @@ -387,7 +387,7 @@ function maybeWake() { page.wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() }; wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches; if (wakeHoldsChime && soundOn("snore")) { - snore = new Audio("/sleeping.mp3"); + snore = new Audio("sleeping.mp3"); snore.loop = true; snore.play().catch(() => {}); } @@ -709,7 +709,7 @@ async function pickUpHandoff(h) { page.launchScoping = true; await hooks.syncWorkspaceScope(h.spec || ""); try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }), @@ -741,7 +741,7 @@ async function readHandoff(h) { body.replaceChildren(el("p", "md-p", "Reading…")); $("handoff-modal").showModal(); try { - const res = await fetch("/handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" }); + const res = await fetch("handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" }); if (res.status !== 200) throw new Error(String(res.status)); mdInto(body, await res.text()); } catch { @@ -836,14 +836,14 @@ export function pendingNotePick(entry) { // grayed, so each must be read). Read only: GET /notepad never writes. async function readNoteTabs(state) { try { - const res = await fetch("/notepad", { cache: "no-store" }); + const res = await fetch("notepad", { cache: "no-store" }); if (!res.ok) throw new Error(String(res.status)); const body = await res.json(); const tabs = Array.isArray(body.tabs) ? body.tabs : []; const read = await Promise.all( tabs.map(async (t) => { try { - const r = await fetch("/notepad?tab=" + encodeURIComponent(t.id), { cache: "no-store" }); + const r = await fetch("notepad?tab=" + encodeURIComponent(t.id), { cache: "no-store" }); if (!r.ok) return null; const b = await r.json(); return b && b.tab ? { text: typeof b.tab.text === "string" ? b.tab.text : "", images: Array.isArray(b.tab.images) ? b.tab.images : [] } : null; @@ -1243,7 +1243,7 @@ export async function launchSkill(entry) { page.launchScoping = true; await hooks.syncWorkspaceScope(target ? target.dir : ""); try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ @@ -1390,7 +1390,7 @@ async function sendDeleteHandoff(h) { const go = $("delete-go"); go.disabled = true; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }), @@ -1422,7 +1422,7 @@ async function sendDelete(spec) { const go = $("delete-go"); go.disabled = true; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }), @@ -1512,7 +1512,7 @@ function learningBanner(sc) { // quiet: the nudge simply stays, as it did before. async function quietTidyNudge() { try { - await postJson("/learning/tidy-quiet", {}); + await postJson("learning/tidy-quiet", {}); } catch {} redraw(); } @@ -1582,7 +1582,7 @@ export async function sendLearning(what) { if (what === "review" || what === "tidy") watchLearningBusy(busy); } try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [learningAction(what)], reply: learningReply(what) }), diff --git a/src/web-console/public/screens/docs.js b/src/web-console/public/screens/docs.js index 427e0c2..4356e55 100644 --- a/src/web-console/public/screens/docs.js +++ b/src/web-console/public/screens/docs.js @@ -82,7 +82,7 @@ export async function sendBrief() { go.disabled = true; go.textContent = "Asking…"; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ @@ -322,7 +322,7 @@ export function renderAgentsDoc(main) { // default browser (the app's webview opens no windows, and a page served over // http cannot open a file:// link). A failure says so on the banner. async function openPrototypePage(spec, name) { - const ok = await fetch("/open-prototype", { + const ok = await fetch("open-prototype", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ spec, name }), diff --git a/src/web-console/public/screens/ending.js b/src/web-console/public/screens/ending.js index aad1152..3ce7b31 100644 --- a/src/web-console/public/screens/ending.js +++ b/src/web-console/public/screens/ending.js @@ -195,7 +195,7 @@ let loopLessons = { key: null, line: "" }; function loopLessonsFor(key) { if (loopLessons.key === key) return loopLessons.line; loopLessons = { key, line: "" }; - fetch("/learning/state", { cache: "no-store" }) + fetch("learning/state", { cache: "no-store" }) .then((res) => (res.ok ? res.json() : null)) .then((learning) => { const line = loopLessonsLine(learning); @@ -907,7 +907,7 @@ const AFTER_FINISH_REPLIES = { review: REVIEW_REPLY, done: DONE_REPLY, dashboard async function sendAfterBuild(kind, launch = null) { if (page.gone || page.pendingResult || page.local.afterBuild) return; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ @@ -1100,7 +1100,7 @@ async function goHome() { const payload = hooks.stagedPayload(); payload.actions.push({ i: "__dashboard", type: "dashboard" }); try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, HOME_REPLY].join("\n") }), @@ -1180,7 +1180,7 @@ async function stopSession(handoff = false) { const payload = hooks.stagedPayload(); payload.actions.push(stopAction({ handoff })); try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }), diff --git a/src/web-console/public/screens/git-host.js b/src/web-console/public/screens/git-host.js index b028c3e..1899aa2 100644 --- a/src/web-console/public/screens/git-host.js +++ b/src/web-console/public/screens/git-host.js @@ -144,7 +144,7 @@ async function sendGit(op, fields = {}, wording = {}) { return; } try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ @@ -281,7 +281,7 @@ function gitTabKeys(e) { // the action that follows has the agent re-read, which rebuilds the link. async function pickPrHost(host, kind) { if (gitLocked()) return; - const res = await postJson("/pr-host", { host, kind }); + const res = await postJson("pr-host", { host, kind }); if (res.status !== 200) { hooks.banner("That could not be saved. Try again in a moment.", "warn"); return; diff --git a/src/web-console/public/screens/help-dialog.js b/src/web-console/public/screens/help-dialog.js index 0ba2b23..90cda05 100644 --- a/src/web-console/public/screens/help-dialog.js +++ b/src/web-console/public/screens/help-dialog.js @@ -209,7 +209,7 @@ let helpTabs = null; async function renderHelpVersion() { const slot = $("help-version"); try { - const res = await fetch("/version", { cache: "no-store" }); + const res = await fetch("version", { cache: "no-store" }); const { version } = res.ok ? await res.json() : {}; slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : [])); slot.hidden = !version; diff --git a/src/web-console/public/screens/learning-row.js b/src/web-console/public/screens/learning-row.js index 833c075..c7713be 100644 --- a/src/web-console/public/screens/learning-row.js +++ b/src/web-console/public/screens/learning-row.js @@ -86,7 +86,7 @@ function pauseSwitch(paused) { if (pausing) return; pausing = true; redraw(); - const { status } = await postJson("/learning/pause", { paused: !paused }); + const { status } = await postJson("learning/pause", { paused: !paused }); pausing = false; if (status !== 200) { hooks.banner( @@ -567,7 +567,7 @@ async function openLessons() { body.replaceChildren(el("p", "md-p", "Reading…")); dlg.showModal(); try { - const res = await fetch("/learning/lessons", { cache: "no-store" }); + const res = await fetch("learning/lessons", { cache: "no-store" }); if (res.status !== 200) throw new Error(String(res.status)); const { files, follows } = await res.json(); body.replaceChildren(); diff --git a/src/web-console/public/screens/loop-setup.js b/src/web-console/public/screens/loop-setup.js index 0c3f63c..e1371cb 100644 --- a/src/web-console/public/screens/loop-setup.js +++ b/src/web-console/public/screens/loop-setup.js @@ -61,7 +61,7 @@ export async function openLoopSetup(spec) { const mine = page.loopSetup; let res; try { - res = await fetch("/loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" }); + res = await fetch("loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" }); } catch { res = null; } @@ -129,7 +129,7 @@ function ensureResolved(s) { s.facts.resolved = null; return; } - fetch("/loop-setup?spec=" + encodeURIComponent(s.spec) + "&agent=" + encodeURIComponent(agent), { cache: "no-store" }) + fetch("loop-setup?spec=" + encodeURIComponent(s.spec) + "&agent=" + encodeURIComponent(agent), { cache: "no-store" }) .then((res) => (res.ok ? res.json() : null)) .catch(() => null) .then((answer) => { @@ -371,7 +371,7 @@ async function askForSuggestion(s, words) { strengths: words, }; try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [action], reply: `Suggest a strength for each phase left in ${s.spec}.` }), @@ -741,7 +741,7 @@ async function sendTest(s) { s.problems = []; page.loopNotifyTest = { waiting: true }; redraw(); - const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s)); + const { status, body: answer } = await postJson("loop-setup", setupBody(f, s)); if (page.loopSetup !== s) return; if (status !== 200 || !answer || answer.ok !== true) { page.loopNotifyTest = null; @@ -759,7 +759,7 @@ async function startLoop(s) { page.loopStart = null; s.starting = true; redraw(); - const { status, body: answer } = await postJson("/loop-setup", setupBody(f, s)); + const { status, body: answer } = await postJson("loop-setup", setupBody(f, s)); if (page.loopSetup !== s) return; if (status !== 200 || !answer || answer.ok !== true) { s.starting = false; diff --git a/src/web-console/public/screens/notepad.js b/src/web-console/public/screens/notepad.js index f0c62cf..228e1cf 100644 --- a/src/web-console/public/screens/notepad.js +++ b/src/web-console/public/screens/notepad.js @@ -160,7 +160,7 @@ async function send() { sending = true; const sent = rev; const tab = saveTab; - const res = await postJson("/notepad/text?tab=" + tab, { text: editor.getValue() }); + const res = await postJson("notepad/text?tab=" + tab, { text: editor.getValue() }); sending = false; // The tab was deleted or left behind while this was out: nothing in the // answer applies to what is on screen now. @@ -231,7 +231,7 @@ async function makeEditor() { // be reached or answered oddly. async function readNote(tab) { try { - const res = await fetch("/notepad" + (tab ? "?tab=" + encodeURIComponent(tab) : ""), { cache: "no-store" }); + const res = await fetch("notepad" + (tab ? "?tab=" + encodeURIComponent(tab) : ""), { cache: "no-store" }); let body = null; try { body = await res.json(); @@ -323,7 +323,7 @@ async function showTab(id, remember = true) { return false; } show(res.body); - if (remember && activeId) postJson("/notepad/tab/last", { id: activeId }); + if (remember && activeId) postJson("notepad/tab/last", { id: activeId }); return true; } @@ -349,7 +349,7 @@ async function reorder(order, focus) { tabBar.focusTab(focus); const at = order.indexOf(focus); if (at >= 0) inform(`Moved ${nameOf(focus)} to position ${at + 1} of ${order.length}`); - const res = await postJson("/notepad/tab/order", { order }); + const res = await postJson("notepad/tab/order", { order }); if (res.status === 200) return; // Refused: draw what the server has, and say why. tabs = before; @@ -438,7 +438,7 @@ function closeNameForm(toFocus = true) { async function createNamed(name) { // The tab on screen is saved first, then the new one is made and shown. if (!(await settled())) return nameError(STAY); - const res = await postJson("/notepad/tab", { name }); + const res = await postJson("notepad/tab", { name }); const id = res.body && res.body.id; if (res.status !== 200 || !TAB_ID_RE.test(String(id))) { return nameError(errorSentence(res.status === 0 ? null : res.body && res.body.error)); @@ -456,7 +456,7 @@ async function createNamed(name) { async function renameTo(name) { const id = activeId; - const res = await postJson("/notepad/tab/rename", { id, name }); + const res = await postJson("notepad/tab/rename", { id, name }); if (res.status !== 200) { const code = res.status === 0 ? null : res.body && res.body.error; if (code !== "no-such-tab") return nameError(errorSentence(code)); @@ -530,7 +530,7 @@ async function confirmDelete() { busy = true; drawTabs(); paintDelete(); - const res = await postJson("/notepad/tab/delete", { id }); + const res = await postJson("notepad/tab/delete", { id }); const code = res.status === 0 ? null : res.body && res.body.error; busy = false; stage = "none"; @@ -592,14 +592,14 @@ async function upload(entry) { entry.status = "uploading"; if (live(entry)) drawStrip(); if (!entry.id) { - const res = await postJpeg("/notepad/image?tab=" + entry.tab, encoded.blob); + const res = await postJpeg("notepad/image?tab=" + entry.tab, encoded.blob); const id = res.body && res.body.id; if (res.status !== 200 || !IMAGE_ID_RE.test(String(id))) return failed(entry, res); entry.id = id; // The server names the URL (it carries the tab). entry.url = res.body.url; } - const res = await postJpeg("/notepad/thumb?id=" + entry.id + "&tab=" + entry.tab, encoded.thumbBlob); + const res = await postJpeg("notepad/thumb?id=" + entry.id + "&tab=" + entry.tab, encoded.thumbBlob); if (res.status !== 200) return failed(entry, res); pending.delete(entry.key); entry.status = "ready"; @@ -756,7 +756,7 @@ async function remove(entry) { if (entry.id) { entry.deleting = true; drawStrip(); - const res = await postJson("/notepad/image/delete?tab=" + entry.tab, { id: entry.id }); + const res = await postJson("notepad/image/delete?tab=" + entry.tab, { id: entry.id }); entry.deleting = false; // The tab was left (or deleted) while this was out: nothing here to update. if (!live(entry)) return; diff --git a/src/web-console/public/screens/review-loop-setup.js b/src/web-console/public/screens/review-loop-setup.js index 1aae9bf..74018bc 100644 --- a/src/web-console/public/screens/review-loop-setup.js +++ b/src/web-console/public/screens/review-loop-setup.js @@ -42,7 +42,7 @@ export async function openReviewLoopSetup(spec) { const mine = page.reviewLoopSetup; let res; try { - res = await fetch("/review-loop-setup?facts=1" + (dir ? "&spec=" + encodeURIComponent(dir) : ""), { cache: "no-store" }); + res = await fetch("review-loop-setup?facts=1" + (dir ? "&spec=" + encodeURIComponent(dir) : ""), { cache: "no-store" }); } catch { res = null; } @@ -97,7 +97,7 @@ function ensureResolved(s) { s.facts.resolved = null; return; } - fetch("/review-loop-setup?agent=" + encodeURIComponent(agent), { cache: "no-store" }) + fetch("review-loop-setup?agent=" + encodeURIComponent(agent), { cache: "no-store" }) .then((res) => (res.ok ? res.json() : null)) .catch(() => null) .then((answer) => { @@ -371,7 +371,7 @@ async function saveNotify(s) { if (url === (facts.notifyUrl || "") && f.notifyKind === (facts.notifyKind || "query") && param === (facts.notifyParam || "message")) return ""; let current = null; try { - const res = await fetch("/loop-setup", { cache: "no-store" }); + const res = await fetch("loop-setup", { cache: "no-store" }); current = res.ok ? await res.json() : null; } catch { current = null; @@ -379,7 +379,7 @@ async function saveNotify(s) { if (!current) return "The notification address could not be saved. Try again."; // The loop's own screen drops these two before it saves; the store rejects them as unknown fields. const { remembered, saved, ...entry } = current; - const { status, body } = await postJson("/loop-setup", { ...entry, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param }); + const { status, body } = await postJson("loop-setup", { ...entry, notifyKind: f.notifyKind, notifyUrl: url, notifyParam: param }); if (status !== 200 || !body || body.ok !== true) { return Array.isArray(body && body.problems) && body.problems.length ? body.problems.join(" ") : "The notification address could not be saved. Try again."; } @@ -420,7 +420,7 @@ async function startReviewLoop(s) { redraw(); return; } - const { status, body } = await postJson("/review-loop-setup", reviewSetupBody(f)); + const { status, body } = await postJson("review-loop-setup", reviewSetupBody(f)); if (page.reviewLoopSetup !== s) return; if (status !== 200 || !body || body.ok !== true) { s.starting = false; diff --git a/src/web-console/public/screens/setup.js b/src/web-console/public/screens/setup.js index 51bba45..96796ff 100644 --- a/src/web-console/public/screens/setup.js +++ b/src/web-console/public/screens/setup.js @@ -54,7 +54,7 @@ async function onStart(entry) { page.local.setupStart = { id: entry.id, label, at: Date.now() }; saveNow(); try { - const res = await fetch("/submit", { + const res = await fetch("submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [{ i: "__start", type: "start", agent: entry.id }], reply: "Start with " + label }), diff --git a/src/web-console/public/screens/workspace.js b/src/web-console/public/screens/workspace.js index 18b571d..0cff71d 100644 --- a/src/web-console/public/screens/workspace.js +++ b/src/web-console/public/screens/workspace.js @@ -54,7 +54,7 @@ export async function syncWorkspaceScope(spec) { page.scopeMine = want; if ((page.wsFrame.scope || "") === want || scopeAsked === want) return; scopeAsked = want; - const { status, body } = await postJson("/workspace/scope", { spec: want }); + const { status, body } = await postJson("workspace/scope", { spec: want }); if (status === 200 && body && Array.isArray(body.folders)) page.wsFrame = { ...page.wsFrame, ...body }; scopeAsked = null; if ($("workspace-modal").open) renderWorkspace(); @@ -83,7 +83,7 @@ let wsBusy = false; export async function openWorkspace() { const dlg = $("workspace-modal"); try { - const res = await fetch("/workspace?check=1", { cache: "no-store" }); + const res = await fetch("workspace?check=1", { cache: "no-store" }); if (res.ok) page.wsFrame = await res.json(); } catch {} wsConfirm = null; @@ -203,7 +203,7 @@ function workspaceField(f, field, labelText) { input.value = saved(); return showError(""); } - const { status, body } = await postJson("/workspace/edit", { id: f.id, [field]: value }); + const { status, body } = await postJson("workspace/edit", { id: f.id, [field]: value }); // An earlier "Added as @x" is out of date once the list moves on. if (status === 200) { setAddMsg(""); @@ -271,7 +271,7 @@ function paintWorkspaceRow(li, f) { go.type = "button"; go.addEventListener("click", async () => { go.disabled = true; - const { status } = await postJson("/workspace/remove", { id: f.id }); + const { status } = await postJson("workspace/remove", { id: f.id }); wsConfirm = null; if (status === 200) setAddMsg(""); if (status !== 200) setAddMsg(`@${f.name} could not be removed. Try again.`, "error"); @@ -290,7 +290,7 @@ async function addWorkspaceFolder(path, name) { if (!trimmed || wsBusy || loopDriving()) return; wsBusy = true; $("workspace-add").disabled = true; - const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed }); + const { status, body } = await postJson("workspace/add", name ? { path: trimmed, name } : { path: trimmed }); wsBusy = false; $("workspace-add").disabled = false; if (status === 200) { @@ -327,7 +327,7 @@ async function browseWorkspace() { if (b.disabled || loopDriving()) return; b.disabled = true; setAddMsg("Waiting for the folder picker…"); - const { status, body } = await postJson("/workspace/browse", {}); + const { status, body } = await postJson("workspace/browse", {}); b.disabled = false; if (status === 200 && body.path) { setAddMsg(""); diff --git a/src/web-console/public/selectors.js b/src/web-console/public/selectors.js index c839e91..7021cad 100644 --- a/src/web-console/public/selectors.js +++ b/src/web-console/public/selectors.js @@ -342,7 +342,7 @@ export function specFileTabs() { async function fetchSpecFile(spec, kind) { try { - const res = await fetch("/overview?spec=" + encodeURIComponent(spec) + "&file=" + kind, { cache: "no-store" }); + const res = await fetch("overview?spec=" + encodeURIComponent(spec) + "&file=" + kind, { cache: "no-store" }); if (res.status !== 200) return null; const file = decodeURIComponent(res.headers.get("x-spec-file") || "") || kind; return { file, text: await res.text() }; @@ -382,7 +382,7 @@ export const prototypesTabShown = () => page.prototypes.key === overviewSpec() & async function fetchPrototypeList(spec) { try { - const res = await fetch("/prototypes?spec=" + encodeURIComponent(spec), { cache: "no-store" }); + const res = await fetch("prototypes?spec=" + encodeURIComponent(spec), { cache: "no-store" }); if (res.status !== 200) return []; const body = await res.json(); return Array.isArray(body.files) ? body.files : []; @@ -393,7 +393,7 @@ async function fetchPrototypeList(spec) { async function fetchPrototypeDoc(spec, name) { try { - const res = await fetch("/prototype?spec=" + encodeURIComponent(spec) + "&name=" + encodeURIComponent(name), { cache: "no-store" }); + const res = await fetch("prototype?spec=" + encodeURIComponent(spec) + "&name=" + encodeURIComponent(name), { cache: "no-store" }); return res.status === 200 ? await res.text() : null; } catch { return null; @@ -437,7 +437,7 @@ export async function loadSpecCarry() { if (specCarryAsked || !isDashboard() || !scan() || page.local.specSel !== undefined) return; specCarryAsked = true; try { - const res = await fetch("/spec-carry", { method: "POST", cache: "no-store" }); + const res = await fetch("spec-carry", { method: "POST", cache: "no-store" }); const { spec } = res.status === 200 ? await res.json() : {}; if (!spec || page.local.specSel !== undefined || !specList().some((s) => s.dir === spec)) return; page.local.specSel = spec; @@ -458,7 +458,7 @@ export const agentsTabShown = () => isDashboard() && typeof page.agentsDoc.texts // keep its text; null when it is not there. Off the dashboard nothing is read. async function fetchAgentsDoc(rel) { try { - const res = await fetch("/agents-doc?file=" + encodeURIComponent(rel), { cache: "no-store" }); + const res = await fetch("agents-doc?file=" + encodeURIComponent(rel), { cache: "no-store" }); return res.status === 200 ? await res.text() : null; } catch { return null; diff --git a/src/web-console/public/sound.js b/src/web-console/public/sound.js index 527f269..1769a99 100644 --- a/src/web-console/public/sound.js +++ b/src/web-console/public/sound.js @@ -39,7 +39,7 @@ export const soundOn = (event) => looks.sound && looks[soundKey(event)]; const soundPath = (event) => PICKABLE_SOUNDS.includes(event) && looks[soundFileKey(event)] ? `sounds/${looks[soundFileKey(event)]}` : SOUND_EVENTS[event].file; -const audioFor = (path) => (SOUNDS[path] ||= new Audio(`/${path}.mp3`)); +const audioFor = (path) => (SOUNDS[path] ||= new Audio(`${path}.mp3`)); // The Audio a cue last played, so a pick changed mid-sound still stops the right one. const soundAudio = (event) => SOUNDS[playingPath[event] || soundPath(event)]; diff --git a/src/web-console/public/uploads.js b/src/web-console/public/uploads.js index f2934b6..e1ccf60 100644 --- a/src/web-console/public/uploads.js +++ b/src/web-console/public/uploads.js @@ -26,8 +26,8 @@ import { step } from "./notepad.js"; export const CHAT_IMAGES = "__chat"; // An upload's server path is `/uploads/.`; the page serves -// it at /uploads/.. -export const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop(); +// it at uploads/., relative to itself. +export const uploadUrl = (img) => img.url || "uploads/" + String(img.path || "").split(/[\\/]/).pop(); // A page with its corner folded, drawn inline: the CSP allows no icon font. function pageIcon() { @@ -236,7 +236,7 @@ function setNoteImages(itemId, list) { // Where an attachment is deleted from. Documents have no `url`, so their // route is built from the path, as uploadUrl does. -export const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop(); +export const deleteUrl = (entry) => entry.url || "uploads/" + String(entry.path || "").split(/[\\/]/).pop(); // The files in a paste worth attaching: images and allowed documents. A paste // with none of them is left to paste as text. @@ -258,7 +258,7 @@ async function uploadBlob(itemId, key, blob) { let body = null; let status = 0; try { - const res = await fetch("/upload", { + const res = await fetch("upload", { method: "POST", headers: { "content-type": isFile ? "application/octet-stream" : "image/jpeg", diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index 56677c6..0816187 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -1430,7 +1430,8 @@ function upload(req, res, ctx) { id, kind: "image", path: file, - url: "/uploads/" + id + ".jpg", + // Page-relative, for the macOS app's frame prefix (takeFramePrefix). + url: "uploads/" + id + ".jpg", name: uploadLabel(req, "image.jpg"), size: buf.length, });