1073 lines
60 KiB
JavaScript
1073 lines
60 KiB
JavaScript
"use strict";
|
|
|
|
// Source-level pins for the planner board's two concurrency fixes.
|
|
//
|
|
// Bug A (drag-reorder): the old protocol shipped the client's ABSOLUTE
|
|
// ordered id list and the server APPENDED every active id the client had not
|
|
// mentioned, so an item created by a teammate after the dragger's last board
|
|
// render was silently demoted to last priority — and the
|
|
// "planner_next_to_agent" scheduler consumes the top active item by
|
|
// sort_order, so the agent then executed a stale priority. The wire contract
|
|
// is now one RELATIVE MOVE ({ itemId, aboveId, belowId }) applied against the
|
|
// server's current order, with failures that let the client self-heal (404
|
|
// for a vanished item, 409 planner_order_changed when an anchor no longer
|
|
// exists, and user-readable 400 texts for legacy bodies / impossible
|
|
// payloads — the dragend catch alerts err.message for any status other than
|
|
// 409/404, so those strings are user-facing, not machine codes).
|
|
//
|
|
// Bug B (Compose edit state): the form now echoes the updated_at it loaded as
|
|
// expectedUpdatedAt, the PUT route rejects stale writes with 409
|
|
// planner_item_modified, and a CONTENT save (title or prompt in the body)
|
|
// without the echo is fail-closed with a 400
|
|
// (adpanel:planner-cas-fail-closed — an echo-less content write would
|
|
// silently clobber a teammate's just-saved text, the exact lost update the
|
|
// CAS exists to catch; only the isDone-only toggle path stays CAS-free, its
|
|
// own safety being the content-write gate plus the flip branch's
|
|
// zero-affected fail-closed guard), and the client recovers from
|
|
// 404 (item deleted under the form — the old dead-id alert loop) and 409
|
|
// (concurrent edit lost — reload, refill, and re-apply the user's unsaved
|
|
// draft on top of the fresh version snapshot) instead of retrying forever.
|
|
// The create route's cap 409 (planner_item_limit_reached) is recognized
|
|
// BEFORE the status branches so it can never be mistaken for that
|
|
// concurrent-edit conflict and wipe the draft.
|
|
//
|
|
// Bug C (create retry duplicate, adpanel:planner-create-success-decoupled):
|
|
// the create (POST) commit IS the save — the follow-up board GET only
|
|
// repaints — so its success feedback ("Prompt saved" status + compose-form
|
|
// reset) must never be gated on that GET's outcome. A failed or superseded
|
|
// reload used to skip both, leaving the draft in Compose with an enabled
|
|
// Save button, and the user's natural retry POSTed a duplicate (the create
|
|
// route has no duplicate detection; only the 200-item cap bounds it). The
|
|
// POST response carries the SAME fetchPlannerItemsForServer shaping as the
|
|
// GET, so it also seeds plannerItems (no render) and re-derives the drag
|
|
// no-op baseline — from the RENDERED DOM (adpanel:planner-create-baseline),
|
|
// since the snapshot momentarily runs ahead of the board and an array-derived
|
|
// seed would make every dragend in the pre-repaint window POST a spurious
|
|
// reorder — keeping the board coherent when the reload fails. The edit
|
|
// (PUT) branch keeps the verified-reload gate: its retry re-PUTs the same
|
|
// row, so an unverified board deliberately keeps the draft visible.
|
|
//
|
|
// index.js is a ~54k-line application bundle (module side effects, DB and
|
|
// network at require time) and public/js/bot.js is served raw to browsers, so
|
|
// both are pinned structurally on well-anchored source windows, matching the
|
|
// convention of tests/planner-access-gate.test.js and the other route-level
|
|
// tests in this directory. The pure decision core itself is unit-tested in
|
|
// utils/planner-reorder.test.js.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
|
|
const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
|
|
const BOT_SRC = fs.readFileSync(path.join(ROOT, "public", "js", "bot.js"), "utf8");
|
|
|
|
// Window from an anchor to an explicit end anchor — deterministic slicing
|
|
// that survives unrelated edits elsewhere in these two large files.
|
|
function windowBetween(src, startAnchor, endAnchor, label) {
|
|
const start = src.indexOf(startAnchor);
|
|
assert.notStrictEqual(start, -1, `${label}: start anchor not found: ${startAnchor}`);
|
|
const end = src.indexOf(endAnchor, start + startAnchor.length);
|
|
assert.notStrictEqual(end, -1, `${label}: end anchor not found after start: ${endAnchor}`);
|
|
return src.slice(start, end);
|
|
}
|
|
|
|
test("index.js requires the planner-reorder helpers", () => {
|
|
const requireAt = INDEX_SRC.indexOf('require("./utils/planner-reorder")');
|
|
assert.notStrictEqual(requireAt, -1, 'missing require("./utils/planner-reorder")');
|
|
assert.ok(
|
|
INDEX_SRC.includes("computeRelativeReorder,") && INDEX_SRC.includes("plannerUpdatedAtMatches,"),
|
|
"both helpers must be destructured from the module"
|
|
);
|
|
});
|
|
|
|
// ─── Bug A: the reorder route speaks the relative-move protocol ─────────────
|
|
|
|
test("reorder route rejects legacy itemIds bodies and item-less payloads with a user-readable 400", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.post("/api/servers/:name/planner/reorder"',
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
"reorder route"
|
|
);
|
|
assert.ok(
|
|
route.includes("Array.isArray(body.itemIds)"),
|
|
"the legacy absolute-order body must be detected explicitly"
|
|
);
|
|
// The 400 string is user-facing: the dragend catch alerts err.message for
|
|
// any status other than 409/404, so a stale cached client (or a client bug)
|
|
// must see plain language, not a raw machine code, before its board reloads
|
|
// and self-heals.
|
|
const protocolAt = route.indexOf("Your planner view is out of date. The board will refresh — please try the move again.");
|
|
assert.notStrictEqual(protocolAt, -1, "the protocol-failure message is missing");
|
|
assert.ok(!route.includes("planner_reorder_protocol"), "the raw protocol machine code must stay gone");
|
|
assert.ok(
|
|
route.includes("!Number.isFinite(parsedItemId)"),
|
|
"an absent/unparsable itemId must also be a protocol error"
|
|
);
|
|
// The old absolute-order append logic must be gone for good.
|
|
assert.ok(!route.includes("normalizedRequested"), "old requested-filter logic must be removed");
|
|
assert.ok(!route.includes("remainingIds"), "old append-the-unknown logic must be removed");
|
|
assert.ok(!route.includes("finalIds"), "old merged-list logic must be removed");
|
|
assert.ok(!route.includes("'itemIds are required'"), "the old itemIds error must be removed");
|
|
});
|
|
|
|
test("reorder route validates the move against the server order and maps the failure codes", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.post("/api/servers/:name/planner/reorder"',
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
"reorder route"
|
|
);
|
|
const callAt = route.indexOf("computeRelativeReorder(currentIds, itemId, aboveId, belowId)");
|
|
assert.notStrictEqual(callAt, -1, "the route must delegate to the pure decision core");
|
|
assert.ok(
|
|
route.includes("SELECT id, sort_order FROM server_planner_items WHERE server_name = ? AND is_done = 0 ORDER BY sort_order ASC"),
|
|
"the current ACTIVE order must be loaded from the server (source of truth)"
|
|
);
|
|
|
|
const notFoundAt = route.indexOf("missing_item");
|
|
const invalidAt = route.indexOf("invalid_neighbors");
|
|
const changedAt = route.indexOf("anchor_missing");
|
|
assert.notStrictEqual(notFoundAt, -1, "missing_item handling is missing");
|
|
assert.notStrictEqual(invalidAt, -1, "invalid_neighbors handling is missing");
|
|
assert.notStrictEqual(changedAt, -1, "anchor_missing handling is missing");
|
|
assert.ok(
|
|
route.includes("res.status(404).json({ error: 'Planner item not found' })"),
|
|
"missing_item must answer 404 Planner item not found"
|
|
);
|
|
assert.ok(
|
|
route.includes("res.status(400).json({ error: 'That move is not valid for the current board. The board will refresh.' })"),
|
|
"invalid_neighbors must answer 400 with the user-readable move message"
|
|
);
|
|
assert.ok(!route.includes("planner_reorder_invalid"), "the raw invalid-move machine code must stay gone");
|
|
assert.ok(
|
|
route.includes("res.status(409).json({ error: 'planner_order_changed' })"),
|
|
"anchor_missing must answer 409 planner_order_changed"
|
|
);
|
|
});
|
|
|
|
test("reorder route persists inside one transaction and updates only rows whose sort_order changes", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.post("/api/servers/:name/planner/reorder"',
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
"reorder route"
|
|
);
|
|
const beginAt = route.indexOf("await conn.beginTransaction()");
|
|
const commitAt = route.indexOf("await conn.commit()");
|
|
const rollbackAt = route.indexOf("await conn.rollback()");
|
|
const releaseAt = route.indexOf("conn.release()");
|
|
assert.notStrictEqual(beginAt, -1, "the transaction is missing");
|
|
assert.notStrictEqual(commitAt, -1, "the commit is missing");
|
|
assert.notStrictEqual(rollbackAt, -1, "the rollback guard is missing");
|
|
assert.notStrictEqual(releaseAt, -1, "the connection release is missing");
|
|
assert.ok(beginAt < commitAt, "commit must follow beginTransaction");
|
|
|
|
// Skip unchanged rows by comparing the STORED sort_order value (not the
|
|
// position), so untouched rows keep updated_by_email/updated_at. (Rows
|
|
// that DO move get their updated_at bumped and will 409 an in-flight edit
|
|
// of that card — the client's 409 recovery preserves the draft.)
|
|
const skipAt = route.indexOf("currentSortOrders.get(id) === index");
|
|
assert.notStrictEqual(skipAt, -1, "unchanged rows must be skipped by stored value");
|
|
assert.ok(
|
|
route.includes("SET sort_order = ?, updated_by_email = ? WHERE id = ? AND server_name = ?"),
|
|
"the scoped single-row UPDATE statement is missing"
|
|
);
|
|
|
|
// adpanel:planner-reorder-lock — the move must be validated against the
|
|
// LOCKED in-transaction snapshot, before any mutation — never from a
|
|
// pre-transaction snapshot. The arrow definition merely BINDS
|
|
// computeRelativeReorder to the move payload (before the connection is even
|
|
// opened); the load-bearing property is the INVOCATION:
|
|
// planRelativeMove(currentIds) must run AFTER beginTransaction (so it
|
|
// validates the FOR UPDATE-locked SELECT's currentIds) and BEFORE the first
|
|
// sort_order mutation (so a failed validation rolls back and answers before
|
|
// any row is written).
|
|
const defAt = route.indexOf("computeRelativeReorder(currentIds, itemId, aboveId, belowId)");
|
|
assert.notStrictEqual(defAt, -1, "the route must bind the pure decision core to the move payload");
|
|
assert.strictEqual(
|
|
route.indexOf("computeRelativeReorder(currentIds, itemId, aboveId, belowId)", defAt + 1),
|
|
-1,
|
|
"the decision core must be bound exactly once — the planRelativeMove wiring"
|
|
);
|
|
assert.ok(defAt < beginAt, "the planRelativeMove binding must precede the transaction");
|
|
const invocationAt = route.indexOf("planRelativeMove(currentIds)");
|
|
assert.notStrictEqual(invocationAt, -1, "the bound core must actually be invoked: planRelativeMove(currentIds) is missing");
|
|
const firstUpdateAt = route.indexOf("SET sort_order");
|
|
assert.notStrictEqual(firstUpdateAt, -1, "the first sort_order mutation is missing");
|
|
assert.ok(
|
|
invocationAt > beginAt && invocationAt < firstUpdateAt,
|
|
"the move must be validated against the locked in-transaction snapshot — after beginTransaction, before the first sort_order mutation"
|
|
);
|
|
|
|
// Response shape untouched: the client replaces plannerItems with it.
|
|
assert.ok(
|
|
route.includes("fetchPlannerItemsForServer(ctx.serverName)") && route.includes("{ ok: true, items }"),
|
|
"the success response must stay { ok: true, items } from fetchPlannerItemsForServer"
|
|
);
|
|
});
|
|
|
|
// ─── Bug B: the PUT route enforces the opt-in updated_at precondition ───────
|
|
|
|
test("PUT route selects updated_at and enforces expectedUpdatedAt as a 409 precondition", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
'app.delete("/api/servers/:name/planner/:id"',
|
|
"PUT route"
|
|
);
|
|
assert.ok(
|
|
route.includes("SELECT id, title, prompt, is_done, sort_order, updated_at, created_by_email, ${PLANNER_EDIT_VERSION_SQL} AS edit_version FROM server_planner_items"),
|
|
"the row load must fetch both preconditions and the existing author label"
|
|
);
|
|
|
|
const preconditionAt = route.indexOf("plannerUpdatedAtMatches(current.updated_at, body.expectedUpdatedAt)");
|
|
assert.notStrictEqual(preconditionAt, -1, "the precondition comparison is missing");
|
|
const guardAt = route.indexOf("Object.prototype.hasOwnProperty.call(body, 'expectedUpdatedAt')");
|
|
assert.notStrictEqual(guardAt, -1, "the precondition must be keyed on the body key's presence");
|
|
const conflictAt = route.indexOf("res.status(409).json({ error: 'planner_item_modified' })");
|
|
assert.notStrictEqual(conflictAt, -1, "the 409 planner_item_modified response is missing");
|
|
|
|
// adpanel:planner-cas-fail-closed — a CONTENT save (title or prompt in the
|
|
// body) without the echo never bound to a version it saw, so it is a
|
|
// fail-closed 400, not a silent uncased write: the gate is keyed on the
|
|
// same hasTitle/hasPrompt detections the writesContent gate consumes, sits
|
|
// AFTER the presence guard and BEFORE the stale-echo 409 comparison (and
|
|
// before every mutation). The isDone-only toggle path keeps its no-CAS
|
|
// contract — the 400 must not fire for it.
|
|
const failClosedAt = route.indexOf("if ((hasTitle || hasPrompt) && !expectedUpdatedAtProvided) {");
|
|
assert.notStrictEqual(failClosedAt, -1, "the fail-closed missing-echo 400 for content saves is missing");
|
|
const missingEcho400At = route.indexOf("res.status(400).json({ error: 'This edit must include the version it was written against (expectedUpdatedAt). Refresh the board and save again.' })");
|
|
assert.notStrictEqual(missingEcho400At, -1, "the missing-echo 400 must carry the send-agent-style recovery sentence in `error` (the board alerts err.error || err.message)");
|
|
assert.ok(failClosedAt < missingEcho400At, "the 400 must live inside the content-carrying, echo-absent branch");
|
|
|
|
// The rejection must happen BEFORE any mutation: both the plain UPDATE and
|
|
// the done-flip transaction come after it in source order.
|
|
const beginAt = route.indexOf("await conn.beginTransaction()");
|
|
const plainUpdateAt = route.indexOf("await db.query(", preconditionAt);
|
|
assert.notStrictEqual(beginAt, -1, "the done-flip transaction is missing");
|
|
assert.ok(
|
|
guardAt < failClosedAt && failClosedAt < preconditionAt && preconditionAt < conflictAt,
|
|
"order must be: presence guard -> missing-echo 400 (content save) -> comparison -> 409"
|
|
);
|
|
assert.ok(conflictAt < beginAt, "the precondition must fire before the done-flip transaction");
|
|
assert.ok(missingEcho400At < beginAt, "the missing-echo 400 must fire before the done-flip transaction");
|
|
if (plainUpdateAt !== -1) {
|
|
assert.ok(conflictAt < plainUpdateAt, "the precondition must fire before the plain UPDATE");
|
|
}
|
|
});
|
|
|
|
test("PUT route keeps hasOwnProperty field preservation (toggle compatibility)", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
'app.delete("/api/servers/:name/planner/:id"',
|
|
"PUT route"
|
|
);
|
|
assert.ok(
|
|
route.includes("Object.prototype.hasOwnProperty.call(body, 'title')"),
|
|
"title field detection is missing"
|
|
);
|
|
assert.ok(
|
|
route.includes("Object.prototype.hasOwnProperty.call(body, 'prompt')"),
|
|
"prompt field detection is missing"
|
|
);
|
|
assert.ok(
|
|
route.includes("Object.prototype.hasOwnProperty.call(body, 'isDone')"),
|
|
"isDone field detection is missing"
|
|
);
|
|
// The precondition is guarded by the same hasOwnProperty discipline, so a
|
|
// toggle body ({ isDone } only) never carries expectedUpdatedAt and skips
|
|
// the check entirely.
|
|
assert.ok(
|
|
route.includes("Object.prototype.hasOwnProperty.call(body, 'expectedUpdatedAt')"),
|
|
"the precondition must be keyed off the body, not off a defaulted value"
|
|
);
|
|
});
|
|
|
|
// Regression pin (adpanel:planner-isdone-strict): the old derivation
|
|
// `hasDone ? !!body.isDone : ...` let JS truthiness decide — a PUT body
|
|
// carrying isDone:"false" (or "0", or any non-empty string) is truthy, so the
|
|
// toggle silently COMPLETED the item. The toggle contract is a real boolean:
|
|
// a present-but-non-boolean isDone is a fail-closed 400 fired immediately
|
|
// after hasDone is computed (before any value is derived or any row is
|
|
// written), and when the body does carry a boolean it is stored verbatim.
|
|
// The shipped client stays compatible: togglePlannerItem sends
|
|
// { isDone: !Number(item.is_done) }, which is always a real boolean and still
|
|
// toggles through the unchanged flip detection.
|
|
test("PUT route rejects a non-boolean isDone with a 400 and stores a real boolean verbatim", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
'app.delete("/api/servers/:name/planner/:id"',
|
|
"PUT route"
|
|
);
|
|
const hasDoneAt = route.indexOf("Object.prototype.hasOwnProperty.call(body, 'isDone')");
|
|
assert.notStrictEqual(hasDoneAt, -1, "isDone field detection is missing");
|
|
const strictAt = route.indexOf("if (hasDone && typeof body.isDone !== 'boolean') {");
|
|
assert.notStrictEqual(strictAt, -1, "the fail-closed non-boolean isDone validation is missing");
|
|
const badValueAt = route.indexOf("res.status(400).json({ error: 'isDone must be a boolean' })");
|
|
assert.notStrictEqual(badValueAt, -1, "a present-but-non-boolean isDone must answer 400 'isDone must be a boolean'");
|
|
assert.ok(hasDoneAt < strictAt && strictAt < badValueAt, "the 400 must live inside the strict-validation branch keyed off hasDone");
|
|
|
|
// The rejection must fire before ANY state changes: both the done-flip
|
|
// transaction and the nextIsDone derivation come after it in source order,
|
|
// so isDone:"false" can never reach a flip and a real boolean toggles
|
|
// exactly as before.
|
|
const flipTxAt = route.indexOf("await conn.beginTransaction()");
|
|
assert.notStrictEqual(flipTxAt, -1, "the done-flip transaction is missing");
|
|
assert.ok(strictAt < flipTxAt, "the non-boolean rejection must fire before the done-flip transaction");
|
|
|
|
// The truthiness coercion must be gone for good: hasDone ? body.isDone (the
|
|
// validated real boolean) — never !!body.isDone, which completed items on
|
|
// the string "false".
|
|
const nextIsDoneAt = route.indexOf("const nextIsDone = hasDone ? body.isDone : !!current.is_done;");
|
|
assert.notStrictEqual(nextIsDoneAt, -1, "the nextIsDone derivation is missing");
|
|
assert.ok(strictAt < nextIsDoneAt, "the validation must precede the value derivation");
|
|
assert.ok(!route.includes("!!body.isDone"), 'the !!body.isDone truthiness coercion must stay gone (it completed items on the string "false")');
|
|
// A real boolean still toggles: nextIsDone keeps driving the flip detection
|
|
// and the stored flag in both UPDATE shapes.
|
|
assert.ok(
|
|
route.includes("if (nextIsDone !== !!current.is_done) {"),
|
|
"the flip detection must keep comparing nextIsDone against the stored flag"
|
|
);
|
|
});
|
|
|
|
// Regression pin (adpanel:planner-lost-update): the PUT route used to write
|
|
// title/prompt on EVERY shape, sourcing them from the SELECT when the body
|
|
// omitted them — so an isDone-only toggle committing inside a teammate's
|
|
// SELECT→UPDATE edit window silently reverted that edit with stale text (a
|
|
// lost update with no 409). Both UPDATE statements are now conditional: a
|
|
// body that carries NEITHER title NOR prompt writes ONLY the done flag (plus
|
|
// the flip's new slot and the bookkeeping columns), never the content the
|
|
// SELECT read, and the "Prompt is required" 400 applies only on the content
|
|
// path so a toggle can never depend on stored content.
|
|
test("PUT route writes title/prompt only when the body carries them (isDone-only toggle cannot revert content)", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
'app.delete("/api/servers/:name/planner/:id"',
|
|
"PUT route"
|
|
);
|
|
const hasTitleAt = route.indexOf("Object.prototype.hasOwnProperty.call(body, 'title')");
|
|
const hasPromptAt = route.indexOf("Object.prototype.hasOwnProperty.call(body, 'prompt')");
|
|
const gateAt = route.indexOf("const writesContent = hasTitle || hasPrompt;");
|
|
assert.notStrictEqual(gateAt, -1, "the writesContent gate is missing");
|
|
assert.ok(
|
|
hasTitleAt !== -1 && hasPromptAt !== -1 && hasTitleAt < gateAt && hasPromptAt < gateAt,
|
|
"writesContent must derive from the body-key detections"
|
|
);
|
|
|
|
// A content edit only writes the prompt alongside its author if the text changed.
|
|
assert.match(route, /const promptAssignment = promptChanged \? "prompt = \?, prompt_author_id = \?, " : "";/);
|
|
assert.ok(
|
|
route.includes("SET title = ?, ${promptAssignment}is_done = ?, sort_order = ?, updated_by_email = ?, created_by_email = ?"),
|
|
"the flip UPDATE must write the prompt and author only through the shared conditional assignment"
|
|
);
|
|
assert.ok(
|
|
route.includes("SET is_done = ?, sort_order = ?, updated_by_email = ?, created_by_email = ?"),
|
|
"the isDone-only flip UPDATE must not write title/prompt"
|
|
);
|
|
// Non-flip path likewise — and BOTH of its shapes keep the sort_order drop
|
|
// from the planner-edit-integrity fix (a stale reorder must never be
|
|
// reverted by a content write).
|
|
assert.ok(
|
|
route.includes("SET title = ?, ${promptAssignment}is_done = ?, updated_by_email = ?, created_by_email = ?"),
|
|
"the non-flip UPDATE must keep the same conditional prompt assignment"
|
|
);
|
|
assert.ok(
|
|
route.includes("SET is_done = ?, updated_by_email = ?, created_by_email = ?"),
|
|
"the isDone-only non-flip UPDATE must not write title/prompt"
|
|
);
|
|
|
|
// The parameter arrays follow the same gate: the content values are
|
|
// prepended only when the body carries content.
|
|
const flipSpreadAt = route.indexOf("...(writesContent ? [nextTitle, ...promptValues] : [])");
|
|
assert.notStrictEqual(flipSpreadAt, -1, "the flip params must prepend content only when writesContent");
|
|
assert.notStrictEqual(
|
|
route.indexOf("...(writesContent ? [nextTitle, ...promptValues] : [])", flipSpreadAt + 1),
|
|
-1,
|
|
"the non-flip params must prepend content only when writesContent"
|
|
);
|
|
|
|
// The "Prompt is required" 400 stays for real content edits but now sits
|
|
// inside the content branch — a toggle must never 400 on stored content.
|
|
const contentBranchAt = route.indexOf("if (writesContent) {");
|
|
const promptRequiredAt = route.indexOf("error: 'Prompt is required'");
|
|
assert.notStrictEqual(contentBranchAt, -1, "content validation must be gated on writesContent");
|
|
assert.notStrictEqual(promptRequiredAt, -1, "the content-edit prompt validation must stay");
|
|
assert.ok(contentBranchAt < promptRequiredAt, "the 'Prompt is required' 400 must apply only on the content path");
|
|
});
|
|
|
|
// Regression pin (adpanel:planner-noop-save + adpanel:planner-noop-request):
|
|
// the db.js pool sets no CLIENT_FOUND_ROWS flag, so affectedRows counts
|
|
// CHANGED rows, not matched rows, and a zero result is ambiguous: either the
|
|
// row is gone, or the UPDATE matched a live row and changed nothing. The
|
|
// NON-FLIP branch must disambiguate by re-SELECTing the anchor row (the same
|
|
// DATE_FORMAT expression the outer SELECT renders updated_at_sql with): a
|
|
// missing row is a concurrent delete -> 404 (never ok:true); a CAS request
|
|
// whose anchor moved is the teammate conflict -> 409 planner_item_modified
|
|
// (a CAS-verified no-op 409 would loop forever — the client's 409 recovery
|
|
// refills the form with a fresh snapshot and the retry no-ops again);
|
|
// otherwise the UPDATE matched a live row and changed nothing -> fall through
|
|
// as success. The FLIP branch fail-closes EVERY zero case through its own
|
|
// rollback + anchor re-read — a flip always changes is_done against the row
|
|
// it read, so 0 is always a lost CAS or a gone row (never a no-op success):
|
|
// missing row -> 404, live row -> 409 planner_item_modified.
|
|
test("PUT route disambiguates a zero-affected save via the anchor row before any false success", () => {
|
|
const route = windowBetween(
|
|
INDEX_SRC,
|
|
'app.put("/api/servers/:name/planner/:id"',
|
|
'app.delete("/api/servers/:name/planner/:id"',
|
|
"PUT route"
|
|
);
|
|
|
|
// Slice the NON-FLIP tail: from its UPDATE execution to the shared success
|
|
// tail the whole route falls through to.
|
|
const updExecAt = route.indexOf("const [updResult] = await db.pool.execute(nonFlipSql, nonFlipParams);");
|
|
assert.notStrictEqual(updExecAt, -1, "the non-flip UPDATE execution is missing");
|
|
// adpanel:planner-postcommit-reread: the shared tail's board re-read is
|
|
// wrapped in its own try/catch (a transient re-read failure must answer the
|
|
// committed success with items: null, not a 500 for an already-committed
|
|
// mutation), so the anchor is the assignment inside that try.
|
|
const tailAt = route.indexOf("items = await fetchPlannerItemsForServer(ctx.serverName);", updExecAt);
|
|
assert.notStrictEqual(tailAt, -1, "the shared success tail is missing after the non-flip branch");
|
|
const nonFlipTail = route.slice(updExecAt, tailAt);
|
|
|
|
// (a) The zero-affected guard is UNCONDITIONAL (CAS and no-CAS requests
|
|
// alike) and must re-SELECT the anchor row BEFORE any false success: the
|
|
// re-SELECT lives inside the affectedRows === 0 guard (not on the happy
|
|
// path) and is scoped by id AND server_name, rendering updated_at with the
|
|
// SAME DATE_FORMAT expression as the route's outer SELECT — so a CAS
|
|
// comparison is against the exact string the CAS clause compared.
|
|
const zeroAt = nonFlipTail.indexOf("if (updResult.affectedRows === 0) {");
|
|
assert.notStrictEqual(zeroAt, -1, "the zero-affected guard is missing");
|
|
const anchorSelectAt = nonFlipTail.indexOf(
|
|
"SELECT DATE_FORMAT(updated_at, '%Y-%m-%d %H:%i:%s') AS updated_at_sql, ${PLANNER_EDIT_VERSION_SQL} AS edit_version FROM server_planner_items WHERE id = ? AND server_name = ? LIMIT 1"
|
|
);
|
|
assert.notStrictEqual(anchorSelectAt, -1, "the zero-affected path must re-SELECT the anchor row");
|
|
assert.ok(anchorSelectAt > zeroAt, "the anchor re-SELECT must live inside the zero-affected guard, not on the happy path");
|
|
assert.ok(
|
|
route.includes("DATE_FORMAT(cur.updated_at, '%Y-%m-%d %H:%i:%s') AS updated_at_sql"),
|
|
"the outer SELECT must render updated_at_sql with the same DATE_FORMAT expression"
|
|
);
|
|
|
|
// (b) The three disambiguation outcomes inside the guard, in order: a
|
|
// missing row is a concurrent delete (404, never ok:true), a CAS request
|
|
// whose anchor moved is the teammate conflict (409, gated on
|
|
// expectedUpdatedAtProvided — without a CAS no version comparison has
|
|
// meaning), and only the equal-anchor live row falls through to the shared
|
|
// success tail — the non-flip tail must not build a success response of
|
|
// its own.
|
|
const missing404At = nonFlipTail.indexOf("res.status(404).json({ error: 'Planner item not found' })");
|
|
const casGuardAt = nonFlipTail.indexOf("expectedUpdatedAtProvided && anchorRow.updated_at_sql !== current.updated_at_sql");
|
|
const nonFlip409At = nonFlipTail.indexOf("res.status(409).json({ error: 'planner_item_modified' })");
|
|
assert.notStrictEqual(missing404At, -1, "a concurrently deleted row must answer 404 Planner item not found");
|
|
assert.notStrictEqual(casGuardAt, -1, "the CAS-moved comparison is missing (it must be gated on expectedUpdatedAtProvided)");
|
|
assert.ok(nonFlipTail.includes("writesContent && anchorRow.edit_version !== body.expectedEditVersion"),
|
|
"a content change with an unchanged timestamp is not a successful no-op");
|
|
assert.notStrictEqual(nonFlip409At, -1, "the moved-anchor path must still 409 planner_item_modified");
|
|
assert.ok(zeroAt < missing404At && missing404At < casGuardAt && casGuardAt < nonFlip409At, "order inside the guard: missing row 404 -> CAS-moved 409");
|
|
assert.ok(
|
|
!nonFlipTail.includes("res.json"),
|
|
"the equal-anchor path must fall through to the shared success tail (no duplicated response building)"
|
|
);
|
|
|
|
// (c) The FLIP branch: the zero-affected guard is UNCONDITIONAL (CAS and
|
|
// no-CAS requests alike — a flip always changes is_done against the row it
|
|
// read, so 0 is always a lost CAS or a gone row, and a concurrently
|
|
// deleted row must not be misreported as the 409 conflict) and fail-closes
|
|
// through the same rollback + anchor re-read the sibling branches use:
|
|
// rollback FIRST (the zero path returns through the finally that releases
|
|
// conn, and the pool must never re-lend a connection carrying a dangling
|
|
// open transaction — its range locks and read view would leak into the
|
|
// next borrower; the re-read itself runs on a DIFFERENT pooled connection,
|
|
// so its visibility never depended on the rollback), then 404 missing /
|
|
// 409 planner_item_modified live — never a
|
|
// false success; the happy path still commits without any anchor read.
|
|
const flipExecAt = route.indexOf("const [flipResult] = await conn.execute(flipSql, flipParams);");
|
|
assert.notStrictEqual(flipExecAt, -1, "the flip UPDATE execution is missing");
|
|
const flipCommitAt = route.indexOf("await conn.commit();", flipExecAt);
|
|
assert.notStrictEqual(flipCommitAt, -1, "the flip commit is missing");
|
|
const flipTail = route.slice(flipExecAt, flipCommitAt);
|
|
const flipZeroAt = flipTail.indexOf("if (flipResult.affectedRows === 0) {");
|
|
assert.notStrictEqual(flipZeroAt, -1, "the flip branch's unconditional zero-affected guard is missing");
|
|
assert.ok(
|
|
!flipTail.includes("expectedUpdatedAtProvided && flipResult.affectedRows === 0"),
|
|
"the flip branch's zero guard must not be gated on the CAS opt-in — a concurrently deleted row yields 0 under CAS too"
|
|
);
|
|
const flipRollbackAt = flipTail.indexOf("await conn.rollback();", flipZeroAt);
|
|
assert.notStrictEqual(flipRollbackAt, -1, "the flip branch's rollback is missing");
|
|
const flipAnchorSelectAt = flipTail.indexOf(
|
|
"SELECT DATE_FORMAT(updated_at, '%Y-%m-%d %H:%i:%s') AS updated_at_sql FROM server_planner_items WHERE id = ? AND server_name = ? LIMIT 1",
|
|
flipZeroAt
|
|
);
|
|
assert.notStrictEqual(flipAnchorSelectAt, -1, "the flip branch's zero path must re-SELECT the anchor row before answering");
|
|
assert.ok(flipRollbackAt < flipAnchorSelectAt, "the rollback must precede the anchor re-read (the zero path settles the transaction before the pool re-read, so conn can never be released with a dangling open transaction even if the re-read itself fails)");
|
|
const flipMissing404At = flipTail.indexOf("res.status(404).json({ error: 'Planner item not found' })", flipZeroAt);
|
|
assert.notStrictEqual(flipMissing404At, -1, "the flip branch's zero path must 404 a concurrently deleted row");
|
|
const flip409At = flipTail.indexOf("res.status(409).json({ error: 'planner_item_modified' })", flipZeroAt);
|
|
assert.notStrictEqual(flip409At, -1, "the flip branch's zero path must 409 a live row (the CAS-lost conflict; a flip can never be a silent false success)");
|
|
assert.ok(flipMissing404At < flip409At, "order inside the guard: missing row 404 -> live row 409");
|
|
});
|
|
|
|
// ─── Bug A client: dragend sends relative anchors and stays quiet on races ──
|
|
|
|
test("Planner refuses stale same-second content before or during the UPDATE", async () => {
|
|
const route = windowBetween(INDEX_SRC, 'app.put("/api/servers/:name/planner/:id"', 'app.delete("/api/servers/:name/planner/:id"', "PUT route");
|
|
const editVersionSql = JSON.parse(INDEX_SRC.match(/^const PLANNER_EDIT_VERSION_SQL = (".*");$/m)[1]);
|
|
const { plannerUpdatedAtMatches } = require("../utils/planner-reorder");
|
|
const timestamp = "2026-11-27T12:00:00.000Z";
|
|
for (const timing of ["before-read", "before-write", "current"]) {
|
|
const row = {
|
|
updated_at: timestamp, updated_at_sql: "2026-11-27 12:00:00", edit_version: "version-seen",
|
|
title: "Example", prompt: "Original", is_done: 0, created_by_email: "creator@example.test"
|
|
};
|
|
const teammateEdit = () => Object.assign(row, { prompt: "Teammate change", edit_version: "version-teammate" });
|
|
if (timing === "before-read") teammateEdit();
|
|
let writes = 0;
|
|
let activity = 0;
|
|
const db = {
|
|
query: async () => [{ ...row }],
|
|
pool: { async execute(sql, params) {
|
|
if (sql.startsWith("SELECT")) return [[{ ...row }]];
|
|
assert.ok(sql.includes(`AND ${editVersionSql} = ?`));
|
|
assert.equal(params.at(-2), row.updated_at_sql);
|
|
if (timing === "before-write") teammateEdit();
|
|
if (params.at(-1) !== row.edit_version) return [{ affectedRows: 0 }];
|
|
row.prompt = params[1];
|
|
writes += 1;
|
|
return [{ affectedRows: 1 }];
|
|
} }
|
|
};
|
|
let handler;
|
|
const app = { put(_path, _limiter, run) { handler = run; } };
|
|
const deps = {
|
|
app, db, plannerMutateRateLimiter() { },
|
|
resolvePlannerContext: async () => ({ userEmail: "editor@example.test", serverName: "example-server" }),
|
|
requireActionTokenOr403: async () => true,
|
|
plannerUpdatedAtMatches, PLANNER_EDIT_VERSION_SQL: editVersionSql,
|
|
sanitizePlannerTitle: String, sanitizePlannerPrompt: String,
|
|
cancelQueuedPlannerAgentJobs: async () => 0,
|
|
recordActivity() { activity += 1; }, getRequestIp: () => "127.0.0.1",
|
|
fetchPlannerItemsForServer: async () => [row]
|
|
};
|
|
new Function(...Object.keys(deps), route)(...Object.values(deps));
|
|
let status = 200;
|
|
let body;
|
|
const response = { status(code) { status = code; return this; }, json(value) { body = value; } };
|
|
await handler({ params: { id: "1" }, currentUser: { id: 2 }, body: {
|
|
title: "Example", prompt: "My change", expectedUpdatedAt: timestamp, expectedEditVersion: "version-seen"
|
|
} }, response);
|
|
if (timing === "current") {
|
|
assert.equal(status, 200);
|
|
assert.equal(row.prompt, "My change");
|
|
assert.equal(writes, 1);
|
|
assert.equal(activity, 1);
|
|
} else {
|
|
assert.equal(status, 409);
|
|
assert.deepEqual(body, { error: "planner_item_modified" });
|
|
assert.equal(row.prompt, "Teammate change");
|
|
assert.equal(writes, 0);
|
|
assert.equal(activity, 0);
|
|
}
|
|
}
|
|
});
|
|
|
|
test("Planner deletes only the confirmed content version and retracts jobs only after deletion", async () => {
|
|
const route = windowBetween(INDEX_SRC, 'app.delete("/api/servers/:name/planner/:id"', "const DATABASE_CONFIG_FILE", "DELETE route");
|
|
const editVersionSql = JSON.parse(INDEX_SRC.match(/^const PLANNER_EDIT_VERSION_SQL = (".*");$/m)[1]);
|
|
const seenVersion = "a".repeat(64);
|
|
for (const { expectedVersion, currentVersion, statusCode } of [
|
|
{ expectedVersion: undefined, currentVersion: seenVersion, statusCode: 400 },
|
|
{ expectedVersion: seenVersion, currentVersion: "b".repeat(64), statusCode: 409 },
|
|
{ expectedVersion: seenVersion, currentVersion: null, statusCode: 404 },
|
|
{ expectedVersion: seenVersion, currentVersion: seenVersion, statusCode: 200 },
|
|
]) {
|
|
let version = currentVersion;
|
|
let handler;
|
|
const sideEffects = [];
|
|
const deps = {
|
|
app: { delete(_path, _limiter, run) { handler = run; } },
|
|
db: { async query(sql, params) {
|
|
if (sql.startsWith("SELECT")) return version ? [{ id: 1 }] : [];
|
|
assert.equal(sql, `DELETE FROM server_planner_items WHERE id = ? AND server_name = ? AND ${editVersionSql} = ?`);
|
|
assert.deepEqual(params, [1, "fixture", seenVersion]);
|
|
if (params[2] !== version) return { affectedRows: 0 };
|
|
version = null;
|
|
return { affectedRows: 1 };
|
|
} },
|
|
plannerMutateRateLimiter() { },
|
|
resolvePlannerContext: async () => ({ userEmail: "editor@example.test", serverName: "fixture" }),
|
|
requireActionTokenOr403: async () => true,
|
|
PLANNER_EDIT_VERSION_SQL: editVersionSql,
|
|
cancelQueuedPlannerAgentJobs: async () => { sideEffects.push("retract"); },
|
|
recordActivity() { sideEffects.push("activity"); },
|
|
getRequestIp: () => "127.0.0.1",
|
|
fetchPlannerItemsForServer: async () => []
|
|
};
|
|
new Function(...Object.keys(deps), route)(...Object.values(deps));
|
|
let status = 200;
|
|
let payload;
|
|
const response = { status(code) { status = code; return this; }, json(value) { payload = value; } };
|
|
await handler({ params: { id: "1" }, body: { expectedEditVersion: expectedVersion } }, response);
|
|
assert.equal(status, statusCode);
|
|
if (statusCode === 409) assert.deepEqual(payload, { error: "planner_item_modified" });
|
|
assert.equal(version, statusCode === 200 ? null : currentVersion);
|
|
assert.deepEqual(sideEffects, statusCode === 200 ? ["retract", "activity"] : []);
|
|
}
|
|
});
|
|
|
|
test("Planner saves priority only for an accepted drop and never settles a newer drag", async () => {
|
|
const dragSource = windowBetween(BOT_SRC, "function bindPlannerDragAndDrop()", "async function sendPlannerPromptToAgent", "Planner drag handlers");
|
|
for (const scenario of ["cancelled", "accepted", "same-card-overlap"]) {
|
|
const accepted = scenario !== "cancelled";
|
|
const requests = [];
|
|
const reconciliations = [];
|
|
let finishReorder;
|
|
const reorderResponse = new Promise((resolve) => { finishReorder = resolve; });
|
|
const makeCard = (id) => {
|
|
const classes = new Set();
|
|
return {
|
|
dataset: { id },
|
|
classList: {
|
|
add: (name) => classes.add(name),
|
|
remove: (name) => classes.delete(name),
|
|
contains: (name) => classes.has(name),
|
|
},
|
|
handlers: {},
|
|
addEventListener(name, handler) { this.handlers[name] = handler; },
|
|
};
|
|
};
|
|
const first = makeCard("1");
|
|
const second = makeCard("2");
|
|
const list = {
|
|
items: [first, second], dataset: {}, handlers: {},
|
|
querySelectorAll() { return this.items; },
|
|
querySelector() { return this.items.find(({ classList }) => classList.contains("dragging")); },
|
|
insertBefore(card, anchor) { this.items = [card, anchor]; },
|
|
addEventListener(name, handler) { this.handlers[name] = handler; },
|
|
};
|
|
const deps = {
|
|
plannerActiveList: list, plannerDragSession: 0, plannerAcceptedDropSession: 0, plannerDragInFlight: false,
|
|
plannerReloadQueuedAfterDrag: false,
|
|
plannerDragEndAt: 0, plannerLastActiveOrder: [1, 2], plannerLoadSeq: 0, plannerRefreshBtn: null,
|
|
plannerItems: [], plannerGetDragAfterElement: () => first,
|
|
plannerMutateRequest: async (_path, options) => { requests.push(JSON.parse(options.body)); return reorderResponse; },
|
|
plannerSettleDrag: (reload) => { reconciliations.push(!!reload); },
|
|
syncPlannerLastActiveOrder() { }, renderPlannerBoard() { }, setPlannerStatus() { },
|
|
};
|
|
const reloadQueued = new Function(...Object.keys(deps), `${dragSource}\nbindPlannerDragAndDrop(); return () => plannerReloadQueuedAfterDrag;`)(...Object.values(deps));
|
|
const event = { preventDefault() {}, dataTransfer: { setData() {} } };
|
|
second.handlers.dragstart(event);
|
|
list.handlers.dragover(event);
|
|
assert.deepEqual(list.items, [second, first]);
|
|
if (accepted) list.handlers.drop(event);
|
|
const dragend = second.handlers.dragend();
|
|
if (scenario === "same-card-overlap") second.handlers.dragstart(event);
|
|
finishReorder({ items: [] });
|
|
await dragend;
|
|
assert.deepEqual(requests, accepted ? [{ itemId: 2, aboveId: null, belowId: 1 }] : []);
|
|
assert.deepEqual(reconciliations, scenario === "same-card-overlap" ? [] : [!accepted]);
|
|
assert.equal(reloadQueued(), scenario === "same-card-overlap");
|
|
}
|
|
});
|
|
|
|
test("bot.js dragend derives aboveId/belowId from the live DOM and sends the relative body", () => {
|
|
const dragend = windowBetween(
|
|
BOT_SRC,
|
|
"item.addEventListener('dragend'",
|
|
"plannerActiveList.dataset.dragBound",
|
|
"dragend handler"
|
|
);
|
|
assert.ok(
|
|
dragend.includes("siblings[idx - 1].dataset.id") && dragend.includes("siblings[idx + 1].dataset.id"),
|
|
"the anchors must be read from the dropped position in the live DOM"
|
|
);
|
|
assert.ok(dragend.includes("itemId:"), "the body must name the dragged item");
|
|
assert.ok(dragend.includes("aboveId:"), "the body must carry aboveId");
|
|
assert.ok(dragend.includes("belowId:"), "the body must carry belowId");
|
|
assert.ok(!dragend.includes("itemIds"), "the absolute itemIds protocol must be gone from the client");
|
|
|
|
// The no-op check and settle lifecycle are kept.
|
|
assert.ok(
|
|
dragend.includes("JSON.stringify(orderedIds) === JSON.stringify(plannerLastActiveOrder)"),
|
|
"the plannerLastActiveOrder no-op check must stay"
|
|
);
|
|
assert.ok(dragend.includes("plannerSettleDrag(true)"), "failed reorders must force a reload");
|
|
});
|
|
|
|
test("bot.js dragend silences 409/404 (server order wins) before the generic alert", () => {
|
|
const dragend = windowBetween(
|
|
BOT_SRC,
|
|
"item.addEventListener('dragend'",
|
|
"plannerActiveList.dataset.dragBound",
|
|
"dragend handler"
|
|
);
|
|
const silentAt = dragend.indexOf("err.status === 409 || err.status === 404");
|
|
assert.notStrictEqual(silentAt, -1, "the silent 409/404 branch is missing");
|
|
assert.ok(
|
|
dragend.includes("plannerSettleDrag(true)", silentAt),
|
|
"the silent branch must still force the board reload"
|
|
);
|
|
const alertAt = dragend.indexOf("alert(err.message || 'Failed to update planner order')");
|
|
assert.notStrictEqual(alertAt, -1, "the generic alert must stay for other errors");
|
|
assert.ok(silentAt < alertAt, "the silent branch must run before the generic alert");
|
|
});
|
|
|
|
// ─── Bug B client: savePlannerItem sends the snapshot and recovers 404/409 ──
|
|
|
|
test("bot.js savePlannerItem sends both snapshot fields on the edit path only", () => {
|
|
const save = windowBetween(
|
|
BOT_SRC,
|
|
"async function savePlannerItem",
|
|
"async function togglePlannerItem",
|
|
"savePlannerItem"
|
|
);
|
|
assert.ok(
|
|
save.includes("expectedUpdatedAt: plannerEditingSnapshot?.updated_at") &&
|
|
save.includes("expectedEditVersion: plannerEditingSnapshot?.edit_version"),
|
|
"the edit PUT must echo the snapshot taken by fillPlannerForm"
|
|
);
|
|
// The create path stays a plain POST { title, prompt }.
|
|
assert.ok(
|
|
save.includes("body: JSON.stringify({ title, prompt })"),
|
|
"the create path must keep its plain body"
|
|
);
|
|
});
|
|
|
|
// Regression pin (adpanel:planner-create-success-decoupled): the POST commit
|
|
// IS the create save; the follow-up GET only repaints the board. Gating the
|
|
// success feedback on that GET used to mean a failed or superseded reload
|
|
// skipped both the "Prompt saved" status and the form reset — the draft
|
|
// stayed in Compose with an enabled Save button, and since the create route
|
|
// has no duplicate detection (only the 200-item cap), the user's natural
|
|
// retry POSTed a second copy of the same prompt.
|
|
test("bot.js savePlannerItem decouples the create success feedback from the follow-up reload", () => {
|
|
const save = windowBetween(
|
|
BOT_SRC,
|
|
"async function savePlannerItem",
|
|
"async function togglePlannerItem",
|
|
"savePlannerItem"
|
|
);
|
|
// The gate must admit the create branch regardless of the reload outcome;
|
|
// the edit branch keeps the verified-reload gate (a failed reload there
|
|
// keeps the draft visible for a safe re-PUT retry).
|
|
const gateAt = save.indexOf("if (reloaded || !isEditing) {");
|
|
assert.notStrictEqual(gateAt, -1, "the success gate no longer admits the create branch on a failed/superseded reload (reloaded || !isEditing) — the confirmation and reset get skipped and the retry POSTs a duplicate");
|
|
const statusAt = save.indexOf("setPlannerStatus('Prompt saved');", gateAt);
|
|
const resetAt = save.indexOf("resetPlannerForm();", gateAt);
|
|
assert.notStrictEqual(statusAt, -1, "a committed create must still surface 'Prompt saved' when the reload failed or was superseded");
|
|
assert.notStrictEqual(resetAt, -1, "the compose-form reset must still run on a committed create whose reload failed — a surviving draft with an enabled Save button is the duplicate-POST invitation");
|
|
assert.ok(statusAt < resetAt, "the confirmation must precede the reset (the shipped UX order)");
|
|
|
|
// The POST response's items seed plannerItems (the create route answers
|
|
// { ok, itemId, items } from the SAME fetchPlannerItemsForServer shaping as
|
|
// the GET; no render here — the follow-up load or the drag settle paints
|
|
// it), so a failed reload's "last synced" board still contains the created
|
|
// item. The seed must re-derive the drag no-op baseline — but from the
|
|
// RENDERED DOM (adpanel:planner-create-baseline): the snapshot momentarily
|
|
// runs ahead of the board, and an array-derived seed would make every
|
|
// dragend in the pre-repaint window mismatch and POST a reorder for a move
|
|
// the user never made.
|
|
const seedGateAt = save.indexOf("if (Array.isArray(created.items)) {");
|
|
assert.notStrictEqual(seedGateAt, -1, "the create branch must seed plannerItems from the POST response's items (same shaping as the GET)");
|
|
const seedAssignAt = save.indexOf("plannerItems = created.items;", seedGateAt);
|
|
const seedSyncAt = save.indexOf("if (!plannerDragInFlight) syncPlannerLastActiveOrderFromDom();", seedGateAt);
|
|
assert.ok(seedAssignAt !== -1 && seedSyncAt !== -1, "the seed must assign plannerItems and re-derive the no-op baseline from the RENDERED DOM, gated on !plannerDragInFlight");
|
|
assert.ok(seedGateAt < gateAt, "the seed must happen before the follow-up reload");
|
|
// adpanel:planner-create-baseline — the DOM seed must carry the drag guard:
|
|
// mid-drag the DOM is PARKED (the dragged card sits at its dragged
|
|
// position), so a seed from it would bake the parked order into the no-op
|
|
// baseline, the dragend compare would match it, and the settle reload
|
|
// would repaint the pre-drag order — reverting the user's move. Gated, the
|
|
// pre-drag baseline survives so dragend compares the dropped DOM against
|
|
// it: a real move mismatches and POSTs (the server recomputes the created
|
|
// item's position from the anchors), a no-op matches and the settle reload
|
|
// repaints and re-derives the baseline. No unguarded DOM-seed call may
|
|
// exist in the create branch.
|
|
let seedCallAt = save.indexOf("syncPlannerLastActiveOrderFromDom();", seedGateAt);
|
|
while (seedCallAt !== -1 && seedCallAt < gateAt) {
|
|
assert.strictEqual(
|
|
save.slice(seedCallAt - "if (!plannerDragInFlight) ".length, seedCallAt),
|
|
"if (!plannerDragInFlight) ",
|
|
"every syncPlannerLastActiveOrderFromDom() call in the create branch must be gated on !plannerDragInFlight — an unguarded seed mid-drag bakes the parked DOM order into the baseline and the settle reload reverts the drag"
|
|
);
|
|
seedCallAt = save.indexOf("syncPlannerLastActiveOrderFromDom();", seedCallAt + 1);
|
|
}
|
|
// adpanel:planner-create-baseline — the array-based derivation must NOT run
|
|
// between the seed and the follow-up reload: it would seed the baseline with
|
|
// the not-yet-rendered created id and desynchronize the no-op detector from
|
|
// what the board actually shows.
|
|
assert.ok(
|
|
!save.slice(seedGateAt, gateAt).includes("syncPlannerLastActiveOrder();"),
|
|
"the create seed must not derive the baseline from the snapshot array — the created id is not rendered yet, so that seed desynchronizes the no-op detector from the DOM"
|
|
);
|
|
});
|
|
|
|
// Regression pin: the 404 catch must break the dead-id alert loop. Normal
|
|
// path — same editor session and the dead id still owns the form — clears
|
|
// edit state and returns to the board, so the next Save CREATES instead of
|
|
// re-PUTting the dead id forever. Epoch-skip path — the SAME dead item was
|
|
// re-opened during the save, so a newer editor session owns the form —
|
|
// deliberately does NOT clear (the draft is preserved) and instead sets the
|
|
// persistent "press Clear" edit-indicator guidance
|
|
// (adpanel:planner-dead-edit-loop). The guidance is EDIT-only: on a create
|
|
// save savedEditId is '' and a create-mode form's formEditId is '', so the
|
|
// bare equality matches "no item at all" — a create 404 (e.g. the server row
|
|
// vanished) after editor churn mid-flight must stay guidance-free. The
|
|
// 409-into-vanished twin carries the same guard.
|
|
test("bot.js savePlannerItem breaks the 404 dead-id loop (reset on the normal path, Clear guidance on the epoch-skip edit path, never on a create)", () => {
|
|
const save = windowBetween(
|
|
BOT_SRC,
|
|
"async function savePlannerItem",
|
|
"async function togglePlannerItem",
|
|
"savePlannerItem"
|
|
);
|
|
const notFoundAt = save.indexOf("err.status === 404");
|
|
assert.notStrictEqual(notFoundAt, -1, "the 404 branch is missing");
|
|
const deletedAlertAt = save.indexOf("alert('This prompt was deleted by another user.')", notFoundAt);
|
|
assert.notStrictEqual(deletedAlertAt, -1, "the 404 alert is missing");
|
|
// Normal path: the reset must stay gated on the editor epoch AND the form
|
|
// still holding the dead id — an edit opened during the in-flight save
|
|
// (a different item or a same-item re-open) must not be wiped by this 404.
|
|
const resetGuardAt = save.indexOf(
|
|
"if (plannerEditorEpoch === savedEditorEpoch && formEditId === savedEditId) {",
|
|
deletedAlertAt
|
|
);
|
|
assert.notStrictEqual(resetGuardAt, -1, "the 404 reset must be gated on the editor epoch and the form still holding the dead id");
|
|
const resetAt = save.indexOf("resetPlannerForm()", resetGuardAt);
|
|
const boardAt = save.indexOf("switchPlannerTab('board')", resetGuardAt);
|
|
// Epoch-skip guidance branch: a same-item re-open must get guidance, not
|
|
// silence — and the branch must require a genuine edit (savedEditId
|
|
// non-empty) so a create save's '' sentinel can never match a create-mode
|
|
// form's '' and fire "no longer exists" on a form that never held an item.
|
|
const guidanceGuardAt = save.indexOf("} else if (savedEditId && formEditId === savedEditId) {", resetGuardAt);
|
|
assert.notStrictEqual(guidanceGuardAt, -1, "the 404 epoch-skip guidance branch is missing or lost its edit-only guard (savedEditId non-empty)");
|
|
assert.ok(
|
|
resetAt !== -1 && resetAt < guidanceGuardAt && boardAt !== -1 && boardAt < guidanceGuardAt,
|
|
"the 404 branch must clear edit state and return to the board on the normal path (next Save creates)"
|
|
);
|
|
const vanishIndicator = "setPlannerEditIndicator('This prompt no longer exists — press Clear to discard the form and start a new prompt.')";
|
|
const firstGuidanceAt = save.indexOf(vanishIndicator, guidanceGuardAt);
|
|
assert.notStrictEqual(firstGuidanceAt, -1, "the 404 epoch-skip edit path must set the persistent dead-edit guidance (the Clear escape hatch)");
|
|
// Both guidance sites in savePlannerItem (this one and the
|
|
// 409-into-vanished twin's) must sit inside an edit-only (savedEditId-
|
|
// guarded) branch — no third, unguarded site may exist.
|
|
const secondGuidanceAt = save.indexOf(vanishIndicator, firstGuidanceAt + 1);
|
|
assert.notStrictEqual(secondGuidanceAt, -1, "the 409-into-vanished twin must keep its guidance site");
|
|
assert.strictEqual(
|
|
save.indexOf(vanishIndicator, secondGuidanceAt + 1),
|
|
-1,
|
|
"no unguarded third guidance site may exist — every site must be inside a savedEditId-guarded branch"
|
|
);
|
|
const conflictAt = save.indexOf("err.status === 409", notFoundAt);
|
|
assert.notStrictEqual(conflictAt, -1, "the 409 branch is missing");
|
|
assert.ok(secondGuidanceAt > conflictAt, "the second guidance site must belong to the 409-into-vanished twin");
|
|
const vanishResetGuardAt = save.indexOf("if (plannerEditorEpoch === savedEditorEpoch) {", conflictAt);
|
|
assert.notStrictEqual(vanishResetGuardAt, -1, "the 409-into-vanished reset must stay gated on the editor epoch");
|
|
const vanishGuidanceGuardAt = save.indexOf("} else if (savedEditId) {", vanishResetGuardAt);
|
|
assert.notStrictEqual(vanishGuidanceGuardAt, -1, "the 409-into-vanished twin must keep the edit-only guard (savedEditId non-empty) on its guidance");
|
|
assert.ok(
|
|
secondGuidanceAt > vanishGuidanceGuardAt,
|
|
"the 409-into-vanished guidance must sit inside its edit-only branch (never fires for a create save)"
|
|
);
|
|
// The create route's cap 409 shares this catch, so the cap must be
|
|
// recognized BEFORE the status branches (see the dedicated ordering pin
|
|
// below) — it used to fall into the concurrent-edit branch and wipe the
|
|
// draft.
|
|
assert.ok(
|
|
save.indexOf("err.message === 'planner_item_limit_reached'") < notFoundAt,
|
|
"the cap check must run before the 404 stale-edit recovery"
|
|
);
|
|
});
|
|
|
|
test("Planner save keeps the draft on server errors and resets it only for a deleted prompt", async () => {
|
|
const source = windowBetween(BOT_SRC, "async function savePlannerItem", "async function togglePlannerItem", "savePlannerItem");
|
|
for (const { itemId, status, message, reset = false } of [
|
|
{ itemId: "", status: 404, message: "Server not found" },
|
|
{ itemId: "", status: 409, message: "Server changed or is being deleted. Reload and try again." },
|
|
{ itemId: "7", status: 404, message: "Server not found" },
|
|
{ itemId: "7", status: 404, message: "Planner item not found", reset: true },
|
|
]) {
|
|
const alerts = [];
|
|
const prompt = { value: "Unsaved prompt" };
|
|
const title = { value: "Unsaved title" };
|
|
const dependencies = {
|
|
plannerSaveInFlight: false,
|
|
plannerPromptInput: prompt,
|
|
plannerTitleInput: title,
|
|
plannerItemIdInput: { value: itemId },
|
|
plannerEditingSnapshot: null,
|
|
plannerEditorEpoch: 1,
|
|
plannerSaveBtn: null,
|
|
plannerItems: [],
|
|
plannerMutateRequest: async () => { throw Object.assign(new Error(message), { status }); },
|
|
resetPlannerForm: () => { prompt.value = ""; title.value = ""; },
|
|
switchPlannerTab: () => {},
|
|
loadPlannerItems: async () => true,
|
|
alert: (text) => alerts.push(text),
|
|
console: { error() {} },
|
|
};
|
|
const save = new Function(...Object.keys(dependencies), `${source}\nreturn savePlannerItem;`)(...Object.values(dependencies));
|
|
await save();
|
|
assert.deepEqual(alerts, [reset ? "This prompt was deleted by another user." : message]);
|
|
assert.equal(prompt.value, reset ? "" : "Unsaved prompt");
|
|
assert.equal(title.value, reset ? "" : "Unsaved title");
|
|
}
|
|
});
|
|
|
|
test("bot.js savePlannerItem recovers from 409 by reloading and refilling the form", () => {
|
|
const save = windowBetween(
|
|
BOT_SRC,
|
|
"async function savePlannerItem",
|
|
"async function togglePlannerItem",
|
|
"savePlannerItem"
|
|
);
|
|
const conflictAt = save.indexOf("err.status === 409");
|
|
assert.notStrictEqual(conflictAt, -1, "the 409 branch is missing");
|
|
// The reload runs BEFORE the alert (adpanel:planner-409-recovery-promise):
|
|
// the alert's promise ("saving will apply them on top of the latest
|
|
// version") is only true when the reload actually re-stamped
|
|
// plannerEditingUpdatedAt — a failed reload must get the accurate
|
|
// "board could not be refreshed" message instead of that promise.
|
|
const reloadAt = save.indexOf("await loadPlannerItems()", conflictAt);
|
|
assert.notStrictEqual(reloadAt, -1, "the 409 branch must reload the board");
|
|
const changedAlertAt = save.indexOf(
|
|
"alert('This prompt was changed by another user. Your unsaved edits were kept — saving will apply them on top of the latest version.')",
|
|
conflictAt
|
|
);
|
|
assert.notStrictEqual(changedAlertAt, -1, "the 409 success-path alert is missing");
|
|
assert.ok(reloadAt < changedAlertAt, "the success alert must follow the reload whose outcome it promises on");
|
|
const failedReloadAlertAt = save.indexOf(
|
|
"alert('This prompt was changed by another user. Your unsaved edits were kept, but the board could not be refreshed — saving will keep conflicting until a refresh succeeds. Press Refresh and try again.')",
|
|
conflictAt
|
|
);
|
|
assert.notStrictEqual(failedReloadAlertAt, -1, "the 409 failed-reload alert is missing");
|
|
const refillAt = save.indexOf("fillPlannerForm(fresh)", changedAlertAt);
|
|
assert.notStrictEqual(refillAt, -1, "the 409 branch must refill the form with the fresh item");
|
|
assert.ok(
|
|
save.indexOf("err.message === 'planner_item_limit_reached'") < conflictAt,
|
|
"the cap check must run before the 409 concurrent-edit recovery"
|
|
);
|
|
});
|
|
|
|
// Regression pin: the create route answers 409 planner_item_limit_reached
|
|
// when the planner is full, and that used to fall into the concurrent-edit
|
|
// branch below (same status code) — double-alerting "changed" then "deleted"
|
|
// and wiping the user's draft. The cap must stay the FIRST branch of the
|
|
// catch; on a create `id` is NaN, so the 409 branch's find() could never have
|
|
// matched it anyway.
|
|
test("bot.js savePlannerItem recognizes the planner-cap 409 before the status branches", () => {
|
|
const save = windowBetween(
|
|
BOT_SRC,
|
|
"async function savePlannerItem",
|
|
"async function togglePlannerItem",
|
|
"savePlannerItem"
|
|
);
|
|
const catchAt = save.indexOf("} catch (err) {");
|
|
assert.notStrictEqual(catchAt, -1, "the save catch is missing");
|
|
const capAt = save.indexOf("err.message === 'planner_item_limit_reached'", catchAt);
|
|
assert.notStrictEqual(capAt, -1, "the cap check must be a first-class branch in the catch");
|
|
const notFoundAt = save.indexOf("err.status === 404", catchAt);
|
|
const conflictAt = save.indexOf("err.status === 409", catchAt);
|
|
assert.notStrictEqual(notFoundAt, -1, "the 404 branch is missing");
|
|
assert.notStrictEqual(conflictAt, -1, "the 409 branch is missing");
|
|
assert.ok(capAt < notFoundAt, "the cap check must run before the 404 branch");
|
|
assert.ok(capAt < conflictAt, "the cap check must run before the 409 branch");
|
|
});
|
|
|
|
// Regression pin: the 409 refill used to overwrite the in-progress text and
|
|
// destroy the user's unsaved edits. The branch must capture both draft
|
|
// inputs BEFORE fillPlannerForm(fresh) and re-apply them AFTER it —
|
|
// fillPlannerForm still re-stamps the fresh plannerEditingUpdatedAt version
|
|
// snapshot, so the next Save succeeds instead of 409ing again.
|
|
test("bot.js savePlannerItem keeps the unsaved draft across the 409 refill", () => {
|
|
const save = windowBetween(
|
|
BOT_SRC,
|
|
"async function savePlannerItem",
|
|
"async function togglePlannerItem",
|
|
"savePlannerItem"
|
|
);
|
|
const conflictAt = save.indexOf("err.status === 409");
|
|
assert.notStrictEqual(conflictAt, -1, "the 409 branch is missing");
|
|
const refillAt = save.indexOf("fillPlannerForm(fresh)", conflictAt);
|
|
assert.notStrictEqual(refillAt, -1, "the 409 branch must refill the form with the fresh item");
|
|
const titleCaptureAt = save.indexOf("const draftTitle = plannerTitleInput?.value;", conflictAt);
|
|
const promptCaptureAt = save.indexOf("const draftPrompt = plannerPromptInput?.value;", conflictAt);
|
|
assert.notStrictEqual(titleCaptureAt, -1, "the title draft must be captured");
|
|
assert.notStrictEqual(promptCaptureAt, -1, "the prompt draft must be captured");
|
|
assert.ok(
|
|
titleCaptureAt < refillAt && promptCaptureAt < refillAt,
|
|
"both drafts must be captured BEFORE the refill"
|
|
);
|
|
const titleReapplyAt = save.indexOf("plannerTitleInput.value = draftTitle", refillAt);
|
|
const promptReapplyAt = save.indexOf("plannerPromptInput.value = draftPrompt", refillAt);
|
|
assert.notStrictEqual(titleReapplyAt, -1, "the title draft must be re-applied after the refill");
|
|
assert.notStrictEqual(promptReapplyAt, -1, "the prompt draft must be re-applied after the refill");
|
|
});
|
|
|
|
// ─── Regression guards ───────────────────────────────────────────────────────
|
|
|
|
test("bot.js togglePlannerItem still sends ONLY { isDone }", () => {
|
|
const toggle = windowBetween(
|
|
BOT_SRC,
|
|
"async function togglePlannerItem",
|
|
"async function deletePlannerItem",
|
|
"togglePlannerItem"
|
|
);
|
|
assert.ok(
|
|
toggle.includes("body: JSON.stringify({ isDone: !Number(item.is_done) })"),
|
|
"the toggle body must stay exactly { isDone }"
|
|
);
|
|
assert.strictEqual(
|
|
(toggle.match(/JSON\.stringify\(/g) || []).length,
|
|
1,
|
|
"togglePlannerItem must issue exactly one request body"
|
|
);
|
|
assert.ok(!toggle.includes("expectedUpdatedAt"), "the toggle must never send the edit snapshot");
|
|
});
|
|
|
|
test("bot.js keeps the edit snapshot separate from the in-flight flag", () => {
|
|
const lastOrderAt = BOT_SRC.indexOf("let plannerLastActiveOrder = [];");
|
|
const editingAt = BOT_SRC.indexOf("let plannerEditingSnapshot = null;");
|
|
const saveInFlightAt = BOT_SRC.indexOf("let plannerSaveInFlight = false;");
|
|
assert.notStrictEqual(lastOrderAt, -1, "plannerLastActiveOrder declaration not found");
|
|
assert.notStrictEqual(editingAt, -1, "plannerEditingSnapshot declaration not found");
|
|
assert.notStrictEqual(saveInFlightAt, -1, "plannerSaveInFlight declaration not found");
|
|
assert.ok(
|
|
lastOrderAt < editingAt && editingAt < saveInFlightAt,
|
|
"the snapshot must sit after plannerLastActiveOrder and before plannerSaveInFlight"
|
|
);
|
|
});
|
|
|
|
test("bot.js form helpers snapshot and reset the version marker", () => {
|
|
const helpers = windowBetween(
|
|
BOT_SRC,
|
|
"function clearPlannerEditState",
|
|
"// Passing null for either list renders",
|
|
"planner form helpers"
|
|
);
|
|
const clearAt = helpers.indexOf("function clearPlannerEditState");
|
|
const resetAt = helpers.indexOf("function resetPlannerForm");
|
|
const fillAt = helpers.indexOf("function fillPlannerForm");
|
|
assert.notStrictEqual(clearAt, -1, "clearPlannerEditState not found");
|
|
assert.notStrictEqual(resetAt, -1, "resetPlannerForm not found");
|
|
assert.notStrictEqual(fillAt, -1, "fillPlannerForm not found");
|
|
assert.ok(
|
|
helpers.slice(clearAt, resetAt).includes("plannerEditingSnapshot = null;"),
|
|
"clearPlannerEditState must reset the snapshot"
|
|
);
|
|
assert.ok(
|
|
helpers.slice(resetAt, fillAt).includes("clearPlannerEditState();"),
|
|
"resetPlannerForm must reset the snapshot"
|
|
);
|
|
assert.ok(
|
|
helpers.includes("plannerEditingSnapshot = item;", fillAt),
|
|
"fillPlannerForm must snapshot both edit preconditions"
|
|
);
|
|
});
|