Files
Kelx/tests/fs-op-ack.test.js
2026-11-30 16:32:37 +00:00

762 lines
38 KiB
JavaScript

"use strict";
// Tests for the dead failure channel on local-mode file save/delete.
//
// Bug: in panel-served (non-remote) mode the client emitted writeFile/
// deleteFile over Socket.IO and returned success immediately — fire and
// forget with no ack. The server's only outcome reporting was a "toast"
// event into the server's room, and nothing client-side ever listened for
// "toast". Every denial (files_create without files_write hitting the node's
// 409, missing files_delete, suspension, access) and every node-side failure
// was therefore invisible: the editor marked the buffer clean on a failed
// save and the user's work was lost with "save says it worked but the file
// didn't change".
//
// Fix: the handlers reply through the socket ack ({ ok, msg }) on every
// terminal path; the room toast survives only as a legacy fallback for
// clients that still emit without an ack (nothing listens to it otherwise).
// The client awaits the ack (socket.timeout, above the 120s node-call
// budget) and throws on failure, so the existing try/catch call sites handle
// local-mode failures exactly like the remote-mode HTTP failures they were
// already written for.
//
// index.js boots servers on require and cannot be loaded in-process, so the
// two handlers and the fsOpReply/fsOpFallbackToast helpers are evaluated
// from source with injected fakes (same technique as server-op-guard and
// ssh-terminal-window-per-tab); the client helper is evaluated the same way
// from the bot.js bundle.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const { attachEditorWriteHash, renderEditorWriteRefusal, FS_WRITE_STALE_CONFLICT_ERROR, FS_WRITE_STALE_CONFLICT_MESSAGE } = require("../services/node-fs-relay");
const { getServerStatusRoom } = require("../utils/server-socket-rooms");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const botSource = fs.readFileSync(BOT_JS, "utf8");
function sliceBetween(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
test("a previous save cannot replace the baseline of a reopened editor at the same path", async () => {
const source = sliceBetween(botSource, "async function performSave(", "if (editorSave) {\n editorSave.onclick", "editor save");
const makeEditor = new Function("apiWriteFile", "computeEditorBaseSha256", `
const currentEditorPath = 'fixture.txt';
let editorDocumentGeneration = 1, editorSaving = false;
let editorOriginalContent = 'first load', editorBaseSha256 = 'first hash';
const editorSave = null, editorModal = null, monacoEditor = null, textArea = null;
const isEditorDirty = () => true, hasPerm = () => true, isEditorErrorContent = () => false;
const getCurrentEditorValue = () => 'first save';
const showStoreToast = () => {}, loadExplorer = () => {}, refreshMiniFm = () => {};
${source}
return {
performSave,
reopen() {
editorDocumentGeneration++;
editorOriginalContent = 'new load';
editorBaseSha256 = 'new hash';
},
baseline: () => [editorOriginalContent, editorBaseSha256]
};
`);
for (const reopenDuringDigest of [false, true]) {
let acknowledge;
let finishDigest;
const editor = makeEditor(
() => new Promise((resolve) => { acknowledge = resolve; }),
() => new Promise((resolve) => { finishDigest = resolve; })
);
const saving = editor.performSave();
if (!reopenDuringDigest) editor.reopen();
acknowledge('Saved fixture.txt');
await Promise.resolve();
assert.equal(typeof finishDigest, reopenDuringDigest ? 'function' : 'undefined');
if (reopenDuringDigest) editor.reopen();
finishDigest?.('first save hash');
assert.equal(await saving, true);
assert.deepEqual(editor.baseline(), ['new load', 'new hash']);
}
});
test("switching from the image viewer keeps edits made while the previous file saves", async () => {
const switchSource = sliceBetween(botSource, "async function switchEditorFile(", "if (miniFmBreadcrumbs)", "editor switch");
const viewerSource = sliceBetween(botSource, "function openNonImageFromViewer(", "function renderImgViewerMiniFmBreadcrumb(", "viewer switch");
for (const typedDuringSave of [true, false]) {
let content = "pending edit";
let saved = "old";
let finishSave;
const opened = [];
const switchFromViewer = new Function("isEditorDirty", "confirm", "performSave", "openFileInEditor", "closeImageViewer", `
const currentEditorPath = "first.txt", editorOpenGeneration = 1, FILE_SIZE_EDITOR_LIMIT = 1024;
${switchSource}
${viewerSource}
return openNonImageFromViewer;
`)(() => content !== saved, () => true, () => {
const snapshot = content;
return new Promise((resolve) => {
finishSave = () => { saved = snapshot; resolve(true); };
});
}, (file) => opened.push(file), () => {});
const switching = switchFromViewer("second.txt", 4);
assert.strictEqual(typeof finishSave, "function", "the viewer must use the dirty-editor guard");
if (typedDuringSave) content += " and newer edits";
finishSave();
await switching;
assert.deepStrictEqual(opened, typedDuringSave ? [] : ["second.txt"]);
}
});
test("a large remote Files selection uses bounded batches and reports item-level refusals", async () => {
const source = sliceBetween(botSource, "if (fmDeleteBtn) {\n fmDeleteBtn.addEventListener", "if (filesModal && fmActions)", "selection delete");
const rows = Array.from({ length: 101 }, (_, index) => ({ dataset: { relPath: `folder/file-${index}.txt` } }));
const batches = [], alerts = [];
let run, refreshes = 0;
require("node:vm").runInNewContext(source, {
fmDeleteBtn: { addEventListener: (_, listener) => { run = listener; } },
entriesEl: { querySelectorAll: () => rows },
selectedEntries: new Set(rows.map(row => row.dataset.relPath)),
REMOTE_MODE: true, NODE_API_BASE: "/api/nodes/server/fixture",
uploadBatchActive: false, urlUploadInFlight: false,
hasPerm: () => true, confirm: () => true, alert: (text) => alerts.push(text),
showProgressWheel: () => 1, hideProgressWheel: () => {}, dialogText: String,
clearSelection: () => {}, loadExplorer: () => { refreshes++; },
apiDelete: () => assert.fail("remote selection must not mint a token per file"),
readJsonResponseSafe: (response) => response.json(),
fetchWithServerActionToken: async (url, options, token, { refreshBefore }) => {
assert.strictEqual(url, "/api/nodes/server/fixture/delete-batch");
assert.strictEqual(options.method, "POST");
assert.strictEqual(token, "fileDelete");
assert.ok(refreshBefore);
const { items } = JSON.parse(options.body);
batches.push(items.length);
return { ok: true, json: async () => ({ results: items.map(item => item.path.endsWith("-100.txt")
? { ok: false, error: "delete failed" } : { ok: true }) }) };
},
});
await run();
assert.deepStrictEqual(batches, [100, 1]);
assert.deepStrictEqual(alerts, ['Deleted 100 of 101 item(s). Failed to delete: "file-100.txt" (delete failed)']);
assert.strictEqual(refreshes, 1);
});
// ---------------------------------------------------------------------------
// Fakes
// ---------------------------------------------------------------------------
function makeFakes({
accessible = true,
writeMode = { ok: true, mode: "" },
suspended = false,
filesDeletePerm = true,
ctx = { remote: true, baseDir: "/srv", serverName: "srv", node: {} },
nodeFsPostImpl = null,
writeTooLarge = false,
} = {}) {
const calls = { denies: [], toasts: [] };
const fakes = {
calls,
canAccessBot: (name) => accessible && !!name,
socketWriteMode: async () => writeMode,
findServer: async () => (suspended ? { status: "suspended" } : { status: "running" }),
isServerSuspended: (entry) => !!(entry && entry.status === "suspended"),
hasPerm: async (name, perm) => (perm === "files_delete" ? filesDeletePerm : false),
resolveRemoteFsContext: async () => ctx,
safeJoinUnix: (base, rel) => `${base}/${rel}`,
nodeFsPost: nodeFsPostImpl || (async () => ({ status: 200, json: { ok: true } })),
// Issue 7: 10 MiB daemon raw-body cap, mirrored from index.js's real
// helper (writeTooLarge forces the pre-check path for the ack tests).
nodeFsWritePayloadTooLarge: (payload) =>
writeTooLarge || Buffer.byteLength(JSON.stringify(payload), "utf8") > 10 * 1024 * 1024,
FILE_WRITE_LIMIT_CLIENT_MESSAGE: "File exceeds the 10 MB editor limit — upload the file instead.",
FILE_WRITE_BASE64_LIMIT_CLIENT_MESSAGE: "Binary file exceeds the ~7.4 MB editor save limit (base64 content must fit the node's 10 MB request body) — upload the file instead.",
NODE_FS_WRITE_TOO_LARGE_MARKER: "content too large",
// Issue 1: server-root refusal, mirrored from index.js's real guard
// (the harness safeJoinUnix always appends "/", so rel "" joins to base+"/").
isServerRootResolvedPath: (base, joined) => joined === base || joined === base + "/",
escapeHtml: (s) => String(s),
deny: (room, msg) => calls.denies.push({ room, msg }),
io: { to: (room) => ({ emit: (ev, payload) => calls.toasts.push({ room, ev, payload }) }) },
};
return fakes;
}
// Evaluate the writeFile/deleteFile handler registrations from index.js with
// the fakes injected, returning the registered handlers.
function loadFsHandlers(fakes) {
const slice = sliceBetween(
indexSource,
'socket.on("writeFile"',
'socket.on("action"',
"index.js fs handlers"
);
const registered = {};
const fakeSocket = { on: (ev, fn) => { registered[ev] = fn; } };
new Function(
"socket", "io", "deny", "canAccessBot", "socketWriteMode", "findServer",
"isServerSuspended", "hasPerm", "resolveRemoteFsContext", "safeJoinUnix",
"nodeFsPost", "escapeHtml", "fsOpReply", "fsOpFallbackToast",
"nodeFsWritePayloadTooLarge", "FILE_WRITE_LIMIT_CLIENT_MESSAGE",
"FILE_WRITE_BASE64_LIMIT_CLIENT_MESSAGE", "NODE_FS_WRITE_TOO_LARGE_MARKER",
"isServerRootResolvedPath",
"attachEditorWriteHash", "renderEditorWriteRefusal", "FS_WRITE_STALE_CONFLICT_ERROR",
slice
)(
fakeSocket, fakes.io, fakes.deny, fakes.canAccessBot, fakes.socketWriteMode,
fakes.findServer, fakes.isServerSuspended, fakes.hasPerm,
fakes.resolveRemoteFsContext, fakes.safeJoinUnix, fakes.nodeFsPost,
fakes.escapeHtml, fakes.fsOpReply, fakes.fsOpFallbackToast,
fakes.nodeFsWritePayloadTooLarge, fakes.FILE_WRITE_LIMIT_CLIENT_MESSAGE,
fakes.FILE_WRITE_BASE64_LIMIT_CLIENT_MESSAGE, fakes.NODE_FS_WRITE_TOO_LARGE_MARKER,
fakes.isServerRootResolvedPath,
attachEditorWriteHash, renderEditorWriteRefusal, FS_WRITE_STALE_CONFLICT_ERROR
);
assert.ok(registered.writeFile, "writeFile handler not registered");
assert.ok(registered.deleteFile, "deleteFile handler not registered");
return registered;
}
// Load fsOpReply/fsOpFallbackToast themselves from source (they carry the
// ack-vs-legacy-toast gating under test). The slice ends at the join handler,
// which directly follows the helpers. io/deny are injected at load time so
// the returned helpers close over the same fakes the handlers get.
function loadFsReplyHelpers(io, deny) {
const slice = sliceBetween(
indexSource,
"function fsOpReply",
'socket.on("join"',
"index.js fs reply helpers"
);
const fakes = makeFakes();
return new Function("io", "deny", "getServerStatusRoom", `
${slice};
return { fsOpReply, fsOpFallbackToast };
`)(io || fakes.io, deny || fakes.deny, getServerStatusRoom);
}
// ---------------------------------------------------------------------------
// Server: writeFile
// ---------------------------------------------------------------------------
test("writeFile acks success with the server message and does not toast acked clients", async () => {
const fakes = makeFakes();
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "config.yml", content: "data" }, (res) => acks.push(res));
assert.strictEqual(acks.length, 1);
assert.deepStrictEqual(acks[0], { ok: true, msg: "Saved config.yml" });
assert.strictEqual(fakes.calls.toasts.length, 0);
assert.strictEqual(fakes.calls.denies.length, 0);
});
test("writeFile acks the overwrite 409 denial and keeps the console deny", async () => {
const fakes = makeFakes({
nodeFsPostImpl: async () => ({ status: 409, json: { ok: false } }),
});
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "server.properties", content: "x" }, (res) => acks.push(res));
assert.strictEqual(acks.length, 1);
assert.strictEqual(acks[0].ok, false);
assert.match(acks[0].msg, /Edit existing files/);
assert.strictEqual(fakes.calls.toasts.length, 0, "acked client must not get the room toast");
assert.strictEqual(fakes.calls.denies.length, 1, "console deny preserved");
});
test("writeFile acks the create-file 404 denial", async () => {
const fakes = makeFakes({
nodeFsPostImpl: async () => ({ status: 404, json: { ok: false, existed: false } }),
});
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "new.txt", content: "x" }, (res) => acks.push(res));
assert.strictEqual(acks[0].ok, false);
assert.match(acks[0].msg, /Create files\/folders/);
});
test("writeFile acks permission, suspension, access and node-resolution failures", async () => {
const variants = [
{ opts: { writeMode: { ok: false, mode: "" } }, match: /not allowed to edit files/ },
{ opts: { suspended: true }, match: /suspended/ },
{ opts: { accessible: false }, match: /not allowed to edit files/ },
{ opts: { ctx: { remote: false } }, match: /server not found on node/ },
];
for (const { opts, match } of variants) {
const fakes = makeFakes(opts);
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "f.txt", content: "x" }, (res) => acks.push(res));
assert.strictEqual(acks.length, 1, JSON.stringify(opts));
assert.strictEqual(acks[0].ok, false, JSON.stringify(opts));
assert.match(acks[0].msg, match, JSON.stringify(opts));
assert.strictEqual(fakes.calls.toasts.length, 0, JSON.stringify(opts));
}
});
test("writeFile acks internal error when the node call throws", async () => {
const fakes = makeFakes({ nodeFsPostImpl: async () => { throw new Error("boom"); } });
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "f.txt", content: "x" }, (res) => acks.push(res));
assert.strictEqual(acks[0].ok, false);
assert.match(acks[0].msg, /internal error/);
assert.strictEqual(fakes.calls.toasts.length, 0);
});
test("writeFile falls back to the room toast only when the client sent no ack", async () => {
const fakes = makeFakes();
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
await handlers.writeFile({ bot: "srv", path: "f.txt", content: "x" }); // legacy: no ack callback
assert.strictEqual(fakes.calls.toasts.length, 1);
assert.strictEqual(fakes.calls.toasts[0].room, "server-status:srv");
assert.strictEqual(fakes.calls.toasts[0].payload.type, "success");
assert.strictEqual(fakes.calls.toasts[0].payload.msg, "Saved f.txt");
});
test("writeFile acks the 10 MB payload pre-check and the daemon content-too-large backstop", async () => {
// Pre-check path: oversized payload never reaches the node.
let nodeCalled = false;
const preCheck = makeFakes({
writeTooLarge: true,
nodeFsPostImpl: async () => { nodeCalled = true; return { status: 200, json: { ok: true } }; },
});
Object.assign(preCheck, loadFsReplyHelpers(preCheck.io, preCheck.deny));
const preHandlers = loadFsHandlers(preCheck);
const preAcks = [];
await preHandlers.writeFile({ bot: "srv", path: "big.bin", content: "x" }, (res) => preAcks.push(res));
assert.deepStrictEqual(preAcks[0], { ok: false, msg: preCheck.FILE_WRITE_LIMIT_CLIENT_MESSAGE });
assert.strictEqual(nodeCalled, false, "oversized write must not reach the node");
// Backstop path: the daemon's 400 "content too large" surfaces as the limit
// message, not "Save failed: internal error". The daemon split its old
// combined "bad json or content too large (max 10MB)" message (malformed
// bodies now get "invalid JSON body" instead), so over-cap bodies answer
// "content too large (max 10MB)" — and the substring match must keep
// mapping the legacy combined wording from older daemons too.
const backstop = makeFakes({
nodeFsPostImpl: async () => ({ status: 400, json: { ok: false, error: "content too large (max 10MB)" } }),
});
Object.assign(backstop, loadFsReplyHelpers(backstop.io, backstop.deny));
const backstopHandlers = loadFsHandlers(backstop);
const backstopAcks = [];
await backstopHandlers.writeFile({ bot: "srv", path: "big.bin", content: "x" }, (res) => backstopAcks.push(res));
assert.deepStrictEqual(backstopAcks[0], { ok: false, msg: backstop.FILE_WRITE_LIMIT_CLIENT_MESSAGE });
// Legacy daemon wording (pre split-contract) keeps mapping by substring.
const legacyBackstop = makeFakes({
nodeFsPostImpl: async () => ({ status: 400, json: { ok: false, error: "bad json or content too large (max 10MB)" } }),
});
Object.assign(legacyBackstop, loadFsReplyHelpers(legacyBackstop.io, legacyBackstop.deny));
const legacyBackstopHandlers = loadFsHandlers(legacyBackstop);
const legacyBackstopAcks = [];
await legacyBackstopHandlers.writeFile({ bot: "srv", path: "big.bin", content: "x" }, (res) => legacyBackstopAcks.push(res));
assert.deepStrictEqual(legacyBackstopAcks[0], { ok: false, msg: legacyBackstop.FILE_WRITE_LIMIT_CLIENT_MESSAGE });
// The split-contract malformed-body wording must NOT map to the limit
// message (it falls through as a write failure instead).
const malformed = makeFakes({
nodeFsPostImpl: async () => ({ status: 400, json: { ok: false, error: "invalid JSON body" } }),
});
Object.assign(malformed, loadFsReplyHelpers(malformed.io, malformed.deny));
const malformedHandlers = loadFsHandlers(malformed);
const malformedAcks = [];
await malformedHandlers.writeFile({ bot: "srv", path: "a.txt", content: "x" }, (res) => malformedAcks.push(res));
assert.notStrictEqual(malformedAcks[0].msg, malformed.FILE_WRITE_LIMIT_CLIENT_MESSAGE);
});
// ---------------------------------------------------------------------------
// Server: writeFile — the adpanel:editor-save-occ concurrency guard
// ---------------------------------------------------------------------------
test("writeFile skips the staleness guard when the save carries no expectedSha256 (opt-in)", async () => {
const nodeCalls = [];
const fakes = makeFakes({
nodeFsPostImpl: async (_node, endpoint, payload) => {
nodeCalls.push({ endpoint, payload });
return { status: 200, json: { ok: true } };
},
});
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
// Absent field (every pre-existing emitter) and a non-string field both
// keep the legacy write: the guard is opt-in.
await handlers.writeFile({ bot: "srv", path: "f.txt", content: "x" }, (res) => acks.push(res));
await handlers.writeFile({ bot: "srv", path: "f.txt", content: "x", expectedSha256: 12345 }, (res) => acks.push(res));
assert.deepStrictEqual(acks, [{ ok: true, msg: "Saved f.txt" }, { ok: true, msg: "Saved f.txt" }]);
assert.strictEqual(nodeCalls.length, 2);
assert.ok(nodeCalls.every(({ endpoint, payload }) => endpoint === "/v1/fs/write" && !("editorBaseSha256" in payload)));
});
test("writeFile sends its precondition to the daemon and acknowledges a conflict without retrying", async () => {
const nodeCalls = [];
const ctx = { remote: true, baseDir: "/srv", serverName: "srv", node: { address: "10.0.0.9" } };
const fakes = makeFakes({
ctx,
nodeFsPostImpl: async (...args) => {
nodeCalls.push(args);
return { status: 409, json: { code: "file_changed_on_disk" } };
},
});
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "config.yml", content: "stale", expectedSha256: "a".repeat(64) }, (res) => acks.push(res));
assert.deepStrictEqual(nodeCalls, [[ctx.node, "/v1/fs/write", {
server: "srv", path: "/srv/config.yml", content: "stale", encoding: "utf8", mode: "", editorBaseSha256: "a".repeat(64),
}, 120000]]);
assert.strictEqual(fakes.calls.toasts.length, 0);
assert.strictEqual(fakes.calls.denies.length, 0, "a staleness conflict is not a permission denial");
assert.deepStrictEqual(acks, [{
ok: false,
msg: FS_WRITE_STALE_CONFLICT_MESSAGE,
code: "file_changed_on_disk",
}]);
});
test("writeFile reports success when the daemon accepts the guarded write", async () => {
const nodeCalls = [];
const fakes = makeFakes({
nodeFsPostImpl: async (_node, endpoint, payload) => {
nodeCalls.push({ endpoint, payload });
return { status: 200, json: { ok: true } };
},
});
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "f.txt", content: "x", expectedSha256: "b".repeat(64) }, (res) => acks.push(res));
assert.deepStrictEqual(acks, [{ ok: true, msg: "Saved f.txt" }]);
assert.strictEqual(nodeCalls.length, 1);
assert.strictEqual(nodeCalls[0].endpoint, "/v1/fs/write");
assert.strictEqual(nodeCalls[0].payload.editorBaseSha256, "b".repeat(64));
});
test("writeFile refuses a malformed hash without dialing the node", async () => {
let nodeCalls = 0;
const fakes = makeFakes({ nodeFsPostImpl: async () => { nodeCalls++; } });
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.writeFile({ bot: "srv", path: "f.txt", content: "x", expectedSha256: "nope" }, (res) => acks.push(res));
assert.deepStrictEqual(acks, [{ ok: false, msg: "invalid expectedSha256" }]);
assert.strictEqual(nodeCalls, 0);
});
// ---------------------------------------------------------------------------
// Server: deleteFile
// ---------------------------------------------------------------------------
test("deleteFile acks success and denial paths", async () => {
const fakes = makeFakes();
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.deleteFile({ bot: "srv", path: "old.log", isDir: false }, (res) => acks.push(res));
assert.deepStrictEqual(acks[0], { ok: true, msg: "Deleted old.log" });
assert.strictEqual(fakes.calls.toasts.length, 0);
});
test("deleteFile acks missing files_delete, suspension and node-resolution failures", async () => {
const variants = [
{ opts: { filesDeletePerm: false }, match: /not allowed to delete files/ },
{ opts: { suspended: true }, match: /suspended/ },
{ opts: { accessible: false }, match: /not allowed to delete files/ },
{ opts: { ctx: { remote: false } }, match: /server not found on node/ },
{ opts: { nodeFsPostImpl: async () => { throw new Error("boom"); } }, match: /internal error/ },
];
for (const { opts, match } of variants) {
const fakes = makeFakes(opts);
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
await handlers.deleteFile({ bot: "srv", path: "f", isDir: false }, (res) => acks.push(res));
assert.strictEqual(acks.length, 1, JSON.stringify(opts));
assert.strictEqual(acks[0].ok, false, JSON.stringify(opts));
assert.match(acks[0].msg, match, JSON.stringify(opts));
assert.strictEqual(fakes.calls.toasts.length, 0, JSON.stringify(opts));
}
});
test("deleteFile toasts only for legacy no-ack clients", async () => {
const fakes = makeFakes();
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
await handlers.deleteFile({ bot: "srv", path: "f", isDir: false });
assert.strictEqual(fakes.calls.toasts.length, 1);
assert.strictEqual(fakes.calls.toasts[0].room, "server-status:srv");
assert.strictEqual(fakes.calls.toasts[0].payload.type, "success");
});
test("deleteFile refuses the server root without calling the node", async () => {
let nodeCalled = false;
const fakes = makeFakes({
nodeFsPostImpl: async () => { nodeCalled = true; return { status: 200, json: { ok: true } }; },
});
Object.assign(fakes, loadFsReplyHelpers(fakes.io, fakes.deny));
const handlers = loadFsHandlers(fakes);
const acks = [];
// The harness safeJoinUnix joins rel "" to baseDir + "/", which the guard
// recognizes as the server root (same as rel "." in production).
await handlers.deleteFile({ bot: "srv", path: "", isDir: true }, (res) => acks.push(res));
assert.deepStrictEqual(acks[0], { ok: false, msg: "Delete failed: refusing to delete the server root" });
assert.strictEqual(nodeCalled, false, "root deletion must never reach the node");
assert.strictEqual(fakes.calls.toasts.length, 0);
});
// ---------------------------------------------------------------------------
// Server helpers: ack-vs-legacy-toast gating
// ---------------------------------------------------------------------------
test("fsOpFallbackToast is a no-op when an ack was provided", () => {
const { fsOpReply, fsOpFallbackToast } = loadFsReplyHelpers();
const fakes = makeFakes();
const acks = [];
fsOpReply((res) => acks.push(res), true, "Saved f.txt");
fsOpFallbackToast((res) => acks.push(res), "srv", "success", "Saved f.txt");
assert.deepStrictEqual(acks, [{ ok: true, msg: "Saved f.txt" }]);
assert.strictEqual(fakes.calls.toasts.length, 0);
});
test("fsOpReply tolerates throwing acks and non-function acks", () => {
const { fsOpReply } = loadFsReplyHelpers();
assert.doesNotThrow(() => fsOpReply(undefined, true, "x"));
assert.doesNotThrow(() => fsOpReply(() => { throw new Error("gone"); }, true, "x"));
});
// ---------------------------------------------------------------------------
// Client: socketFsRequest (bot.js slice)
// ---------------------------------------------------------------------------
// The slice spans the ack timeout constant and the socketFsRequest helper —
// both free of DOM access, closing only over `socket`.
const clientFsSlice = sliceBetween(
botSource,
"const FS_SOCKET_ACK_TIMEOUT_MS",
"async function apiWriteFile",
"bot.js socketFsRequest"
);
function loadClientFsHelper(fakeSocket) {
return new Function("socket", `${clientFsSlice}; return socketFsRequest;`)(fakeSocket);
}
function makeFakeSioSocket() {
const state = { timeoutMs: null, emitArgs: null, ack: null };
const socket = {
timeout(ms) { state.timeoutMs = ms; return socket; },
emit(event, payload, ack) {
state.emitArgs = { event, payload };
state.ack = ack;
},
};
return { socket, state };
}
test("socketFsRequest resolves with the server message on ok ack", async () => {
const { socket, state } = makeFakeSioSocket();
const socketFsRequest = loadClientFsHelper(socket);
const p = socketFsRequest("writeFile", { bot: "srv", path: "f.txt", content: "x" }, "Save");
assert.strictEqual(state.emitArgs.event, "writeFile");
assert.strictEqual(state.timeoutMs, 125000, "ack timeout must exceed the 120s node-call budget");
state.ack(null, { ok: true, msg: "Saved f.txt" });
assert.strictEqual(await p, "Saved f.txt");
});
test("socketFsRequest rejects with the server's denial message", async () => {
const { socket, state } = makeFakeSioSocket();
const socketFsRequest = loadClientFsHelper(socket);
const p = socketFsRequest("writeFile", { bot: "srv", path: "f.txt", content: "x" }, "Save");
state.ack(null, { ok: false, msg: "Overwriting existing files requires the 'Edit existing files' permission." });
await assert.rejects(p, /Edit existing files/);
});
test("socketFsRequest rejects on ack timeout instead of assuming success", async () => {
const { socket, state } = makeFakeSioSocket();
const socketFsRequest = loadClientFsHelper(socket);
const p = socketFsRequest("deleteFile", { bot: "srv", path: "f", isDir: false }, "Delete");
assert.strictEqual(state.emitArgs.event, "deleteFile");
state.ack(new Error("operation has timed out"));
await assert.rejects(p, /timed out/);
});
test("socketFsRequest fails fast on sockets without ack support", async () => {
const socketFsRequest = loadClientFsHelper({ on() {}, emit() {}, connected: false });
await assert.rejects(
socketFsRequest("writeFile", { bot: "srv", path: "f.txt", content: "x" }, "Save"),
/Not connected/
);
});
test("socketFsRequest rejects malformed ack payloads", async () => {
const { socket, state } = makeFakeSioSocket();
const socketFsRequest = loadClientFsHelper(socket);
const p = socketFsRequest("writeFile", { bot: "srv", path: "f.txt", content: "x" }, "Save");
state.ack(null, undefined);
await assert.rejects(p, /Save failed/);
});
// ---------------------------------------------------------------------------
// Wiring locks (source assertions)
// ---------------------------------------------------------------------------
test("bot.js no longer fire-and-forgets writeFile/deleteFile", () => {
assert.ok(!botSource.includes('socket.emit("writeFile"'), "fire-and-forget writeFile must be gone");
assert.ok(!botSource.includes('socket.emit("deleteFile"'), "fire-and-forget deleteFile must be gone");
assert.ok(botSource.includes('socketFsRequest("writeFile"'), "apiWriteFile must use the acked path");
assert.ok(botSource.includes('socketFsRequest("deleteFile"'), "apiDelete must use the acked path");
});
test("index.js toast emissions live only in the legacy fallback helper", () => {
const helpers = loadFsReplyHelpers();
assert.strictEqual(typeof helpers.fsOpReply, "function");
assert.strictEqual(typeof helpers.fsOpFallbackToast, "function");
const handlerSlice = sliceBetween(
indexSource,
'socket.on("writeFile"',
'socket.on("action"',
"index.js fs handlers"
);
assert.ok(!handlerSlice.includes('emit("toast"'),
"handlers must report through the ack, not the room toast");
const helperSlice = sliceBetween(
indexSource,
"function fsOpFallbackToast",
'socket.on("join"',
"index.js fallback helper"
);
assert.strictEqual(helperSlice.split('emit("toast"').length - 1, 1,
"the fallback helper is the only place emitting the room toast");
assert.ok(helperSlice.includes('typeof ack === "function"'),
"the room toast must be gated on a missing ack");
});
test("editor save paths carry the loaded hash as a daemon write precondition", () => {
const relaySrc = fs.readFileSync(path.join(ROOT, "services", "node-fs-relay.js"), "utf8");
assert.ok(relaySrc.includes("function attachEditorWriteHash("),
"the shared guard must be exported from services/node-fs-relay.js (one home)");
assert.ok(relaySrc.includes('const FS_WRITE_STALE_CONFLICT_ERROR = "file_changed_on_disk";'),
"the conflict wire code lives in the shared module, not re-typed per surface");
const routeWindow = sliceBetween(
indexSource,
'app.put("/api/servers/:name/files/write"',
'app.post("/api/servers/:name/files/mkdir"',
"index.js files/write route"
);
const handlerSlice = sliceBetween(
indexSource,
'socket.on("writeFile"',
'socket.on("action"',
"index.js fs handlers"
);
for (const [label, window] of [["REST write route", routeWindow], ["socket writeFile handler", handlerSlice]]) {
const attach = window.indexOf("attachEditorWriteHash(writePayload");
const checkSize = window.indexOf("nodeFsWritePayloadTooLarge(writePayload)");
assert.ok(attach >= 0 && attach < checkSize && checkSize < window.indexOf('"/v1/fs/write"'),
`${label} includes the hash in the bounded daemon write`);
assert.doesNotMatch(window, /verifyNodeFileUnchanged/);
}
// Client side: only the editor's save paths carry the base hash.
assert.ok(botSource.includes("payload.expectedSha256 = expectedSha256"),
"the editor socket save must attach expectedSha256 to the writeFile emit");
assert.ok(botSource.includes("writeServerFileWithActionToken(bot, relPath, content, expectedSha256)"),
"the oversized editor-save fallback must forward the hash to PUT /files/write");
const openEditor = sliceBetween(botSource, "async function openEditorModal(", "function closeEditorModal(");
const rawHashAt = openEditor.indexOf('const baseSha256 = await computeEditorBaseSha256(content || "")');
assert.ok(rawHashAt >= 0 && rawHashAt < openEditor.indexOf("const normalized = normalizeInput("),
"the editor open must base the hash on the exact loaded content (pre-normalizeInput)");
assert.match(openEditor, /editorBaseSha256 = baseSha256;/, "the editor must commit the raw hash for the displayed file");
assert.ok(botSource.includes("err.code === EDITOR_SAVE_CONFLICT_CODE"),
"performSave must react to the conflict code with its reload confirm");
// Client side, REMOTE_MODE branch: the relay write now runs the shared
// guard too, so the hash must ride along (same opt-in shape as the local
// paths — omitted when empty) and a relay 409 must carry the code on the
// thrown Error so the SAME performSave conflict handling runs uniformly.
const remoteSaveBranch = sliceBetween(
botSource,
"const savePayload = { path: relPath, content };",
"async function apiDelete(",
"bot.js apiWriteFile REMOTE_MODE branch"
);
assert.ok(remoteSaveBranch.includes("if (expectedSha256) savePayload.expectedSha256 = expectedSha256;"),
"the REMOTE_MODE save must attach expectedSha256 when a base hash exists (omitted when empty — the server gate is opt-in)");
assert.ok(remoteSaveBranch.includes("body: JSON.stringify(savePayload)"),
"the remote relay POST must send the guarded payload");
assert.ok(
remoteSaveBranch.includes("r.status === 409 && j && j.error === EDITOR_SAVE_CONFLICT_CODE") &&
remoteSaveBranch.includes("conflict.code = EDITOR_SAVE_CONFLICT_CODE;"),
"a relay 409 file_changed_on_disk must surface through err.code (performSave's reload confirm must work on the remote path too)"
);
// adpanel:editor-save-occ — the success-path re-base must be gated on the
// editor still showing the saved file. The open entry points do not block
// on editorSaving, so file B can be open while file A's save settles; an
// ungated re-base stamps B's baseline and base hash with A's saved content,
// so B's next save sends hash(A) (guaranteed spurious 409) and
// isEditorDirty() compares against the wrong baseline. The 409 branch
// already carries this guard — the success branch must not be the copy
// that drifted.
const successRebase = sliceBetween(
botSource,
"const savedMsg = await apiWriteFile(path, contentToSave, editorBaseSha256);",
"} catch (err) {",
"bot.js performSave success path"
);
const rebaseGuard = "if (documentGeneration === editorDocumentGeneration) {";
const rebaseGateAt = successRebase.indexOf(rebaseGuard);
assert.ok(rebaseGateAt >= 0,
"the success-path re-base must belong to the same editor document");
for (const rebaseLine of [
"editorOriginalContent = contentToSave;",
"editorBaseSha256 = savedBaseSha256;",
"monacoEditor.__originalValue = contentToSave;",
"textArea.dataset.original = contentToSave;",
]) {
const at = successRebase.indexOf(rebaseLine);
assert.ok(at > rebaseGateAt,
`the re-base assignment "${rebaseLine}" must sit inside the editor document guard`);
}
// (Follow-up closure) the pre-await gate alone is racy: the digest's await
// is exactly where openEditorModal(B) can complete, so the gate must be
// re-checked AFTER the await and BEFORE the four assignments — the digest
// is computed first (into savedBaseSha256) and only stamped when the editor
// still shows the saved file. A pre-await assignment of the baseline, or a
// post-await stamp without a re-check, reintroduces the hash(A)-on-B bug
// this gate exists to prevent.
const digestAt = successRebase.indexOf("await computeEditorBaseSha256(contentToSave)");
const reGateAt = successRebase.indexOf(rebaseGuard, digestAt);
const firstAssignAt = successRebase.indexOf("editorOriginalContent = contentToSave;");
assert.ok(digestAt > rebaseGateAt,
"the base digest must be computed inside the outer editor document gate (no assignment before it)");
assert.ok(reGateAt > digestAt,
"the editor document gate must be re-checked after the digest await");
assert.ok(firstAssignAt > reGateAt,
"the re-base assignments must sit inside the post-await re-gate, so a mid-digest file switch skips them silently (save + toast stay unconditional)");
// The success feedback must survive the guard: the write landed, so the
// user must never be told the save failed even when the editor moved on.
assert.ok(successRebase.includes("showStoreToast(") && successRebase.includes("`Saved ${path}`"),
"the success toast must stay outside the re-base guard and keep naming the saved file");
assert.ok(successRebase.includes("editorSaveSucceeded = true;"),
"the save must still report success to its caller");
});