From a4eed1e219dbd15e186c4baedd78410fa8637ea5 Mon Sep 17 00:00:00 2001 From: Jason Woltje Date: Tue, 10 Nov 2026 16:19:10 -0600 Subject: [PATCH] fix(agents): A2 review round: config check, name rule, drafts and test gaps (#1873) The CLI agent verbs validate the instance config through loadSystem before any read or write, and print a fixed line for errors they do not own. The root writer refuses a config directory with an ancestor another user can write without the sticky bit. The project HTTP route checks agent names with the organization ID_PATTERN and answers 400 naming the key. The Settings level forms take their own class, so the role-instance handlers no longer catch them, and keep both drafts in module state with the revision each began at. The organization writer tests now reach the file's own uid check and test the assistant protection with an assistant in the fixture. --- packages/cli/src/agent-levels.mjs | 24 ++++++-- packages/cli/tests/agent-levels-cli.test.mjs | 38 ++++++++++++- .../organization/src/agent-levels-write.mjs | 24 +++++--- .../tests/agent-levels-write.test.mjs | 50 +++++++++++----- packages/webui/src/agent-levels-write.mjs | 10 +++- packages/webui/src/public/agents.js | 57 ++++++++++++++----- packages/webui/src/public/bus.js | 4 +- packages/webui/src/public/shell.css | 10 ++-- .../tests/agent-levels-edit-browser.test.mjs | 55 +++++++++++++++++- .../tests/agent-levels-write-http.test.mjs | 8 +++ 10 files changed, 226 insertions(+), 54 deletions(-) diff --git a/packages/cli/src/agent-levels.mjs b/packages/cli/src/agent-levels.mjs index 3a81f42ea..8778367ad 100644 --- a/packages/cli/src/agent-levels.mjs +++ b/packages/cli/src/agent-levels.mjs @@ -19,9 +19,10 @@ // A write prints its receipt; refusals name keys, never values. import { configDir } from '../../organization/src/organization-config.mjs'; -import { organizationWriter } from '../../organization/src/organization.mjs'; +import { OrgError } from '../../organization/src/org-registry.mjs'; +import { OrganizationError, organizationWriter } from '../../organization/src/organization.mjs'; import { changeRootAgent, patchRootEntry, projectAgentSummary, readRootAgentsFile, rootAgentSummary } from '../../organization/src/agent-levels-write.mjs'; -import { rolesDir } from './config.mjs'; +import { loadSystem, rolesDir } from './config.mjs'; import { DEV_OWNER, devOwnerInstance } from './dev-local-owner.mjs'; import { CliError } from './errors.mjs'; import { refuseInsideAgent } from './transport.mjs'; @@ -82,15 +83,26 @@ function vars(parsed, line) { const revisionOf = (parsed, read) => parsed.single['--revision'] ?? read(); function owner(io) { refuseInsideAgent(io.env); - devOwnerInstance(io.env); + // Its refusal is one fixed line naming no path. + let instance; + try { instance = devOwnerInstance(io.env); } catch (error) { throw error instanceof CliError ? error : new CliError(String(error?.message), 2); } + // The instance's system config must exist and validate, marker included, as `mosaic org` checks: + // a missing or broken config refuses (exit 3) before anything is read or written. + loadSystem({ env: io.env, instance }); return { dir: configDir(io.env), roles: rolesDir(io.env) }; } +// Only the writers' own coded refusals print their text (it names keys and ids, never a value). +// Anything else, a filesystem error above all, prints its code and a fixed line: its message can +// hold a host path. So does a coded refusal whose text happens to hold an absolute path. +const ABSOLUTE_PATH = /(?:^|[\s('"=:])\/[^\s/]/; function refusal(error) { if (error instanceof CliError) return error; - const code = typeof error?.code === 'string' ? error.code : null; + const code = typeof error?.code === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(error.code) ? error.code : null; + const ours = (error instanceof OrgError || error instanceof OrganizationError || error?.name === 'BusinessError') && code !== null; + const text = ours && typeof error.message === 'string' && !ABSOLUTE_PATH.test(error.message) ? error.message : 'the operation failed; the error text is not shown'; // A refusal after the replace says the change landed; the receipt may be missing. const landed = error?.committed ? ' (the change was written; its receipt may be missing)' : ''; - return new CliError(`${code ? `${code}: ` : ''}${error?.message ?? String(error)}${landed}`, 2); + return new CliError(`${code ? `${code}: ` : ''}${text}${landed}`, 2); } export async function agentsRootCommand(args, io) { @@ -145,7 +157,7 @@ export async function projectAgentsCommand(args, io) { if (name !== undefined) throw usage('list takes no name', line); only(parsed, ['--org', '--json'], line); const { document, revision } = writer.read(org); - if (!Object.hasOwn(document.projects ?? {}, project)) throw Object.assign(new Error(`project ${project} is not in organization ${org}`), { code: 'project-not-found' }); + if (!Object.hasOwn(document.projects ?? {}, project)) throw new OrgError('project-not-found', `project ${project} is not in organization ${org}`); const listing = { organization: org, project, revision, agents: projectAgentSummary(document.projects[project].agents ?? {}) }; io.stdout.write(parsed.flags.has('--json') ? `${JSON.stringify(listing, null, 2)}\n` : formatProject(listing)); return; diff --git a/packages/cli/tests/agent-levels-cli.test.mjs b/packages/cli/tests/agent-levels-cli.test.mjs index cf4c9a956..2b76bd697 100644 --- a/packages/cli/tests/agent-levels-cli.test.mjs +++ b/packages/cli/tests/agent-levels-cli.test.mjs @@ -3,7 +3,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { existsSync, mkdtempSync, readFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; import { tmpdir } from 'node:os'; import { spawnSync } from 'node:child_process'; @@ -69,6 +69,42 @@ test('agents root list, set, remove: each write prints its receipt, values stay assert.equal(unknown.status, 4); assert.ok(!unknown.stderr.includes(SECRET)); }); +test('a filesystem failure prints its code and a fixed line, never a host path', () => { + const { run, configDir, home } = instance(); + // A directory where the receipt file goes: opening it fails EISDIR, whose message holds the path. + mkdirSync(join(configDir, 'agents-receipts.jsonl')); + const r = run(['agents', 'root', 'set', 'researcher', '--definition', 'research']); + assert.equal(r.status, 2, r.stderr); + assert.match(r.stderr, /EISDIR: the operation failed; the error text is not shown/); + assert.ok(!r.stderr.includes(home), r.stderr); + assert.equal(existsSync(join(configDir, 'agents.json')), false); +}); + +test('a missing, malformed or unclaimed instance config refuses before anything is read or written', () => { + const verbs = [['agents', 'root', 'set', 'researcher', '--definition', 'research'], ['agents', 'root', 'list'], ['project', 'agents', 'work', '--org', 'alpha', 'exclude', 'coder']]; + const check = (env, dir, why) => { + for (const args of verbs) { + const r = spawnSync(join(repo, 'scripts/mosaic'), args, { cwd: repo, env, encoding: 'utf8' }); + assert.equal(r.status, 3, `${why} ${args.join(' ')}: ${r.stderr}`); assert.match(r.stderr, /system config problem/); + } + assert.equal(existsSync(join(dir, 'agents.json')), false, why); + assert.equal(existsSync(join(dir, 'agents-receipts.jsonl')), false, why); + }; + // Missing: the instance's config directory exists, its config.json does not. + const home = mkdtempSync(join(tmpdir(), 'a2cfg-')); + const dir = join(home, '.config/mosaic-atwo'); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const env = { PATH: process.env.PATH, LANG: 'C.UTF-8', TMPDIR: process.env.TMPDIR ?? tmpdir(), HOME: home, MOSAIC_CONFIG: join(dir, 'config.json') }; + check(env, dir, 'missing'); + writeFileSync(join(dir, 'config.json'), '{', { mode: 0o600 }); + check(env, dir, 'malformed'); + // Unclaimed: a bootstrapped instance whose data root marker names another instance. + const booted = instance(); + const { dataRoot } = JSON.parse(readFileSync(booted.env.MOSAIC_CONFIG, 'utf8')); + writeFileSync(join(dataRoot, 'instance.json'), JSON.stringify({ instanceVersion: 1, name: 'other' })); + check(booted.env, booted.configDir, 'marker'); +}); + test('the default instance refuses the agent level verbs', () => { const home = mkdtempSync(join(tmpdir(), 'a2def-')); const env = { PATH: process.env.PATH, LANG: 'C.UTF-8', TMPDIR: process.env.TMPDIR ?? tmpdir(), HOME: home }; diff --git a/packages/organization/src/agent-levels-write.mjs b/packages/organization/src/agent-levels-write.mjs index 30579fcb8..7badc3589 100644 --- a/packages/organization/src/agent-levels-write.mjs +++ b/packages/organization/src/agent-levels-write.mjs @@ -38,15 +38,22 @@ export function requireRootOwner(actor, owner) { fail('human-required', 'only the signed-in owner writes the root agent file'); } -// Every ancestor a real directory, configDir this uid's and not group or other writable. +// Every ancestor a real directory that only root or this uid can change: owned by one of them, and +// group or other writable only with the sticky bit (as /tmp is), so no other user can rename or +// replace configDir between these checks and the path-based lock, temp file and rename. configDir +// itself is this uid's and not group or other writable. function assertConfigDir(configDir, uid) { if (typeof configDir !== 'string' || resolve(configDir) !== configDir) fail('agents-unsafe', 'config directory must be an absolute normalized path'); let current = parse(configDir).root; + const trusted = st => (st.uid === 0 || st.uid === uid) && (!(st.mode & 0o022) || (st.mode & 0o1000)); + try { if (!trusted(lstatSync(current))) fail('agents-unsafe', `a config directory ancestor must belong to root or uid ${uid} and not be writable by others without the sticky bit`); } + catch (error) { if (error instanceof OrgError) throw error; fail('agents-unsafe', 'config directory is missing'); } for (const part of configDir.slice(current.length).split('/').filter(Boolean)) { current = join(current, part); let st; try { st = lstatSync(current); } catch { fail('agents-unsafe', 'config directory is missing'); } if (!st.isDirectory() || st.isSymbolicLink()) fail('agents-unsafe', 'config path contains a symbolic link or non-directory'); + if (current !== configDir && !trusted(st)) fail('agents-unsafe', `a config directory ancestor must belong to root or uid ${uid} and not be writable by others without the sticky bit`); } const st = lstatSync(configDir); if (st.uid !== uid) fail('agents-unsafe', `config directory must belong to uid ${uid}`); @@ -55,7 +62,7 @@ function assertConfigDir(configDir, uid) { // The reader's descriptor checks (loadRootAgents), plus one link: a regular file, no symbolic link, // this uid, no group or other write. Missing is an empty root level at ABSENT_REVISION. -async function readCurrent(configDir, uid) { +async function readCurrent(configDir, uid, statFile = fd => fd.stat()) { const file = rootAgentsPath(configDir); let fd; try { fd = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } @@ -65,7 +72,7 @@ async function readCurrent(configDir, uid) { } let bytes; try { - const st = await fd.stat(); + const st = await statFile(fd); if (!st.isFile()) fail('agents-unsafe', `root agent file must be a regular file, not a symbolic link (${ROOT_FILE})`); if (st.uid !== uid) fail('agents-unsafe', `root agent file must belong to uid ${uid} (${ROOT_FILE})`); if (st.mode & 0o022) fail('agents-unsafe', `root agent file must not be writable by group or other (${ROOT_FILE})`); @@ -80,9 +87,10 @@ async function readCurrent(configDir, uid) { // The file's document and revision, for a form or a CLI list. A file that is not a root agent // document at all refuses; one with a bad entry reads, so the owner can fix or remove that entry. -export async function readRootAgentsFile(configDir, { uid = process.geteuid() } = {}) { +// statFile is a test seam for the descriptor stat; it grants nothing a caller's uid does not. +export async function readRootAgentsFile(configDir, { uid = process.geteuid(), statFile } = {}) { assertConfigDir(configDir, uid); - const current = await readCurrent(configDir, uid); + const current = await readCurrent(configDir, uid, statFile); shape(current.document); return current; } @@ -172,7 +180,7 @@ async function syncDirectory(dir) { // Change one root agent. `entry` is the new entry, null to remove it, or a function of the old // entry (undefined when there is none) returning either. Returns the receipt. An error after the // rename carries committed: true, so a caller never retries a write that landed. -export async function changeRootAgent(configDir, { revision, name, entry }, { actor, owner, rolesDir, uid = process.geteuid(), beforeReplace, syncDirectory: syncDir = syncDirectory } = {}) { +export async function changeRootAgent(configDir, { revision, name, entry }, { actor, owner, rolesDir, uid = process.geteuid(), beforeReplace, statFile, syncDirectory: syncDir = syncDirectory } = {}) { requireRootOwner(actor, owner); if (typeof name !== 'string' || !ID_PATTERN.test(name)) fail('agents-invalid', 'agent name must be an id: lowercase letters, digits, dot, dash or underscore, at most 64'); if (typeof revision !== 'string' || !REVISION.test(revision)) fail('revision-conflict', 'a root agent change needs the revision it was read at'); @@ -188,7 +196,7 @@ export async function changeRootAgent(configDir, { revision, name, entry }, { ac let temp, receiptFd, committed = false; try { assertConfigDir(configDir, uid); - const before = await readCurrent(configDir, uid); + const before = await readCurrent(configDir, uid, statFile); if (before.revision !== revision) fail('revision-conflict', 'the root agent file changed since it was read; read it again'); shape(before.document); const old = Object.hasOwn(before.document.agents, name) ? before.document.agents[name] : undefined; @@ -219,7 +227,7 @@ export async function changeRootAgent(configDir, { revision, name, entry }, { ac try { await fd.writeFile(bytes); await fd.sync(); } finally { await fd.close(); } await beforeReplace?.(); // A writer that ignores the lock still loses: the bytes must be the ones read. - const again = await readCurrent(configDir, uid); + const again = await readCurrent(configDir, uid, statFile); if (again.exists !== before.exists || again.revision !== before.revision) fail('revision-conflict', 'the root agent file changed before the write; read it again'); // A new file is published with link, which fails rather than replace a file made meanwhile. if (before.exists) await fs.rename(temp, file); diff --git a/packages/organization/tests/agent-levels-write.test.mjs b/packages/organization/tests/agent-levels-write.test.mjs index 4134a771c..bb996fafb 100644 --- a/packages/organization/tests/agent-levels-write.test.mjs +++ b/packages/organization/tests/agent-levels-write.test.mjs @@ -4,10 +4,10 @@ import test from "node:test"; import assert from "node:assert/strict"; import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { loadRootAgents } from "../src/agent-levels.mjs"; import { - ABSENT_REVISION, ROOT_RECEIPTS, changeRootAgent, patchRootEntry, projectAgentProblem, readRootAgentsFile, rootAgentSummary, + ABSENT_REVISION, ROOT_LOCK, ROOT_RECEIPTS, changeRootAgent, patchRootEntry, projectAgentProblem, readRootAgentsFile, rootAgentSummary, } from "../src/agent-levels-write.mjs"; import * as oldPath from "../../business/src/agent-levels-write.mjs"; import { organizationWriter } from "../src/organization.mjs"; @@ -138,14 +138,35 @@ test("root writer: a symbolic link, a group-writable file and a foreign uid refu linkSync(file(dir), join(dir, "alias.json")); await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /one link/.test(e.message))); unlinkSync(join(dir, "alias.json")); - // Not this process's uid: the config directory's owner check refuses first, the file's after it. - await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, { ...as(), uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /uid/.test(e.message))); - await assert.rejects(readRootAgentsFile(dir, { uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /uid/.test(e.message))); + // Not this process's uid: the directory checks refuse first (an ancestor this uid owns is foreign). + await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, { ...as(), uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /config directory/.test(e.message) && !/root agent file/.test(e.message))); + await assert.rejects(readRootAgentsFile(dir, { uid: process.geteuid() + 1 }), refuses("agents-unsafe", e => /config directory/.test(e.message) && !/root agent file/.test(e.message))); assert.equal(bytes(dir), original); + // A file another uid owns, in a directory that is this uid's: the file's own owner check refuses. + // Changing a file's owner needs root, so the descriptor stat reports a foreign uid through the seam. + const foreign = async fd => { const st = await fd.stat(); return Object.assign(Object.create(Object.getPrototypeOf(st)), st, { uid: st.uid + 1 }); }; + const receiptsBefore = existsSync(join(dir, ROOT_RECEIPTS)) ? readFileSync(join(dir, ROOT_RECEIPTS), "utf8") : null; + await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, { ...as(), statFile: foreign }), refuses("agents-unsafe", e => /root agent file must belong to uid/.test(e.message))); + await assert.rejects(readRootAgentsFile(dir, { statFile: foreign }), refuses("agents-unsafe", e => /root agent file must belong to uid/.test(e.message))); + assert.equal(bytes(dir), original); + assert.equal(lstatSync(file(dir)).mode & 0o777, 0o600); + assert.equal(existsSync(join(dir, ROOT_RECEIPTS)) ? readFileSync(join(dir, ROOT_RECEIPTS), "utf8") : null, receiptsBefore); + assert.equal(existsSync(join(dir, ROOT_LOCK)), false, "the lock is released"); // A group-writable config directory refuses before any lock or read. chmodSync(dir, 0o770); await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /config directory/.test(e.message))); chmodSync(dir, 0o700); + // An ancestor another user can write without the sticky bit refuses: that user could rename the + // config directory between the checks and the write. With the sticky bit, as /tmp has, it can't. + const parent = dirname(dir); + const mode = lstatSync(parent).mode & 0o7777; + chmodSync(parent, 0o777); + try { + await assert.rejects(changeRootAgent(dir, { revision, name: "pm", entry: { definition: "pm" } }, as()), refuses("agents-unsafe", e => /ancestor/.test(e.message) && !e.message.includes(dir))); + await assert.rejects(readRootAgentsFile(dir), refuses("agents-unsafe", e => /ancestor/.test(e.message))); + chmodSync(parent, 0o1777); + assert.equal((await readRootAgentsFile(dir)).revision, revision); + } finally { chmodSync(parent, mode); } assert.equal(bytes(dir), original); assert.equal(receipts(dir).length, 1); assert.equal(existsSync(join(dir, "agents.lock")), false); @@ -206,11 +227,9 @@ test("root writer: a held lock refuses agents-locked", async () => { }); // The project-agent verb: the organization file's projects.

.agents, one entry per call. -function org(t, mutate = () => {}) { +function org(mutate = () => {}) { const root = tmp(); const doc = businessDoc(root); - doc.projects.notes = { kind: "library", root: join(root, "notes"), mapping: undefined }; - delete doc.projects.notes; mutate(doc); const dir = join(root, "config"); const orgFile = writeJson(join(dir, "businesses/acme.json"), doc); @@ -266,13 +285,18 @@ test("project verb: a narrow that widens refuses, and refusals never quote a val test("project verb: the chief and the assistant refuse", () => { const { writer, orgFile } = org(doc => { doc.roles.assistant = { definition: "assistant" }; }); - const { revision } = writer.read("acme"); + const { document, revision } = writer.read("acme"); + assert.equal(document.roles.assistant.definition, "assistant", "the fixture has an organization assistant"); + assert.equal(document.roles.chief.definition, "chief-of-staff", "the fixture has a chief"); const before = readFileSync(orgFile, "utf8"); - for (const [name, entry] of [ - ["chief", { exclude: true }], ["chief", { vars: { "limits.network": "none" } }], ["chief", { definition: "reviewer" }], - ["assistant", { exclude: true }], ["helper", { definition: "chief-of-staff" }], ["helper", { definition: "assistant" }], + const protectedAgent = /a project can't change the organization's (chief-of-staff|assistant)/; + const notProjectAgent = /can't be a project agent/; + for (const [name, entry, reason] of [ + ["chief", { exclude: true }, protectedAgent], ["chief", { vars: { "limits.network": "none" } }, protectedAgent], ["chief", { definition: "reviewer" }, protectedAgent], + ["assistant", { exclude: true }, protectedAgent], ["assistant", { vars: { "limits.network": "none" } }, protectedAgent], ["assistant", { definition: "reviewer" }, protectedAgent], + ["helper", { definition: "chief-of-staff" }, notProjectAgent], ["helper", { definition: "assistant" }, notProjectAgent], ]) { - assert.throws(() => writer.setProjectAgent("acme", { revision, project: "stack", name, entry }, "jason"), e => e.code === "project-agents-invalid", `${name} ${JSON.stringify(entry)}`); + assert.throws(() => writer.setProjectAgent("acme", { revision, project: "stack", name, entry }, "jason"), e => e.code === "project-agents-invalid" && reason.test(e.message), `${name} ${JSON.stringify(entry)}`); } assert.equal(readFileSync(orgFile, "utf8"), before); }); diff --git a/packages/webui/src/agent-levels-write.mjs b/packages/webui/src/agent-levels-write.mjs index ebfbeab57..6bac109e8 100644 --- a/packages/webui/src/agent-levels-write.mjs +++ b/packages/webui/src/agent-levels-write.mjs @@ -21,6 +21,7 @@ // A response or trail entry names agents, keys and revisions, never a var value or a host path. import { organizationWriter } from '../../organization/src/organization.mjs'; import { changeRootAgent, patchRootEntry, projectAgentSummary, readRootAgentsFile, rootAgentSummary } from '../../organization/src/agent-levels-write.mjs'; +import { ID_PATTERN } from '../../organization/src/vocabulary.mjs'; import { actor } from './action-trail.mjs'; export const ROOT_ROUTE = '/api/agents/root'; @@ -28,7 +29,10 @@ export const PROJECT_ROUTE = /^\/api\/orgs\/([^/]+)\/agent-levels\/projects\/([^ // routeTable takes GET and POST only; any other method never reaches these hooks (serve.mjs answers it). const METHODS = ['GET', 'POST']; const REVISION = /^[a-f0-9]{64}$/; -const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/; +// Agent and project names are the writers' ids (requireId): checked here so a bad one is a 400 +// naming the field, not a writer error the Console can't classify. +const NAME = ID_PATTERN; +const NAME_RULE = 'lowercase letters, digits, dot, dash or underscore, at most 64'; const LIMIT = 4096; const ROOT_PATCH = ['definition', 'vars', 'excludeOrgs']; const PROJECT_ENTRY = ['definition', 'vars', 'exclude']; @@ -86,7 +90,8 @@ async function body(req) { try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return null; } const keys = ['revision', 'name', 'entry']; if (!plain(value) || Object.keys(value).length !== keys.length || !keys.every(k => Object.hasOwn(value, k))) return null; - if (typeof value.revision !== 'string' || !REVISION.test(value.revision) || typeof value.name !== 'string' || !NAME.test(value.name)) return null; + if (typeof value.revision !== 'string' || !REVISION.test(value.revision) || typeof value.name !== 'string') return null; + if (!NAME.test(value.name)) return 'bad-name'; return value; } const only = (entry, keys) => plain(entry) && Object.keys(entry).length > 0 && Object.keys(entry).every(k => keys.includes(k)); @@ -107,6 +112,7 @@ export function agentLevelsWriteRoutes({ configDir, rolesDir, trail = null, log if (!send) { json(res, 403, { error: 'read-only', message: 'this Console was started without writes' }); return null; } const value = await body(req); if (value === 'too-large') { json(res, 413, { error: 'invalid-request', message: `a change is at most ${LIMIT} bytes` }); return null; } + if (value === 'bad-name') { json(res, 400, { error: 'invalid-request', message: `name must be an id: ${NAME_RULE}` }); return null; } if (!value) { json(res, 400, { error: 'invalid-request', message: 'this takes revision, name and entry, nothing else' }); return null; } return value; } diff --git a/packages/webui/src/public/agents.js b/packages/webui/src/public/agents.js index e05a7bd9e..32ebdc554 100644 --- a/packages/webui/src/public/agents.js +++ b/packages/webui/src/public/agents.js @@ -247,6 +247,11 @@ const UNKNOWN = 'Outcome unknown. Nothing was retried. The grid below was read again.'; let root = null, levels = null, project = null, selected = { org: '', project: '' }; let receipts = { root: '', project: '' }, busy = false, confirming = null; + // What each form holds, kept here so a polling render, a picker change or the other form's save + // repaints it as typed. A draft keeps the revision it began at, so a save sends that and a file + // changed meanwhile refuses rather than being overwritten unseen. The project draft belongs to its + // organization and project. Only the submitted form's own success clears it. + const drafts = { root: null, project: null }; const read = url => fetch(url, { cache: 'no-store', redirect: 'manual' }).then(async r => { if (r.type === 'opaqueredirect') return { signedOut: true }; @@ -308,14 +313,22 @@ return `

${esc(text)}

`; }; + const projectDraft = () => drafts.project && drafts.project.org === selected.org && drafts.project.project === selected.project ? drafts.project : null; + const shownDraft = which => which === 'root' ? drafts.root : projectDraft(); + const field = (which, key) => esc(shownDraft(which)?.values?.[key] ?? ''); + const filled = d => !!d && Object.entries(d.values).some(([k, v]) => k !== 'form' && String(v).trim()); + function markup() { if (!levels || levels.refused || levels.signedOut) return ''; const off = !writable() || busy ? ' disabled' : ''; + const at = (which, current) => esc(shownDraft(which)?.revision ?? current); + const key = (which, name) => ` data-focus-key="level-${which}-${name}"`; + const chosen = v => (projectDraft()?.values?.form ?? 'define') === v ? ' selected' : ''; const readOnly = writable() ? '' : '

This Console was started without writes, so these levels are read only here. mosaic agents root and mosaic project agents change them from a terminal.

'; - const rootForm = writable() && root && !root.refused ? `

Add or change a root agent

` : ''; + const rootForm = writable() && root && !root.refused ? `

Add or change a root agent

` : ''; const orgs = orgsOf(), projects = orgs.find(o => o.id === selected.org)?.projects ?? []; const pick = `
`; - const projectForm = writable() && project && !project.refused && !project.library ? `

Add or change a project entry

` : ''; + const projectForm = writable() && project && !project.refused && !project.library ? `

Add or change a project entry

` : ''; return `

Root agents

Root agents are in every organization unless a row excludes it. They are read from the instance's root agent file and are not launched yet.

${readOnly}${rootGrid()}${receiptLine('root')}${rootForm}

Project agents

A project can define its own agents, narrow an inherited agent's limits, or exclude one. Project agents are not launched yet.

${orgs.length ? pick : '

No organization to show.

'}${orgs.length ? projectGrid() : ''}${receiptLine('project')}${projectForm}
`; } const repaint = () => { const box = $('agent-levels-edit'); if (box) box.outerHTML = markup(); }; @@ -334,9 +347,8 @@ const refusedText = body => body?.error === 'revision-conflict' ? 'Refused: the file changed since this page read it. The grid below was read again; check it and save again.' : typeof body?.message === 'string' ? `Refused (${body.error}): ${body.message}` : UNKNOWN; - async function write(which, url, payload, done, focus) { - // The busy repaint below replaces the form, so what was typed is taken first. - const typed = draft(which); + // fromForm: the submitted form's draft is cleared on success. A row's Remove leaves it alone. + async function write(which, url, payload, done, focus, fromForm = false) { busy = true; receipts[which] = ''; repaint(); let answer; try { answer = await post(url, payload); } catch { answer = null; } @@ -344,16 +356,25 @@ if (answer?.signedOut) { receipts[which] = 'Sign in again, then retry.'; repaint(); return false; } const ok = answer?.ok && answer.body?.outcome === 'done'; receipts[which] = ok ? done(answer.body.receipt) : answer ? refusedText(answer.body) : UNKNOWN; - const kept = ok ? null : typed; + const conflict = answer?.body?.error === 'revision-conflict'; await load(); + if (ok && fromForm) drafts[which] = null; + // After a conflict the grid is read again and the receipt asks for a check: the next save is a + // deliberate one against what is shown now. + if (conflict && fromForm && shownDraft(which)) shownDraft(which).revision = which === 'root' ? root?.revision : project?.revision; repaint(); - if (kept) restore(which, kept); (focus && $(focus))?.focus?.(); return ok; } - // A refused form keeps what was typed. - const draft = which => { const form = $(`agent-levels-${which}-form`); return form ? Object.fromEntries(new FormData(form)) : null; }; - const restore = (which, values) => { const form = $(`agent-levels-${which}-form`); if (form) for (const [k, v] of Object.entries(values)) if (form.elements[k]) form.elements[k].value = v; }; + // Take what a form holds into its draft, keeping the revision the draft began at. + function capture(form) { + const which = form.id === 'agent-levels-root-form' ? 'root' : 'project'; + const values = Object.fromEntries(new FormData(form)); + const old = shownDraft(which); + drafts[which] = { ...(which === 'project' ? { org: selected.org, project: selected.project } : {}), revision: old?.revision ?? form.dataset.revision, values }; + form.querySelector('.settings-actions')?.classList.toggle('has-draft', filled(drafts[which])); + return which; + } async function saveRoot(form) { const f = Object.fromEntries(new FormData(form)); @@ -367,9 +388,9 @@ if (String(f.excludeOrgs ?? '').trim()) entry.excludeOrgs = String(f.excludeOrgs).trim() === 'none' ? [] : list(f.excludeOrgs); if (!name) throw new Error('A root agent needs a name.'); if (!Object.keys(entry).length) throw new Error('Nothing to change: give a definition, a variable or the organizations it is not in.'); - } catch (error) { receipts.root = error.message; const kept = draft('root'); repaint(); restore('root', kept); return; } + } catch (error) { receipts.root = error.message; capture(form); repaint(); return; } await write('root', '/api/agents/root', { revision: form.dataset.revision, name, entry }, - r => `Saved ${r.agent} at ${clock()}: ${r.changed.join(', ')}.`, 'agent-levels-root-title'); + r => `Saved ${r.agent} at ${clock()}: ${r.changed.join(', ')}.`, 'agent-levels-root-title', true); } async function saveProject(form) { @@ -382,9 +403,9 @@ if (f.form === 'exclude') { if (Object.keys(vars).length || String(f.definition ?? '').trim()) throw new Error('An exclude takes no definition and no variables.'); entry = { exclude: true }; } else if (f.form === 'narrow') { if (String(f.definition ?? '').trim()) throw new Error('A narrow takes no definition.'); if (!Object.keys(vars).length) throw new Error('A narrow needs at least one variable.'); entry = { vars }; } else { if (!String(f.definition ?? '').trim()) throw new Error('A defined agent needs a definition.'); entry = { definition: String(f.definition).trim(), ...(Object.keys(vars).length ? { vars } : {}) }; } - } catch (error) { receipts.project = error.message; const kept = draft('project'); repaint(); restore('project', kept); return; } + } catch (error) { receipts.project = error.message; capture(form); repaint(); return; } await write('project', `/api/orgs/${enc(selected.org)}/agent-levels/projects/${enc(selected.project)}`, { revision: form.dataset.revision, name, entry }, - r => `Saved ${r.agent} in ${r.project} at ${clock()}: ${r.form}.`, 'agent-levels-project-title'); + r => `Saved ${r.agent} in ${r.project} at ${clock()}: ${r.form}.`, 'agent-levels-project-title', true); } async function remove(which, name) { @@ -398,8 +419,13 @@ if (form.id !== 'agent-levels-root-form' && form.id !== 'agent-levels-project-form') return; e.preventDefault(); if (busy) return; + capture(form); (form.id === 'agent-levels-root-form' ? saveRoot : saveProject)(form); }); + for (const kind of ['input', 'change']) document.addEventListener(kind, e => { + const form = e.target?.closest?.('.level-form'); + if (form && e.target !== form) capture(form); + }); document.addEventListener('click', e => { const button = e.target.closest?.('[data-level-remove]'); if (!button || button.disabled || busy || !writable()) return; @@ -414,5 +440,6 @@ await load(); repaint(); $(id)?.focus(); }); - window.MosaicAgentLevels = Object.freeze({ section, hasDraft: () => [...document.querySelectorAll('#agent-levels-edit form')].some(f => [...f.elements].some(el => (el.tagName === 'TEXTAREA' || el.type === 'text' || el.tagName === 'INPUT') && el.type !== 'hidden' && el.value?.trim())) }); + // hasDraft feeds the Settings nav's unsaved-changes dot (bus.js settingsShell and its input listener). + window.MosaicAgentLevels = Object.freeze({ section, hasDraft: () => filled(drafts.root) || filled(drafts.project) }); })(); diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 84303d839..55e12a702 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1047,6 +1047,8 @@ const unknownInstance='Outcome unknown. Read the role instances again before trying. Draft kept.'; // The answer replaces the view the next render draws, so it must have the read's whole shape. const instanceAnswer=r=>/^[a-f0-9]{64}$/.test(r?.revision??'')&&typeof r.restart==='boolean'&&[r.instances,r.definitions].every(o=>o&&typeof o==='object'&&!Array.isArray(o)); + // #1873 A2: the level forms keep their own drafts (agents.js); here they only mark the nav. + for(const kind of ['input','change'])document.addEventListener(kind,e=>{if(e.target?.closest?.('.level-form'))markSettingsDraft('agents',!!window.MosaicAgentLevels?.hasDraft());}); for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=e.target?.closest?.('.instance-form');if(form){instanceDrafts[form.dataset.op]=instanceFields(form);markSettingsDraft('agents',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-instance-discard]');if(discard)discard.hidden=false;}}); document.addEventListener('click',e=>{if(e.target.id!=='instances-reload' && e.target.dataset?.instanceDiscard===undefined)return;instanceDrafts={add:null,change:null};instanceView=null;instanceReceipt='';instanceReceipts=Object.create(null);instanceReceiptOp=null;last.delete('instances');render(true);}); document.addEventListener('submit',async e=>{ @@ -1200,7 +1202,7 @@ function settingsShell(page, body, helper='') { const pages=isTester ? [['appearance','Appearance'],['business','Business'],['routing','Routing'],['agents','Agents'],['names','Seat names']] : settingsPages; const label=pages.find(([id])=>id===page)?.[1] || 'Appearance'; - const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change)); + const isDirty=id=>(id==='routing'&&routesDraft)||(id==='limits'&&settingsInputs)||(id==='assistant'&&(Object.keys(assistantDrafts).length||Object.keys(nameDrafts).length))||(id==='agents'&&(instanceDrafts.add||instanceDrafts.change||window.MosaicAgentLevels?.hasDraft())); const dot='unsaved changes'; const links=pages.map(([id,name],i)=>`${i===0?'
Your browser
':i===1?'
This instance
':''}${name}${isDirty(id)?dot:''}`).join('') + (!isTester ? '
Members and invites not built
' : ''); return `${head('Settings','Your browser and this instance.')}

${label}

${helper}

${readonlyPage(page)?'

Read only. Saving requires signed-in send mode.

':''}${body}
`; diff --git a/packages/webui/src/public/shell.css b/packages/webui/src/public/shell.css index 0a755e3f2..773f6de0a 100644 --- a/packages/webui/src/public/shell.css +++ b/packages/webui/src/public/shell.css @@ -294,7 +294,7 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} #agents-table tbody th,#routes-table tbody th{text-transform:none;font-size:14px;font-weight:600;color:var(--strong)} @media(max-width:759px){.settings-content .routing-panel{border:0;background:transparent;padding:0}.routing-panel .table-wrap{border:0;overflow:visible}.routing-panel #routes-table tr{display:grid;grid-template-columns:1fr 1fr;gap:0 10px;background:var(--surface)}.routing-panel #routes-table th,.routing-panel #routes-table td:first-of-type,.routing-panel #routes-table .fallback-cell:first-of-type{grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4){grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4)::before{content:'Fallback: None'}.routing-panel #routes-table .fallback-open td:nth-of-type(4)::before{content:'Fallback harness'}} .settings-content label:has(>input[type=checkbox]){display:inline-flex;align-items:center;gap:8px;min-height:44px;padding:0 8px} -.settings-content .instance-form textarea,.settings-content .assistant-form textarea{display:block;width:100%} +.settings-content :is(.instance-form,.level-form) textarea,.settings-content .assistant-form textarea{display:block;width:100%} .route-definition{display:none}.settings-spinner{display:inline-block;width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:middle;animation:settings-spin .8s linear infinite}@keyframes settings-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.settings-spinner{animation:none}} @media(max-width:759px){#routes-table .route-definition{display:inline;float:right;color:var(--muted);font-size:12px;font-weight:400}} /* Settings forms: align controls across rows without changing their write paths. */ @@ -302,15 +302,15 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed} .settings-limits-table,.settings-model-table{width:100%;table-layout:fixed;border-collapse:collapse} .settings-limits-table col:first-child{width:45%}.settings-limits-table col:nth-child(2){width:144px}.settings-model-table col:first-child{width:25%}.settings-model-table col:nth-child(2),.settings-model-table col:nth-child(3){width:37.5%} .settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:8px;text-align:left;vertical-align:middle}.settings-limits-table tbody th,.settings-model-table tbody th{text-transform:none;font-size:14px;font-weight:500;color:var(--text)}.settings-limits-table .limit-group th{padding-top:14px;color:var(--muted);font-size:12px;font-weight:600}.settings-model-table input{width:100%} -.settings-content .instance-form .filters{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:var(--gap);align-items:end}.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])){display:flex;flex-direction:column;gap:6px}.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])) :is(input,select){width:100%}.settings-content .instance-form .filters>label:has(input[type=checkbox]){display:flex;gap:8px;align-items:center;min-height:44px;white-space:nowrap}.settings-content .instance-form details{margin:var(--gap) 0}.hiring-grid>div{justify-content:flex-start;gap:var(--gap)} -@media(max-width:759px){.settings-content .instance-form .filters{grid-template-columns:1fr}.settings-limits-table,.settings-limits-table tbody,.settings-limits-table tr,.settings-limits-table th,.settings-limits-table td,.settings-model-table,.settings-model-table tbody,.settings-model-table tr,.settings-model-table th,.settings-model-table td{display:block;width:100%}.settings-limits-table colgroup,.settings-model-table colgroup,.settings-limits-table thead,.settings-model-table thead{display:none}.settings-limits-table tbody tr:not(.limit-group){display:grid;grid-template-columns:120px 1fr;gap:0 12px;border-bottom:1px solid var(--line)}.settings-limits-table tbody tr:not(.limit-group)>th{grid-column:1/-1}.settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:6px 0}.settings-model-table tbody tr{padding:8px 0;border-bottom:1px solid var(--line)}.settings-model-table td:before{display:block;color:var(--muted);font-size:12px}.settings-model-table td:nth-of-type(1):before{content:'Provider'}.settings-model-table td:nth-of-type(2):before{content:'Model'}#routes-table .route-row:not(.fallback-open) td.fallback-cell:nth-of-type(n+5){display:none}} +.settings-content :is(.instance-form,.level-form) .filters{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr) auto;gap:var(--gap);align-items:end}.settings-content :is(.instance-form,.level-form) .filters>label:not(:has(input[type=checkbox])){display:flex;flex-direction:column;gap:6px}.settings-content :is(.instance-form,.level-form) .filters>label:not(:has(input[type=checkbox])) :is(input,select){width:100%}.settings-content :is(.instance-form,.level-form) .filters>label:has(input[type=checkbox]){display:flex;gap:8px;align-items:center;min-height:44px;white-space:nowrap}.settings-content :is(.instance-form,.level-form) details{margin:var(--gap) 0}.hiring-grid>div{justify-content:flex-start;gap:var(--gap)} +@media(max-width:759px){.settings-content :is(.instance-form,.level-form) .filters{grid-template-columns:1fr}.settings-limits-table,.settings-limits-table tbody,.settings-limits-table tr,.settings-limits-table th,.settings-limits-table td,.settings-model-table,.settings-model-table tbody,.settings-model-table tr,.settings-model-table th,.settings-model-table td{display:block;width:100%}.settings-limits-table colgroup,.settings-model-table colgroup,.settings-limits-table thead,.settings-model-table thead{display:none}.settings-limits-table tbody tr:not(.limit-group){display:grid;grid-template-columns:120px 1fr;gap:0 12px;border-bottom:1px solid var(--line)}.settings-limits-table tbody tr:not(.limit-group)>th{grid-column:1/-1}.settings-limits-table :is(th,td),.settings-model-table :is(th,td){padding:6px 0}.settings-model-table tbody tr{padding:8px 0;border-bottom:1px solid var(--line)}.settings-model-table td:before{display:block;color:var(--muted);font-size:12px}.settings-model-table td:nth-of-type(1):before{content:'Provider'}.settings-model-table td:nth-of-type(2):before{content:'Model'}#routes-table .route-row:not(.fallback-open) td.fallback-cell:nth-of-type(n+5){display:none}} /* Agent menus must extend beyond the table without being clipped by its scroll region. */ .settings-agents .table-wrap{overflow:visible} /* Review fixes: preserve readable actions, labels and targets at every width. */ -.settings-content .instance-form .filters>label:not(:has(input[type=checkbox])){align-items:flex-start} -.settings-content .instance-form .filters>label:has(input[type=checkbox]){grid-column:1/-1;justify-self:start} +.settings-content :is(.instance-form,.level-form) .filters>label:not(:has(input[type=checkbox])){align-items:flex-start} +.settings-content :is(.instance-form,.level-form) .filters>label:has(input[type=checkbox]){grid-column:1/-1;justify-self:start} .settings-content .settings-actions .banner:not(:empty){order:-1;flex:1 0 100%;margin:0} .agent-mobile-label{display:none} #bus-view .page-head:has(+ .settings-layout) p{font-size:16px} diff --git a/packages/webui/tests/agent-levels-edit-browser.test.mjs b/packages/webui/tests/agent-levels-edit-browser.test.mjs index b9f007a7d..31c661bdd 100644 --- a/packages/webui/tests/agent-levels-edit-browser.test.mjs +++ b/packages/webui/tests/agent-levels-edit-browser.test.mjs @@ -2,7 +2,7 @@ // browser on the real routes and writers (a temporary config directory with one organization). import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { businessDoc, rolesCopy, writeJson } from '../../organization/tests/helpers.mjs'; @@ -16,7 +16,9 @@ import { close } from './fixture.mjs'; const SECRET = 'sk-test-NOT-A-SECRET-1234'; const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`); -async function open(t, { send = true } = {}) { +// orgSend gives the selected organization a send transport, so the role-instance Settings forms +// are writable too and their handlers are live beside the level forms. +async function open(t, { send = true, orgSend = false } = {}) { const root = mkdtempSync(join(tmpdir(), 'ale-')); t.after(() => rmSync(root, { recursive: true, force: true })); const rolesDir = rolesCopy(root); @@ -28,7 +30,7 @@ async function open(t, { send = true } = {}) { list: async () => [{ id: 'demo', label: 'Demo', busHealthy: true }], members: async () => [{ id: 'demo', doc: doc() }], resolve: async id => id !== 'demo' ? null : { - busHealthy: true, + busHealthy: true, ...(orgSend ? { send: async () => ({}) } : {}), reads: { business: async () => ({ business: { id: 'demo', human: 'jason', arbiters: ['chief'], projects: ['stack'], vars: {}, instances: [{ instance: 'chief', vars: {} }] } }), settings: async () => ({ business: 'demo', release: 'fixture', notifier: {}, launch: { limits: {} } }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) }, bus: { instances: async () => instances, messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [] }, @@ -45,6 +47,9 @@ async function open(t, { send = true } = {}) { return { b, wait: waitFor(b), file, root }; } const fill = (b, form, values) => b.evaluate(`(() => { const f = document.getElementById(${JSON.stringify(form)}); for (const [k, v] of Object.entries(${JSON.stringify(values)})) { f.elements[k].value = v; } f.requestSubmit(); })()`); +// Typing: each value set, then input and change fired, as a person's edit fires them. +const type = (b, form, values) => b.evaluate(`(() => { const f = document.getElementById(${JSON.stringify(form)}); for (const [k, v] of Object.entries(${JSON.stringify(values)})) { const el = f.elements[k]; el.value = v; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); } })()`); +const values = (b, form) => b.evaluate(`Object.fromEntries(new FormData(document.getElementById(${JSON.stringify(form)})))`); const receipt = which => `(document.getElementById("agent-levels-${which}-receipt")?.textContent || "")`; test('the root form adds a root agent and the grid repaints from a fresh read; a refusal names the key, keeps the draft and never shows the value', async t => { @@ -111,3 +116,47 @@ test('without --send both levels read but offer no form', async t => { assert.match(await b.evaluate('document.getElementById("agent-levels-edit").innerText'), /started without writes/); assert.equal(await b.evaluate('!!document.getElementById("agent-levels-root-form") || !!document.getElementById("agent-levels-project-form")'), false); }); + +test('both drafts survive a refresh render and the other form\'s save; a draft keeps its revision; the role-instance handlers leave the level forms alone', async t => { + const { b, wait, root } = await open(t, { orgSend: true }); + await wait('document.getElementById("agent-levels-root-form") && document.getElementById("agent-levels-project-form")'); + assert.equal(await b.evaluate('!!document.getElementById("instance-add-form")'), true, 'the role-instance forms are writable in this fixture'); + assert.equal(await b.evaluate('document.querySelectorAll("#agent-levels-edit .instance-form").length'), 0); + assert.equal(await b.evaluate('getComputedStyle(document.querySelector("#agent-levels-root-form .filters")).display'), 'grid', 'the level forms keep the Settings form layout'); + await type(b, 'agent-levels-root-form', { name: 'drafted', vars: 'limits.network=none' }); + await type(b, 'agent-levels-project-form', { name: 'helper', form: 'narrow', vars: 'limits.tools=read' }); + assert.equal(await b.evaluate('!!document.querySelector("#settings-nav a[href$=\'settings/agents\'] .settings-dot")'), true, 'the nav marks unsaved changes'); + // A full Settings render, as the ten-second poll does: the edit box is a new node, the drafts are in it. + await b.evaluate('document.getElementById("agent-levels-edit").dataset.old = "1"; document.getElementById("refresh").click()'); + await wait('document.getElementById("agent-levels-edit") && !document.getElementById("agent-levels-edit").dataset.old'); + assert.deepEqual(await values(b, 'agent-levels-root-form'), { name: 'drafted', definition: '', model: '', vars: 'limits.network=none', unset: '', excludeOrgs: '' }); + assert.deepEqual(await values(b, 'agent-levels-project-form'), { name: 'helper', form: 'narrow', definition: '', vars: 'limits.tools=read' }); + // The root form saves; the project draft stays as typed and the root draft clears. + await type(b, 'agent-levels-root-form', { name: 'researcher', definition: 'research', vars: '' }); + await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()'); + await wait(`${receipt('root')}.startsWith("Saved researcher at ")`); + assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.name.value'), ''); + assert.deepEqual(await values(b, 'agent-levels-project-form'), { name: 'helper', form: 'narrow', definition: '', vars: 'limits.tools=read' }); + // A locally refused submit keeps its draft; the role-instance handler takes no part. + await type(b, 'agent-levels-root-form', { name: 'second', vars: 'malformed' }); + await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()'); + await wait(`${receipt('root')} === "Variables line 1 needs KEY=VALUE."`); + await new Promise(r => setTimeout(r, 300)); + assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.name.value'), 'second'); + assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.vars.value'), 'malformed'); + assert.equal(await b.evaluate('!!document.querySelector("#instance-add-form .settings-actions.has-draft")'), false, 'the instance form took no draft'); + // The file changes under a draft: the draft's save sends the revision it began at and is refused, + // then a second, deliberate save goes through against the file as now read. + await type(b, 'agent-levels-root-form', { name: 'later', definition: 'research', vars: '' }); + const began = await b.evaluate('document.getElementById("agent-levels-root-form").dataset.revision'); + writeFileSync(join(root, 'agents.json'), JSON.stringify({ agentsVersion: 1, agents: {} }) + '\n', { mode: 0o600 }); + await b.evaluate('document.getElementById("agent-levels-edit").dataset.old = "1"; document.getElementById("refresh").click()'); + await wait('document.getElementById("agent-levels-edit") && !document.getElementById("agent-levels-edit").dataset.old'); + assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").dataset.revision'), began, 'the draft keeps the revision it began at'); + await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()'); + await wait(`${receipt('root')}.startsWith("Refused: the file changed")`); + assert.equal(await b.evaluate('document.getElementById("agent-levels-root-form").elements.name.value'), 'later'); + await b.evaluate('document.getElementById("agent-levels-root-form").requestSubmit()'); + await wait(`${receipt('root')}.startsWith("Saved later at ")`); + assert.deepEqual(Object.keys(JSON.parse(readFileSync(join(root, 'agents.json'), 'utf8')).agents), ['later']); +}); diff --git a/packages/webui/tests/agent-levels-write-http.test.mjs b/packages/webui/tests/agent-levels-write-http.test.mjs index c81868fb9..fb5bfb21c 100644 --- a/packages/webui/tests/agent-levels-write-http.test.mjs +++ b/packages/webui/tests/agent-levels-write-http.test.mjs @@ -168,6 +168,14 @@ test('project entries: define, narrow, exclude and remove repaint the read; a wi const [missing, missingBody] = await call(f, '/api/orgs/demo/agent-levels/projects/nope', 'POST', { revision: listed.revision, name: 'scout', entry: { exclude: true } }); assert.equal(missing, 404); assert.equal(missingBody.error, 'project-not-found'); assert.equal((await call(f, '/api/orgs/other/agent-levels/projects/stack'))[0], 404); + // A name the writers can't take is a 400 that names the field, never the value, on both routes. + for (const name of ['BadName', 'a'.repeat(65)]) { + for (const [route, entry] of [[PROJECT, { definition: 'research' }], [ROOT, { definition: 'research' }]]) { + const [s, body, text] = await call(f, route, 'POST', { revision: listed.revision, name, entry }); + assert.equal(s, 400, `${route} ${name}: ${text}`); assert.equal(body.error, 'invalid-request'); assert.match(body.message, /^name must be an id/); + assert.ok(!text.includes(name), text); + } + } assert.equal(readFileSync(f.file, 'utf8'), before); for (const name of ['checker', 'coder', 'scout']) assert.equal((await set(name, null))[1].receipt.form, 'remove'); assert.deepEqual((await call(f, PROJECT))[1].agents, []);