Make every URL the console page uses page-relative, guarded by a source test

AI Assisted
This commit is contained in:
Seth committed 2026-12-05 00:10:44 -08:00
1 parent 4ced32be5c
commit 1d007737b1
47 files changed
+401 -202

No files matched your search

@@ -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. - **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. - **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 `<link rel="modulepreload">` 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. **Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` 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.
+1 -1
View File
@@ -18,7 +18,7 @@
"pretest": "node scripts/fix-line-endings.mjs", "pretest": "node scripts/fix-line-endings.mjs",
"test:fast": "node scripts/test-fast.mjs", "test:fast": "node scripts/test-fast.mjs",
"test:page": "node scripts/run-page-tests.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" "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": { "devDependencies": {
+1
View File
@@ -43,6 +43,7 @@
"test-web-console-diff-parse.mjs", "test-web-console-diff-parse.mjs",
"test-web-console-git-board.mjs", "test-web-console-git-board.mjs",
"test-web-console-prototypes.mjs", "test-web-console-prototypes.mjs",
"test-web-console-relative-urls.mjs",
"test-web-console-send-state.mjs", "test-web-console-send-state.mjs",
"test-web-console-shape.mjs", "test-web-console-shape.mjs",
"test-web-console-skills.mjs", "test-web-console-skills.mjs",
+1 -1
View File
@@ -52,6 +52,6 @@ test("it asks once per page", async () => {
await load(); await load();
await load(); await load();
assert.equal(calls.length, 1); assert.equal(calls.length, 1);
assert.deepEqual(calls[0], ["/spec-carry", "POST"]); assert.deepEqual(calls[0], ["spec-carry", "POST"]);
assert.equal(typeof loadSpecCarry, "function"); assert.equal(typeof loadSpecCarry, "function");
}); });
+1 -1
View File
@@ -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"); assert.equal(ACTIVITIES[12].title, "Flock Dash");
for (const a of ACTIVITIES) { for (const a of ACTIVITIES) {
assert.ok(Object.isFrozen(a), `${a.id} is frozen`); 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.equal(typeof a.title, "string");
assert.ok(typeof a.blurb === "string" && a.blurb.length > 10, `${a.id} has a line for its picker card`); assert.ok(typeof a.blurb === "string" && a.blurb.length > 10, `${a.id} has a line for its picker card`);
} }
+1 -1
View File
@@ -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 core = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "core.js"), "utf8");
const wire = core.slice(core.indexOf("export function wireChrome()")); const wire = core.slice(core.indexOf("export function wireChrome()"));
const pagehide = wire.slice(0, wire.indexOf("});")); 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"); assert.doesNotMatch(core, /navigator\.sendBeacon\(/, "no beacon call left anywhere in the page's core");
}); });
+1 -1
View File
@@ -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 dir = path.join(path.dirname(CONSOLE_CLI), "public");
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8"); const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "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"); 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(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"); assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
+1 -1
View File
@@ -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, "the pill sits in .ident");
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"')); 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"]) { 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. // The CSP refuses style attributes and inline script: the new markup has neither.
const added = [ const added = [
+18 -13
View File
@@ -144,14 +144,14 @@ test("pictures: JPEG only, listed oldest first, with thumbnails when sent", () =
const first = addImage(folder, tab, JPEG); const first = addImage(folder, tab, JPEG);
const second = addImage(folder, tab, JPEG); const second = addImage(folder, tab, JPEG);
assert.match(first.id, IMAGE_ID_RE); 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. // Make the order unambiguous: the first is older.
const older = new Date(Date.now() - 60_000); const older = new Date(Date.now() - 60_000);
fs.utimesSync(path.join(tabDir(folder, tab), "images", first.id + ".jpg"), older, older); fs.utimesSync(path.join(tabDir(folder, tab), "images", first.id + ".jpg"), older, older);
addThumb(folder, tab, second.id, JPEG); addThumb(folder, tab, second.id, JPEG);
assert.deepEqual(readNotepad(folder).images, [ assert.deepEqual(readNotepad(folder).images, [
{ id: first.id, url: first.url, thumb: null }, { 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], [U1, U2],
"oldest first", "oldest first",
); );
assert.equal(read.images[0].url, `/notepad/images/${LEGACY_TAB_ID}/${U1}.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[0].thumb, `notepad/images/${LEGACY_TAB_ID}/${U1}.thumb.jpg`);
assert.equal(read.images[1].thumb, null); assert.equal(read.images[1].thumb, null);
assert.deepEqual(listTabs(folder), { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID }); 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"); 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"); const f2 = freshFolder("legacy");
legacyNotepad(f2); legacyNotepad(f2);
const added = addImage(f2, LEGACY_TAB_ID, JPEG); 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); assert.equal(readNotepad(f2).images.length, 3);
// A first-shape notepad with a picture and no note still migrates. // A first-shape notepad with a picture and no note still migrates.
const f3 = freshFolder("legacy"); 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); const up = await postJpeg(s, "/notepad/image", JPEG);
assert.equal(up.status, 200); 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); assert.match(id, IMAGE_ID_RE);
const unknownThumb = await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG); 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.text, "old note\n");
assert.equal(res.body.images.length, 2); assert.equal(res.body.images.length, 2);
assert.deepEqual(treeOf(dir), before, "the read wrote nothing"); 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"); 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. // 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); 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); const up = await postJpeg(s, `/notepad/image?tab=${a}`, JPEG);
assert.equal(up.status, 200); assert.equal(up.status, 200);
const { id, url } = await up.json(); 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 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); 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. // 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/${b}/${id}.jpg`)).status, 404);
assert.equal((await get(`/notepad/images/${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.equal((await get(`/notepad/images/ffffffffffff/${id}.jpg`)).status, 404);
assert.deepEqual((await getJson(s, `/notepad?tab=${b}`)).body.images, []); 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. // 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); const stray = await postJpeg(s, "/notepad/image?tab=ffffffffffff", JPEG);
assert.equal(stray.status, 404); 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 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=${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 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 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. // With no tab named, the picture goes to the last tab used.
const unnamed = await (await postJpeg(s, "/notepad/image", JPEG)).json(); 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.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" }); assert.deepEqual(await (await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG)).json(), { error: "not-found" });
}); });
+3 -2
View File
@@ -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 tabNamed(s, "Ideas").click();
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1); await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li.is-ready").length === 1);
const src = await s.page.locator("#notepad-strip img").getAttribute("src"); 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. // A save that cannot reach the server keeps you on the tab, with why.
await s.page.route("**/notepad/text*", (route) => route.abort()); 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 }); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s); await openNotepad(s);
for (const color of ["#c33", "#3c3", "#33c"]) await addViaButton(s, color); 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 = () => const shown = () =>
s.page.evaluate(() => ({ s.page.evaluate(() => ({
src: new URL(document.getElementById("picview-img").src).pathname, src: new URL(document.getElementById("picview-img").src).pathname,
+1 -1
View File
@@ -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, /realpathSync/);
assert.match(kept, /path\.dirname\(real\)\.toLowerCase\(\) !== realDir\.toLowerCase\(\)/, "only files directly in attachments/"); 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"); 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, /function isComment\(t\)/, "HTML comments are not shown");
assert.match(render, /"!": \{ mark: "!", label: "blocked"/, "a blocked task gets its marker"); assert.match(render, /"!": \{ mark: "!", label: "blocked"/, "a blocked task gets its marker");
}); });
+182
View File
@@ -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/<key>/`, 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/<key>/, 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 `/`
* (`` `<img src="/x">` ``). 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 = `<img src="/uploads/${id}.jpg">`;'), ['`<img src="/uploads/${id}.jpg">`']);
assert.deepEqual(found("h = '<a href=\\'/state\\'>'; s = \"<img src=\\\"/x.png\\\">\";").length, 2);
assert.deepEqual(found('h = `<img src="uploads/${id}.jpg"><a href="//cdn/x">`'), []);
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('<link href="/app.css" /><script src="app.js"></script>'), [{ line: 1, literal: "/app.css" }]);
assert.deepEqual(htmlUrls("<img src='/x.png' srcset=\"/y.png 2x\">"), [
{ 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`);
}
});
+1 -1
View File
@@ -83,7 +83,7 @@ test("the page carries its first state, title and badge, so the first paint need
assert.ok(html.includes(`<h1 id="title">Lunch &lt;/script&gt;&lt;script&gt;alert(1)&lt;/script&gt; $&amp; $&#39; app</h1>`)); assert.ok(html.includes(`<h1 id="title">Lunch &lt;/script&gt;&lt;script&gt;alert(1)&lt;/script&gt; $&amp; $&#39; app</h1>`));
assert.ok(html.includes('<span class="pill is-accent is-caps badge" id="badge">Building</span>')); assert.ok(html.includes('<span class="pill is-accent is-caps badge" id="badge">Building</span>'));
assert.ok(html.includes("Starting Implement"), "the static starting screen names the skill"); 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"]); cli(["stop", "--session", res.json.sid, "--force"]);
}); });
+7 -5
View File
@@ -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]); assert.deepEqual([...bytes.slice(0, 4)], [0x89, 0x50, 0x4e, 0x47]);
const html = await (await fetch(baseUrl + "/", { headers: { cookie: cookieFor(baseUrl, token) } })).text(); 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.svg"'));
assert.ok(html.includes('href="/favicon.png"')); assert.ok(html.includes('href="favicon.png"'));
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/); 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"); const uploads = path.join(fs.realpathSync.native(session), "uploads");
assert.equal(path.dirname(file).toLowerCase(), uploads.toLowerCase()); assert.equal(path.dirname(file).toLowerCase(), uploads.toLowerCase());
assert.equal(path.basename(file), id + ".jpg"); 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(name, "../../evil name.png", "the name comes back as a label");
assert.equal(res.json.kind, "image"); assert.equal(res.json.kind, "image");
assert.equal(res.json.size, JPEG.length); 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 () => { 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); const res = await raw("GET", url);
assert.equal(res.status, 200); assert.equal(res.status, 200);
assert.equal(res.headers["content-type"], "image/jpeg"); 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 () => { 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.equal((await raw("DELETE", url, undefined, { origin: "http://evil.example.com" })).status, 403);
assert.ok(fs.existsSync(file)); assert.ok(fs.existsSync(file));
assert.equal((await raw("DELETE", url)).status, 204); assert.equal((await raw("DELETE", url)).status, 204);
+1 -1
View File
@@ -516,7 +516,7 @@ test("prefs: the new modules are served and preloaded, and Preferences' styles l
"screens/agents/agents-form.js", "screens/agents/agents-form.js",
]) { ]) {
assert.ok(SERVABLE.has(m), `${m} is servable`); 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"]) { for (const sheet of ["styles/prefs.css", "styles/agents.css"]) {
const css = publicSource(sheet); const css = publicSource(sheet);
+3 -3
View File
@@ -497,7 +497,7 @@ test("music: a song plays from its file, fades in toward its level, says when it
withSongs(async () => { withSongs(async () => {
const [name] = TRAILS_TRACKS; const [name] = TRAILS_TRACKS;
assert.equal(music(name, 1, 1, { restart: true }), "playing"); 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, "an element for the song's file");
assert.ok(!el.paused && el.plays === 1, "it plays"); assert.ok(!el.paused && el.plays === 1, "it plays");
for (let i = 0; i < 20; i++) { 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 () => { withSongs(async () => {
const [first, second] = TRAILS_TRACKS; const [first, second] = TRAILS_TRACKS;
music(first, 1, 0.5); 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; const loads = el.loads;
await sleep(800); await sleep(800);
assert.ok(el.paused, "paused once it stops being asked for"); 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); assert.equal(music(name, 1, 0), undefined);
globalThis.Audio = undefined; globalThis.Audio = undefined;
assert.equal(music(name, 1, 1), 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", () => { test("music: every Sunset Drive road has a song, and every song is a real track", () => {
+3 -1
View File
@@ -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)); 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 * The tabs, as `[{ id, name, sent? }]` in order (`sent` only on a tab sent
+2 -2
View File
@@ -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 // 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. // 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([ export const ACTIVITIES = Object.freeze([
entry("snake", "Snake", "Eat, grow and dodge. Every level brings something new.", { music: 70 }), 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("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("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("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 }), entry("flock", "Flock Dash", "Lead your flock through the sunset sky. Dodge everything, keep the line.", { music: 70 }),
]); ]);
+1 -1
View File
@@ -65,7 +65,7 @@ async function askAgain(button, status, reply) {
button.disabled = true; button.disabled = true;
button.textContent = "Asking…"; button.textContent = "Asking…";
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [{ i: "__changes", type: "changes" }], reply }), body: JSON.stringify({ actions: [{ i: "__changes", type: "changes" }], reply }),
+7 -4
View File
@@ -14,7 +14,7 @@ export function blockBody(b, doc) {
if (typeof b.image !== "string") return md(b.md, "md"); if (typeof b.image !== "string") return md(b.md, "md");
const fig = el("figure", "doc-figure"); const fig = el("figure", "doc-figure");
const img = el("img", "doc-img"); 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 // The caption already says it: an alt repeating it is read twice, and shows
// twice in an export whose picture would not load. // twice in an export whose picture would not load.
img.alt = ""; 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 // 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 // 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 // meant to be shared. A remote image keeps its own address; anything else on
// this origin becomes its alt text. // this origin becomes its alt text. Matched on the path below the page's own
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; // 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) { function imageToAlt(img) {
const alt = img.getAttribute("alt") || ""; const alt = img.getAttribute("alt") || "";
@@ -148,7 +149,9 @@ async function inlineImage(img) {
img.setAttribute("src", url.href); img.setAttribute("src", url.href);
return; 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 { try {
const res = await fetch(url); const res = await fetch(url);
if (!res.ok) throw new Error(String(res.status)); if (!res.ok) throw new Error(String(res.status));
+2 -2
View File
@@ -69,8 +69,8 @@ export function setFavicon(state) {
const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]'); const svgLink = document.querySelector('link[rel="icon"][type="image/svg+xml"]');
const pngLink = document.querySelector('link[rel="icon"][type="image/png"]'); const pngLink = document.querySelector('link[rel="icon"][type="image/png"]');
if (state === "plain") { if (state === "plain") {
if (svgLink) svgLink.href = "/favicon.svg"; if (svgLink) svgLink.href = "favicon.svg";
if (pngLink) pngLink.href = "/favicon.png"; if (pngLink) pngLink.href = "favicon.png";
return; return;
} }
const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state)); const url = "data:image/svg+xml," + encodeURIComponent(faviconSvg(state));
+65 -65
View File
@@ -5,74 +5,74 @@
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" /> <meta name="color-scheme" content="light dark" />
<title>Plan2Code Console</title> <title>Plan2Code Console</title>
<link rel="stylesheet" href="/app.css" /> <link rel="stylesheet" href="app.css" />
<!-- Every module up front. Without these the browser finds render.js and <!-- Every module up front. Without these the browser finds render.js and
answers.js only once app.js has arrived and been parsed, and marked answers.js only once app.js has arrived and been parsed, and marked
only once render.js has: three round trips in a row before the page only once render.js has: three round trips in a row before the page
can draw anything real. --> can draw anything real. -->
<link rel="modulepreload" href="/app.js" /> <link rel="modulepreload" href="app.js" />
<link rel="modulepreload" href="/answers.js" /> <link rel="modulepreload" href="answers.js" />
<link rel="modulepreload" href="/skills.js" /> <link rel="modulepreload" href="skills.js" />
<link rel="modulepreload" href="/spec-states.js" /> <link rel="modulepreload" href="spec-states.js" />
<link rel="modulepreload" href="/state.js" /> <link rel="modulepreload" href="state.js" />
<link rel="modulepreload" href="/doc-files.js" /> <link rel="modulepreload" href="doc-files.js" />
<link rel="modulepreload" href="/diff-view.js" /> <link rel="modulepreload" href="diff-view.js" />
<link rel="modulepreload" href="/diff-parse.js" /> <link rel="modulepreload" href="diff-parse.js" />
<link rel="modulepreload" href="/send-state.js" /> <link rel="modulepreload" href="send-state.js" />
<link rel="modulepreload" href="/mention-box.js" /> <link rel="modulepreload" href="mention-box.js" />
<link rel="modulepreload" href="/uploads.js" /> <link rel="modulepreload" href="uploads.js" />
<link rel="modulepreload" href="/sound.js" /> <link rel="modulepreload" href="sound.js" />
<link rel="modulepreload" href="/looks.js" /> <link rel="modulepreload" href="looks.js" />
<link rel="modulepreload" href="/selectors.js" /> <link rel="modulepreload" href="selectors.js" />
<link rel="modulepreload" href="/screens/core.js" /> <link rel="modulepreload" href="screens/core.js" />
<link rel="modulepreload" href="/screens/ending.js" /> <link rel="modulepreload" href="screens/ending.js" />
<link rel="modulepreload" href="/screens/docs.js" /> <link rel="modulepreload" href="screens/docs.js" />
<link rel="modulepreload" href="/screens/cards.js" /> <link rel="modulepreload" href="screens/cards.js" />
<link rel="modulepreload" href="/screens/starting.js" /> <link rel="modulepreload" href="screens/starting.js" />
<link rel="modulepreload" href="/screens/dashboard.js" /> <link rel="modulepreload" href="screens/dashboard.js" />
<link rel="modulepreload" href="/screens/git-host.js" /> <link rel="modulepreload" href="screens/git-host.js" />
<link rel="modulepreload" href="/screens/looks.js" /> <link rel="modulepreload" href="screens/looks.js" />
<link rel="modulepreload" href="/screens/prefs-dialog.js" /> <link rel="modulepreload" href="screens/prefs-dialog.js" />
<link rel="modulepreload" href="/screens/agents-view.js" /> <link rel="modulepreload" href="screens/agents-view.js" />
<link rel="modulepreload" href="/screens/agents/agents-data.js" /> <link rel="modulepreload" href="screens/agents/agents-data.js" />
<link rel="modulepreload" href="/screens/agents/agents-list-editor.js" /> <link rel="modulepreload" href="screens/agents/agents-list-editor.js" />
<link rel="modulepreload" href="/screens/agents/agents-summary.js" /> <link rel="modulepreload" href="screens/agents/agents-summary.js" />
<link rel="modulepreload" href="/screens/agents/agents-form.js" /> <link rel="modulepreload" href="screens/agents/agents-form.js" />
<link rel="modulepreload" href="/screens/agents/agents-strengths.js" /> <link rel="modulepreload" href="screens/agents/agents-strengths.js" />
<link rel="modulepreload" href="/strengths.js" /> <link rel="modulepreload" href="strengths.js" />
<link rel="modulepreload" href="/screens/cleanup.js" /> <link rel="modulepreload" href="screens/cleanup.js" />
<link rel="modulepreload" href="/screens/help-dialog.js" /> <link rel="modulepreload" href="screens/help-dialog.js" />
<link rel="modulepreload" href="/screens/workspace.js" /> <link rel="modulepreload" href="screens/workspace.js" />
<link rel="modulepreload" href="/screens/ask.js" /> <link rel="modulepreload" href="screens/ask.js" />
<link rel="modulepreload" href="/screens/notepad.js" /> <link rel="modulepreload" href="screens/notepad.js" />
<link rel="modulepreload" href="/screens/activities.js" /> <link rel="modulepreload" href="screens/activities.js" />
<link rel="modulepreload" href="/screens/setup.js" /> <link rel="modulepreload" href="screens/setup.js" />
<link rel="modulepreload" href="/activities.js" /> <link rel="modulepreload" href="activities.js" />
<link rel="modulepreload" href="/tones.js" /> <link rel="modulepreload" href="tones.js" />
<link rel="modulepreload" href="/net.js" /> <link rel="modulepreload" href="net.js" />
<link rel="modulepreload" href="/render.js" /> <link rel="modulepreload" href="render.js" />
<link rel="modulepreload" href="/palette.js" /> <link rel="modulepreload" href="palette.js" />
<link rel="modulepreload" href="/labels.js" /> <link rel="modulepreload" href="labels.js" />
<link rel="modulepreload" href="/boot.js" /> <link rel="modulepreload" href="boot.js" />
<link rel="modulepreload" href="/chat.js" /> <link rel="modulepreload" href="chat.js" />
<link rel="modulepreload" href="/help.js" /> <link rel="modulepreload" href="help.js" />
<link rel="modulepreload" href="/tabs.js" /> <link rel="modulepreload" href="tabs.js" />
<link rel="modulepreload" href="/prefs.js" /> <link rel="modulepreload" href="prefs.js" />
<link rel="modulepreload" href="/starters.js" /> <link rel="modulepreload" href="starters.js" />
<link rel="modulepreload" href="/workspace.js" /> <link rel="modulepreload" href="workspace.js" />
<link rel="modulepreload" href="/meter.js" /> <link rel="modulepreload" href="meter.js" />
<link rel="modulepreload" href="/subagents.js" /> <link rel="modulepreload" href="subagents.js" />
<link rel="modulepreload" href="/mentions.js" /> <link rel="modulepreload" href="mentions.js" />
<link rel="modulepreload" href="/favicon.js" /> <link rel="modulepreload" href="favicon.js" />
<link rel="modulepreload" href="/app-bridge.js" /> <link rel="modulepreload" href="app-bridge.js" />
<link rel="modulepreload" href="/git-board.js" /> <link rel="modulepreload" href="git-board.js" />
<link rel="modulepreload" href="/git-board-view.js" /> <link rel="modulepreload" href="git-board-view.js" />
<link rel="modulepreload" href="/pr-url.js" /> <link rel="modulepreload" href="pr-url.js" />
<link rel="modulepreload" href="/vendor/marked.esm.js" /> <link rel="modulepreload" href="vendor/marked.esm.js" />
<link rel="modulepreload" href="/notepad.js" /> <link rel="modulepreload" href="notepad.js" />
<link rel="modulepreload" href="/notepad-tabs.js" /> <link rel="modulepreload" href="notepad-tabs.js" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="favicon.svg" />
<link rel="icon" type="image/png" sizes="192x192" href="/favicon.png" /> <link rel="icon" type="image/png" sizes="192x192" href="favicon.png" />
</head> </head>
<body> <body>
<a class="skip" href="#main">Skip to the questions</a> <a class="skip" href="#main">Skip to the questions</a>
@@ -4653,6 +4653,6 @@
</footer> </footer>
<!-- p2c:boot --> <!-- p2c:boot -->
<script type="module" src="/app.js"></script> <script type="module" src="app.js"></script>
</body> </body>
</html> </html>
+2 -2
View File
@@ -139,7 +139,7 @@ export async function syncLooks() {
if (boot && "looks" in boot) saved = boot.looks ? { looks: boot.looks } : null; if (boot && "looks" in boot) saved = boot.looks ? { looks: boot.looks } : null;
else { else {
try { try {
const res = await fetch("/looks"); const res = await fetch("looks");
if (res.ok) saved = await res.json(); if (res.ok) saved = await res.json();
} catch {} } catch {}
} }
@@ -184,7 +184,7 @@ function pushLooks() {
undo(); undo();
return { ok: false, error: error || "Could not save." }; return { ok: false, error: error || "Could not save." };
}; };
return fetch("/looks", { return fetch("looks", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify(body), body: JSON.stringify(body),
+1 -1
View File
@@ -61,7 +61,7 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
host.className = "md-host" + (className ? " " + className : ""); host.className = "md-host" + (className ? " " + className : "");
if (id) host.id = id; if (id) host.id = id;
const root = host.attachShadow({ mode: "open" }); 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"); const link = document.createElement("link");
link.rel = "stylesheet"; link.rel = "stylesheet";
link.href = href; link.href = href;
+1 -1
View File
@@ -413,7 +413,7 @@ let songTicker = null;
function songElement(name) { function songElement(name) {
if (!songAudio.has(name)) { if (!songAudio.has(name)) {
const el = new Audio(`/${SONGS[name]}`); const el = new Audio(SONGS[name]);
el.preload = "auto"; el.preload = "auto";
el.volume = 0; el.volume = 0;
songAudio.set(name, el); songAudio.set(name, el);
+1 -1
View File
@@ -208,7 +208,7 @@ export function makeCodeMirrorEditor(parent, { onChange, label }) {
const root = host.attachShadow({ mode: "open" }); const root = host.attachShadow({ mode: "open" });
const sheet = document.createElement("link"); const sheet = document.createElement("link");
sheet.rel = "stylesheet"; sheet.rel = "stylesheet";
sheet.href = "/notepad-editor.css"; sheet.href = "notepad-editor.css";
const mount = document.createElement("div"); const mount = document.createElement("div");
mount.className = "notepad-cm"; mount.className = "notepad-cm";
root.append(sheet, mount); root.append(sheet, mount);
+1 -1
View File
@@ -73,7 +73,7 @@ function safeHref(href) {
if (!href) return null; if (!href) return null;
const trimmed = String(href).trim(); const trimmed = String(href).trim();
const kept = KEPT_ATTACHMENT.exec(trimmed); 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 // 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. // protocol-relative `//host` (or `/\host`), which leaves the page for another site.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null; return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
+3 -1
View File
@@ -654,7 +654,9 @@ async function loadGame(entry) {
if (games.has(entry.id)) return games.get(entry.id); if (games.has(entry.id)) return games.get(entry.id);
if (!loading.has(entry.id)) { if (!loading.has(entry.id)) {
const made = (async () => { 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); defs.set(entry.id, def);
if (def.lowerIsBetter) lowerIsBetter.add(entry.id); if (def.lowerIsBetter) lowerIsBetter.add(entry.id);
else lowerIsBetter.delete(entry.id); else lowerIsBetter.delete(entry.id);
+10 -10
View File
@@ -306,7 +306,7 @@ export function mountAgentsView(container, opts = {}) {
let state = ctx.templateState.get(command) || "unknown"; let state = ctx.templateState.get(command) || "unknown";
if (state === "unknown") { if (state === "unknown") {
try { try {
const res = await fetch("/agents/test", { const res = await fetch("agents/test", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ command }), body: JSON.stringify({ command }),
@@ -337,7 +337,7 @@ export function mountAgentsView(container, opts = {}) {
rows.map(async (row) => { rows.map(async (row) => {
let state = "unknown"; let state = "unknown";
try { try {
const res = await fetch("/agents/test", { const res = await fetch("agents/test", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ command: row.command }), 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. // The command's Test: where it would run from. Never saves.
async function testCommand(command) { async function testCommand(command) {
try { try {
const res = await fetch("/agents/test", { const res = await fetch("agents/test", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ command }), body: JSON.stringify({ command }),
@@ -373,7 +373,7 @@ export function mountAgentsView(container, opts = {}) {
// press is the one failure the status line gets. // press is the one failure the status line gets.
async function useFromHere(entry) { async function useFromHere(entry) {
try { try {
const res = await fetch("/agents/use-path", { const res = await fetch("agents/use-path", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ id: entry.id }), 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 modelIds = [...ctx.saved.shipped[cli], ...sent].map((m) => m.id);
const payload = { models: { ...ctx.saved.user, [cli]: sent } }; const payload = { models: { ...ctx.saved.user, [cli]: sent } };
if (ctx.modelsLoaded) payload.strengths = strengthsToSend(cli, key, modelIds); 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) { if (!res.ok) {
formMark({ ok: false, error: body.error || "Could not save." }); formMark({ ok: false, error: body.error || "Could not save." });
return false; return false;
@@ -465,7 +465,7 @@ export function mountAgentsView(container, opts = {}) {
const agents = ctx.saved.agents.map((a) => cleanAgent(a)); const agents = ctx.saved.agents.map((a) => cleanAgent(a));
agents.splice(at, isNew ? 0 : 1, cleanAgent(draft)); agents.splice(at, isNew ? 0 : 1, cleanAgent(draft));
try { 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) { if (res.status === 409) {
ctx.formError = { field: null, error: body.error || "Not saved." }; ctx.formError = { field: null, error: body.error || "Not saved." };
ctx.formReplace = Array.isArray(body.warnings) ? body.warnings : []; ctx.formReplace = Array.isArray(body.warnings) ? body.warnings : [];
@@ -504,7 +504,7 @@ export function mountAgentsView(container, opts = {}) {
return false; return false;
}; };
try { 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."); if (!res.ok) return strengthsFailed(body.error || "Saved, but the strengths could not be.");
ctx.saved.strengths.user = body.strengths || {}; ctx.saved.strengths.user = body.strengths || {};
} catch { } catch {
@@ -526,7 +526,7 @@ export function mountAgentsView(container, opts = {}) {
const agents = ctx.saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent); const agents = ctx.saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent);
ctx.confirming = false; ctx.confirming = false;
try { try {
const { res, body } = await postJson("/agents", { agents }); const { res, body } = await postJson("agents", { agents });
if (!res.ok) { if (!res.ok) {
ctx.formError = { field: null, error: body.error || "Could not delete." }; ctx.formError = { field: null, error: body.error || "Could not delete." };
drawForm(ctx); drawForm(ctx);
@@ -592,8 +592,8 @@ export function mountAgentsView(container, opts = {}) {
ctx.formReplace = null; ctx.formReplace = null;
ctx.confirming = false; ctx.confirming = false;
const [agents, models] = await Promise.all([ const [agents, models] = await Promise.all([
fetch("/agents").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), mode === "setup" ? Promise.resolve(null) : fetch("models").then((r) => (r.ok ? r.json() : null)).catch(() => null),
]); ]);
if (seq !== loadSeq) return; if (seq !== loadSeq) return;
const problems = []; const problems = [];
+4 -4
View File
@@ -592,7 +592,7 @@ async function postChat(pend) {
let res = null; let res = null;
let body = {}; let body = {};
try { try {
res = await fetch("/chat", { res = await fetch("chat", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
@@ -641,7 +641,7 @@ async function newConversation() {
let res = null; let res = null;
let body = {}; let body = {};
try { try {
res = await fetch("/chat", { res = await fetch("chat", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ reset: true, conversation: askConversation() }), body: JSON.stringify({ reset: true, conversation: askConversation() }),
@@ -674,7 +674,7 @@ async function decideChat(re, decision, text) {
let ok = false; let ok = false;
let body = {}; let body = {};
try { try {
const res = await fetch("/chat/decision", { const res = await fetch("chat/decision", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }), body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }),
@@ -1176,7 +1176,7 @@ export async function saveSubagents() {
}; };
save.disabled = true; save.disabled = true;
status.textContent = ""; status.textContent = "";
const res = await postJson("/subagents", body); const res = await postJson("subagents", body);
save.disabled = false; save.disabled = false;
// The next state frame redraws the button. // The next state frame redraws the button.
if (res.status === 200) { if (res.status === 200) {
+2 -2
View File
@@ -141,7 +141,7 @@ async function scanCleanup() {
$("cleanup-scan").disabled = true; $("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true; $("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false); setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true }); const { status, body } = await postJson("cleanup", { scan: true });
if (gen !== cleanupGen) return; if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false; $("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false; $("cleanup-delete").disabled = false;
@@ -169,7 +169,7 @@ async function deleteCleanup() {
$("cleanup-scan").disabled = true; $("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false); setCleanupStatus("Deleting…", false);
cleanupBusy = true; cleanupBusy = true;
const { status, body } = await postJson("/cleanup", { delete: ids }).finally(() => { const { status, body } = await postJson("cleanup", { delete: ids }).finally(() => {
cleanupBusy = false; cleanupBusy = false;
}); });
if (gen !== cleanupGen) return; if (gen !== cleanupGen) return;
+12 -12
View File
@@ -234,7 +234,7 @@ function fillNoteBox() {
async function seedNoteBox(item, ns) { async function seedNoteBox(item, ns) {
const tab = encodeURIComponent(ns.tab); const tab = encodeURIComponent(ns.tab);
try { 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) { if (res.status === 404) {
banner("That Notebook tab is gone; the box starts empty.", "warn"); banner("That Notebook tab is gone; the box starts empty.", "warn");
return; return;
@@ -251,7 +251,7 @@ async function seedNoteBox(item, ns) {
const files = await Promise.all( const files = await Promise.all(
(ns.pictures || []).map(async (id) => { (ns.pictures || []).map(async (id) => {
try { 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; return r.ok ? new File([await r.blob()], id + ".jpg", { type: "image/jpeg" }) : null;
} catch { } catch {
return null; return null;
@@ -264,7 +264,7 @@ async function seedNoteBox(item, ns) {
async function pushDraft() { async function pushDraft() {
try { try {
await fetch("/draft", { await fetch("draft", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ staged: page.local.staged, drafts: page.local.drafts, images: page.local.images, seeded: page.local.seeded }), 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() { export async function loadState() {
try { 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)); if (!res.ok) throw new Error(String(res.status));
const body = await res.json(); const body = await res.json();
// The same rev is the same state: adopting it again would redraw the page // The same rev is the same state: adopting it again would redraw the page
@@ -759,7 +759,7 @@ function markGone() {
export function connect() { export function connect() {
esErrors = 0; esErrors = 0;
try { try {
es = new EventSource(lastHave ? "/events?have=" + encodeURIComponent(lastHave) : "/events"); es = new EventSource(lastHave ? "events?have=" + encodeURIComponent(lastHave) : "events");
} catch { } catch {
es = null; es = null;
return startPolling(); return startPolling();
@@ -846,7 +846,7 @@ function retryStream() {
// whether the agent is, whether a state frame went missing, and whether a // whether the agent is, whether a state frame went missing, and whether a
// send is still waiting to be picked up. // send is still waiting to be picked up.
export function checkIn() { export function checkIn() {
fetch("/ping", { method: "POST" }) fetch("ping", { method: "POST" })
.then((r) => (r.ok ? r.json() : null)) .then((r) => (r.ok ? r.json() : null))
.then((body) => { .then((body) => {
if (!body) return; if (!body) return;
@@ -2194,7 +2194,7 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) {
const ns = page.local.noteSent; const ns = page.local.noteSent;
if (ns && sentIds.has(ns.item)) { if (ns && sentIds.has(ns.item)) {
page.local.noteSent = null; page.local.noteSent = null;
fetch("/notepad/tab/sent", { fetch("notepad/tab/sent", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ id: ns.tab, workflow: ns.workflow, ...(ns.spec ? { spec: ns.spec } : {}) }), 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 text = note ? note.text : "";
const images = note ? note.images : []; const images = note ? note.images : [];
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
@@ -2275,7 +2275,7 @@ export async function send() {
$("send-nudge").hidden = true; $("send-nudge").hidden = true;
btn.textContent = "Sending…"; btn.textContent = "Sending…";
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions, reply: replyLines.join("\n") }), 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 // server is the lost-contact state now, with its reconnect help; a server
// still there was a blip, and Send is the whole fix. // still there was a blip, and Send is the whole fix.
async function sendLost() { async function sendLost() {
const up = await fetch("/state", { cache: "no-store" }) const up = await fetch("state", { cache: "no-store" })
.then((res) => res.ok) .then((res) => res.ok)
.catch(() => false); .catch(() => false);
if (up) { if (up) {
@@ -2489,7 +2489,7 @@ let whereResizeTimer = null;
// A link the console could not hand to a browser is shown, with a Copy // A link the console could not hand to a browser is shown, with a Copy
// button, for the person to paste into one. // button, for the person to paste into one.
async function openOutside(href) { async function openOutside(href) {
const ok = await fetch("/open-link", { const ok = await fetch("open-link", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ url: href }), body: JSON.stringify({ url: href }),
@@ -2507,7 +2507,7 @@ export function wireChrome() {
// with `referrer-policy: no-referrer` with `Origin: null`, which /bye's // with `referrer-policy: no-referrer` with `Origin: null`, which /bye's
// origin check refuses. // origin check refuses.
try { try {
fetch("/bye", { method: "POST", keepalive: true }).catch(() => {}); fetch("bye", { method: "POST", keepalive: true }).catch(() => {});
} catch {} } catch {}
// A page that goes away leaves no dot on the app's taskbar behind it. // A page that goes away leaves no dot on the app's taskbar behind it.
tellAttention("plain"); tellAttention("plain");
+10 -10
View File
@@ -387,7 +387,7 @@ function maybeWake() {
page.wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() }; page.wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() };
wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches; wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches;
if (wakeHoldsChime && soundOn("snore")) { if (wakeHoldsChime && soundOn("snore")) {
snore = new Audio("/sleeping.mp3"); snore = new Audio("sleeping.mp3");
snore.loop = true; snore.loop = true;
snore.play().catch(() => {}); snore.play().catch(() => {});
} }
@@ -709,7 +709,7 @@ async function pickUpHandoff(h) {
page.launchScoping = true; page.launchScoping = true;
await hooks.syncWorkspaceScope(h.spec || ""); await hooks.syncWorkspaceScope(h.spec || "");
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }), body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }),
@@ -741,7 +741,7 @@ async function readHandoff(h) {
body.replaceChildren(el("p", "md-p", "Reading…")); body.replaceChildren(el("p", "md-p", "Reading…"));
$("handoff-modal").showModal(); $("handoff-modal").showModal();
try { 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)); if (res.status !== 200) throw new Error(String(res.status));
mdInto(body, await res.text()); mdInto(body, await res.text());
} catch { } catch {
@@ -836,14 +836,14 @@ export function pendingNotePick(entry) {
// grayed, so each must be read). Read only: GET /notepad never writes. // grayed, so each must be read). Read only: GET /notepad never writes.
async function readNoteTabs(state) { async function readNoteTabs(state) {
try { 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)); if (!res.ok) throw new Error(String(res.status));
const body = await res.json(); const body = await res.json();
const tabs = Array.isArray(body.tabs) ? body.tabs : []; const tabs = Array.isArray(body.tabs) ? body.tabs : [];
const read = await Promise.all( const read = await Promise.all(
tabs.map(async (t) => { tabs.map(async (t) => {
try { 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; if (!r.ok) return null;
const b = await r.json(); 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; 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; page.launchScoping = true;
await hooks.syncWorkspaceScope(target ? target.dir : ""); await hooks.syncWorkspaceScope(target ? target.dir : "");
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
@@ -1390,7 +1390,7 @@ async function sendDeleteHandoff(h) {
const go = $("delete-go"); const go = $("delete-go");
go.disabled = true; go.disabled = true;
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }), body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }),
@@ -1422,7 +1422,7 @@ async function sendDelete(spec) {
const go = $("delete-go"); const go = $("delete-go");
go.disabled = true; go.disabled = true;
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }), 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. // quiet: the nudge simply stays, as it did before.
async function quietTidyNudge() { async function quietTidyNudge() {
try { try {
await postJson("/learning/tidy-quiet", {}); await postJson("learning/tidy-quiet", {});
} catch {} } catch {}
redraw(); redraw();
} }
@@ -1582,7 +1582,7 @@ export async function sendLearning(what) {
if (what === "review" || what === "tidy") watchLearningBusy(busy); if (what === "review" || what === "tidy") watchLearningBusy(busy);
} }
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [learningAction(what)], reply: learningReply(what) }), body: JSON.stringify({ actions: [learningAction(what)], reply: learningReply(what) }),
+2 -2
View File
@@ -82,7 +82,7 @@ export async function sendBrief() {
go.disabled = true; go.disabled = true;
go.textContent = "Asking…"; go.textContent = "Asking…";
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ 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 // 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. // http cannot open a file:// link). A failure says so on the banner.
async function openPrototypePage(spec, name) { async function openPrototypePage(spec, name) {
const ok = await fetch("/open-prototype", { const ok = await fetch("open-prototype", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ spec, name }), body: JSON.stringify({ spec, name }),
+4 -4
View File
@@ -195,7 +195,7 @@ let loopLessons = { key: null, line: "" };
function loopLessonsFor(key) { function loopLessonsFor(key) {
if (loopLessons.key === key) return loopLessons.line; if (loopLessons.key === key) return loopLessons.line;
loopLessons = { key, line: "" }; loopLessons = { key, line: "" };
fetch("/learning/state", { cache: "no-store" }) fetch("learning/state", { cache: "no-store" })
.then((res) => (res.ok ? res.json() : null)) .then((res) => (res.ok ? res.json() : null))
.then((learning) => { .then((learning) => {
const line = loopLessonsLine(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) { async function sendAfterBuild(kind, launch = null) {
if (page.gone || page.pendingResult || page.local.afterBuild) return; if (page.gone || page.pendingResult || page.local.afterBuild) return;
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
@@ -1100,7 +1100,7 @@ async function goHome() {
const payload = hooks.stagedPayload(); const payload = hooks.stagedPayload();
payload.actions.push({ i: "__dashboard", type: "dashboard" }); payload.actions.push({ i: "__dashboard", type: "dashboard" });
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, HOME_REPLY].join("\n") }), 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(); const payload = hooks.stagedPayload();
payload.actions.push(stopAction({ handoff })); payload.actions.push(stopAction({ handoff }));
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }), body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }),
+2 -2
View File
@@ -144,7 +144,7 @@ async function sendGit(op, fields = {}, wording = {}) {
return; return;
} }
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
@@ -281,7 +281,7 @@ function gitTabKeys(e) {
// the action that follows has the agent re-read, which rebuilds the link. // the action that follows has the agent re-read, which rebuilds the link.
async function pickPrHost(host, kind) { async function pickPrHost(host, kind) {
if (gitLocked()) return; if (gitLocked()) return;
const res = await postJson("/pr-host", { host, kind }); const res = await postJson("pr-host", { host, kind });
if (res.status !== 200) { if (res.status !== 200) {
hooks.banner("That could not be saved. Try again in a moment.", "warn"); hooks.banner("That could not be saved. Try again in a moment.", "warn");
return; return;
@@ -209,7 +209,7 @@ let helpTabs = null;
async function renderHelpVersion() { async function renderHelpVersion() {
const slot = $("help-version"); const slot = $("help-version");
try { try {
const res = await fetch("/version", { cache: "no-store" }); const res = await fetch("version", { cache: "no-store" });
const { version } = res.ok ? await res.json() : {}; const { version } = res.ok ? await res.json() : {};
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : [])); slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version; slot.hidden = !version;
@@ -86,7 +86,7 @@ function pauseSwitch(paused) {
if (pausing) return; if (pausing) return;
pausing = true; pausing = true;
redraw(); redraw();
const { status } = await postJson("/learning/pause", { paused: !paused }); const { status } = await postJson("learning/pause", { paused: !paused });
pausing = false; pausing = false;
if (status !== 200) { if (status !== 200) {
hooks.banner( hooks.banner(
@@ -567,7 +567,7 @@ async function openLessons() {
body.replaceChildren(el("p", "md-p", "Reading…")); body.replaceChildren(el("p", "md-p", "Reading…"));
dlg.showModal(); dlg.showModal();
try { 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)); if (res.status !== 200) throw new Error(String(res.status));
const { files, follows } = await res.json(); const { files, follows } = await res.json();
body.replaceChildren(); body.replaceChildren();
+5 -5
View File
@@ -61,7 +61,7 @@ export async function openLoopSetup(spec) {
const mine = page.loopSetup; const mine = page.loopSetup;
let res; let res;
try { try {
res = await fetch("/loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" }); res = await fetch("loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" });
} catch { } catch {
res = null; res = null;
} }
@@ -129,7 +129,7 @@ function ensureResolved(s) {
s.facts.resolved = null; s.facts.resolved = null;
return; 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)) .then((res) => (res.ok ? res.json() : null))
.catch(() => null) .catch(() => null)
.then((answer) => { .then((answer) => {
@@ -371,7 +371,7 @@ async function askForSuggestion(s, words) {
strengths: words, strengths: words,
}; };
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [action], reply: `Suggest a strength for each phase left in ${s.spec}.` }), 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 = []; s.problems = [];
page.loopNotifyTest = { waiting: true }; page.loopNotifyTest = { waiting: true };
redraw(); 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 (page.loopSetup !== s) return;
if (status !== 200 || !answer || answer.ok !== true) { if (status !== 200 || !answer || answer.ok !== true) {
page.loopNotifyTest = null; page.loopNotifyTest = null;
@@ -759,7 +759,7 @@ async function startLoop(s) {
page.loopStart = null; page.loopStart = null;
s.starting = true; s.starting = true;
redraw(); 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 (page.loopSetup !== s) return;
if (status !== 200 || !answer || answer.ok !== true) { if (status !== 200 || !answer || answer.ok !== true) {
s.starting = false; s.starting = false;
+10 -10
View File
@@ -160,7 +160,7 @@ async function send() {
sending = true; sending = true;
const sent = rev; const sent = rev;
const tab = saveTab; 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; sending = false;
// The tab was deleted or left behind while this was out: nothing in the // The tab was deleted or left behind while this was out: nothing in the
// answer applies to what is on screen now. // answer applies to what is on screen now.
@@ -231,7 +231,7 @@ async function makeEditor() {
// be reached or answered oddly. // be reached or answered oddly.
async function readNote(tab) { async function readNote(tab) {
try { 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; let body = null;
try { try {
body = await res.json(); body = await res.json();
@@ -323,7 +323,7 @@ async function showTab(id, remember = true) {
return false; return false;
} }
show(res.body); show(res.body);
if (remember && activeId) postJson("/notepad/tab/last", { id: activeId }); if (remember && activeId) postJson("notepad/tab/last", { id: activeId });
return true; return true;
} }
@@ -349,7 +349,7 @@ async function reorder(order, focus) {
tabBar.focusTab(focus); tabBar.focusTab(focus);
const at = order.indexOf(focus); const at = order.indexOf(focus);
if (at >= 0) inform(`Moved ${nameOf(focus)} to position ${at + 1} of ${order.length}`); 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; if (res.status === 200) return;
// Refused: draw what the server has, and say why. // Refused: draw what the server has, and say why.
tabs = before; tabs = before;
@@ -438,7 +438,7 @@ function closeNameForm(toFocus = true) {
async function createNamed(name) { async function createNamed(name) {
// The tab on screen is saved first, then the new one is made and shown. // The tab on screen is saved first, then the new one is made and shown.
if (!(await settled())) return nameError(STAY); 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; const id = res.body && res.body.id;
if (res.status !== 200 || !TAB_ID_RE.test(String(id))) { if (res.status !== 200 || !TAB_ID_RE.test(String(id))) {
return nameError(errorSentence(res.status === 0 ? null : res.body && res.body.error)); return nameError(errorSentence(res.status === 0 ? null : res.body && res.body.error));
@@ -456,7 +456,7 @@ async function createNamed(name) {
async function renameTo(name) { async function renameTo(name) {
const id = activeId; 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) { if (res.status !== 200) {
const code = res.status === 0 ? null : res.body && res.body.error; const code = res.status === 0 ? null : res.body && res.body.error;
if (code !== "no-such-tab") return nameError(errorSentence(code)); if (code !== "no-such-tab") return nameError(errorSentence(code));
@@ -530,7 +530,7 @@ async function confirmDelete() {
busy = true; busy = true;
drawTabs(); drawTabs();
paintDelete(); 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; const code = res.status === 0 ? null : res.body && res.body.error;
busy = false; busy = false;
stage = "none"; stage = "none";
@@ -592,14 +592,14 @@ async function upload(entry) {
entry.status = "uploading"; entry.status = "uploading";
if (live(entry)) drawStrip(); if (live(entry)) drawStrip();
if (!entry.id) { 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; const id = res.body && res.body.id;
if (res.status !== 200 || !IMAGE_ID_RE.test(String(id))) return failed(entry, res); if (res.status !== 200 || !IMAGE_ID_RE.test(String(id))) return failed(entry, res);
entry.id = id; entry.id = id;
// The server names the URL (it carries the tab). // The server names the URL (it carries the tab).
entry.url = res.body.url; 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); if (res.status !== 200) return failed(entry, res);
pending.delete(entry.key); pending.delete(entry.key);
entry.status = "ready"; entry.status = "ready";
@@ -756,7 +756,7 @@ async function remove(entry) {
if (entry.id) { if (entry.id) {
entry.deleting = true; entry.deleting = true;
drawStrip(); 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; entry.deleting = false;
// The tab was left (or deleted) while this was out: nothing here to update. // The tab was left (or deleted) while this was out: nothing here to update.
if (!live(entry)) return; if (!live(entry)) return;
@@ -42,7 +42,7 @@ export async function openReviewLoopSetup(spec) {
const mine = page.reviewLoopSetup; const mine = page.reviewLoopSetup;
let res; let res;
try { 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 { } catch {
res = null; res = null;
} }
@@ -97,7 +97,7 @@ function ensureResolved(s) {
s.facts.resolved = null; s.facts.resolved = null;
return; 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)) .then((res) => (res.ok ? res.json() : null))
.catch(() => null) .catch(() => null)
.then((answer) => { .then((answer) => {
@@ -371,7 +371,7 @@ async function saveNotify(s) {
if (url === (facts.notifyUrl || "") && f.notifyKind === (facts.notifyKind || "query") && param === (facts.notifyParam || "message")) return ""; if (url === (facts.notifyUrl || "") && f.notifyKind === (facts.notifyKind || "query") && param === (facts.notifyParam || "message")) return "";
let current = null; let current = null;
try { 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; current = res.ok ? await res.json() : null;
} catch { } catch {
current = null; current = null;
@@ -379,7 +379,7 @@ async function saveNotify(s) {
if (!current) return "The notification address could not be saved. Try again."; 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. // The loop's own screen drops these two before it saves; the store rejects them as unknown fields.
const { remembered, saved, ...entry } = current; 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) { 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."; 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(); redraw();
return; 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 (page.reviewLoopSetup !== s) return;
if (status !== 200 || !body || body.ok !== true) { if (status !== 200 || !body || body.ok !== true) {
s.starting = false; s.starting = false;
+1 -1
View File
@@ -54,7 +54,7 @@ async function onStart(entry) {
page.local.setupStart = { id: entry.id, label, at: Date.now() }; page.local.setupStart = { id: entry.id, label, at: Date.now() };
saveNow(); saveNow();
try { try {
const res = await fetch("/submit", { const res = await fetch("submit", {
method: "POST", method: "POST",
headers: { "content-type": "application/json" }, headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [{ i: "__start", type: "start", agent: entry.id }], reply: "Start with " + label }), body: JSON.stringify({ actions: [{ i: "__start", type: "start", agent: entry.id }], reply: "Start with " + label }),
+6 -6
View File
@@ -54,7 +54,7 @@ export async function syncWorkspaceScope(spec) {
page.scopeMine = want; page.scopeMine = want;
if ((page.wsFrame.scope || "") === want || scopeAsked === want) return; if ((page.wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want; 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 }; if (status === 200 && body && Array.isArray(body.folders)) page.wsFrame = { ...page.wsFrame, ...body };
scopeAsked = null; scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace(); if ($("workspace-modal").open) renderWorkspace();
@@ -83,7 +83,7 @@ let wsBusy = false;
export async function openWorkspace() { export async function openWorkspace() {
const dlg = $("workspace-modal"); const dlg = $("workspace-modal");
try { 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(); if (res.ok) page.wsFrame = await res.json();
} catch {} } catch {}
wsConfirm = null; wsConfirm = null;
@@ -203,7 +203,7 @@ function workspaceField(f, field, labelText) {
input.value = saved(); input.value = saved();
return showError(""); 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. // An earlier "Added as @x" is out of date once the list moves on.
if (status === 200) { if (status === 200) {
setAddMsg(""); setAddMsg("");
@@ -271,7 +271,7 @@ function paintWorkspaceRow(li, f) {
go.type = "button"; go.type = "button";
go.addEventListener("click", async () => { go.addEventListener("click", async () => {
go.disabled = true; go.disabled = true;
const { status } = await postJson("/workspace/remove", { id: f.id }); const { status } = await postJson("workspace/remove", { id: f.id });
wsConfirm = null; wsConfirm = null;
if (status === 200) setAddMsg(""); if (status === 200) setAddMsg("");
if (status !== 200) setAddMsg(`@${f.name} could not be removed. Try again.`, "error"); 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; if (!trimmed || wsBusy || loopDriving()) return;
wsBusy = true; wsBusy = true;
$("workspace-add").disabled = 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; wsBusy = false;
$("workspace-add").disabled = false; $("workspace-add").disabled = false;
if (status === 200) { if (status === 200) {
@@ -327,7 +327,7 @@ async function browseWorkspace() {
if (b.disabled || loopDriving()) return; if (b.disabled || loopDriving()) return;
b.disabled = true; b.disabled = true;
setAddMsg("Waiting for the folder picker…"); setAddMsg("Waiting for the folder picker…");
const { status, body } = await postJson("/workspace/browse", {}); const { status, body } = await postJson("workspace/browse", {});
b.disabled = false; b.disabled = false;
if (status === 200 && body.path) { if (status === 200 && body.path) {
setAddMsg(""); setAddMsg("");
+5 -5
View File
@@ -342,7 +342,7 @@ export function specFileTabs() {
async function fetchSpecFile(spec, kind) { async function fetchSpecFile(spec, kind) {
try { 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; if (res.status !== 200) return null;
const file = decodeURIComponent(res.headers.get("x-spec-file") || "") || kind; const file = decodeURIComponent(res.headers.get("x-spec-file") || "") || kind;
return { file, text: await res.text() }; return { file, text: await res.text() };
@@ -382,7 +382,7 @@ export const prototypesTabShown = () => page.prototypes.key === overviewSpec() &
async function fetchPrototypeList(spec) { async function fetchPrototypeList(spec) {
try { 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 []; if (res.status !== 200) return [];
const body = await res.json(); const body = await res.json();
return Array.isArray(body.files) ? body.files : []; return Array.isArray(body.files) ? body.files : [];
@@ -393,7 +393,7 @@ async function fetchPrototypeList(spec) {
async function fetchPrototypeDoc(spec, name) { async function fetchPrototypeDoc(spec, name) {
try { 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; return res.status === 200 ? await res.text() : null;
} catch { } catch {
return null; return null;
@@ -437,7 +437,7 @@ export async function loadSpecCarry() {
if (specCarryAsked || !isDashboard() || !scan() || page.local.specSel !== undefined) return; if (specCarryAsked || !isDashboard() || !scan() || page.local.specSel !== undefined) return;
specCarryAsked = true; specCarryAsked = true;
try { 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() : {}; const { spec } = res.status === 200 ? await res.json() : {};
if (!spec || page.local.specSel !== undefined || !specList().some((s) => s.dir === spec)) return; if (!spec || page.local.specSel !== undefined || !specList().some((s) => s.dir === spec)) return;
page.local.specSel = spec; 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. // keep its text; null when it is not there. Off the dashboard nothing is read.
async function fetchAgentsDoc(rel) { async function fetchAgentsDoc(rel) {
try { 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; return res.status === 200 ? await res.text() : null;
} catch { } catch {
return null; return null;
+1 -1
View File
@@ -39,7 +39,7 @@ export const soundOn = (event) => looks.sound && looks[soundKey(event)];
const soundPath = (event) => const soundPath = (event) =>
PICKABLE_SOUNDS.includes(event) && looks[soundFileKey(event)] ? `sounds/${looks[soundFileKey(event)]}` : SOUND_EVENTS[event].file; 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. // 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)]; const soundAudio = (event) => SOUNDS[playingPath[event] || soundPath(event)];
+4 -4
View File
@@ -26,8 +26,8 @@ import { step } from "./notepad.js";
export const CHAT_IMAGES = "__chat"; export const CHAT_IMAGES = "__chat";
// An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves // An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves
// it at /uploads/<uuid>.<ext>. // it at uploads/<uuid>.<ext>, relative to itself.
export const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop(); 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. // A page with its corner folded, drawn inline: the CSP allows no icon font.
function pageIcon() { function pageIcon() {
@@ -236,7 +236,7 @@ function setNoteImages(itemId, list) {
// Where an attachment is deleted from. Documents have no `url`, so their // Where an attachment is deleted from. Documents have no `url`, so their
// route is built from the path, as uploadUrl does. // 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 // The files in a paste worth attaching: images and allowed documents. A paste
// with none of them is left to paste as text. // with none of them is left to paste as text.
@@ -258,7 +258,7 @@ async function uploadBlob(itemId, key, blob) {
let body = null; let body = null;
let status = 0; let status = 0;
try { try {
const res = await fetch("/upload", { const res = await fetch("upload", {
method: "POST", method: "POST",
headers: { headers: {
"content-type": isFile ? "application/octet-stream" : "image/jpeg", "content-type": isFile ? "application/octet-stream" : "image/jpeg",
+2 -1
View File
@@ -1430,7 +1430,8 @@ function upload(req, res, ctx) {
id, id,
kind: "image", kind: "image",
path: file, 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"), name: uploadLabel(req, "image.jpg"),
size: buf.length, size: buf.length,
}); });