diff --git a/src/bundled/tasks/store.test.ts b/src/bundled/tasks/store.test.ts index 884a75a0e0..e51d66c264 100644 --- a/src/bundled/tasks/store.test.ts +++ b/src/bundled/tasks/store.test.ts @@ -2,7 +2,7 @@ import { expect, it, vi } from "vitest"; import { PublishRejected } from "../../features/relay/outbox"; import type { RelaySession } from "../../features/relay/session"; import { TASK_TYPE, type Task, type TaskFields, taskOf } from "./model"; -import { NOT_A_TASK_PLACE, readTask, saveTask } from "./store"; +import { NOT_A_TASK_PLACE, readTask, saveTask, TaskRefused } from "./store"; const viewer = "a".repeat(64); const id = "11111111-1111-4111-8111-111111111111"; @@ -33,6 +33,7 @@ const head = (revision: string, content: object = {}, at = home) => ({ }); const relayKey = "e".repeat(64); +const riley = "c".repeat(64); const dm = "44444444-4444-4444-8444-444444444444"; const huddle = "55555555-5555-4555-8555-555555555555"; const place = (d: string, more: string[][] = [["t", "stream"]]) => ({ @@ -77,6 +78,7 @@ function session(publish: () => Promise, heads: object[] = []) { relayAuthor: relayKey, snapshotRead: read, configArtifactWriter: { sign, publish: vi.fn(publish) }, + profiles: { snapshot: () => new Map([[riley, { name: "Riley" }]]) }, } as unknown as RelaySession, }; } @@ -169,6 +171,130 @@ it("says why the relay refused, for an edit and for a move", async () => { ).rejects.toThrow("between places you can post in"); }); +const refusedWith = (reason: string) => + session(async () => { + throw new PublishRejected("rejected", reason); + }).session; + +it("says each relay reason in plain words, naming people it knows", async () => { + const base = taskOf(head("d".repeat(64))) as Task; + const save = (reason: string) => + saveTask(refusedWith(reason), refusedWith(reason), fields, { + op: "update", + base, + }); + await expect( + save( + `invalid: assignee-unreadable:${riley} — an assignee can't see this artifact`, + ), + ).rejects.toThrow( + "Riley can’t see #2222, so they can’t be assigned. Nothing was saved.", + ); + await expect( + save(`invalid: assignee-unreadable:${riley},${"9".repeat(64)} — x`), + ).rejects.toThrow( + "One of the people assigned can’t see #2222. Nothing was saved.", + ); + // A place it can't read is described, not named. + const unread = taskOf(head("d".repeat(64), {}, dm.replace("4444", "6666"))); + await expect( + saveTask( + refusedWith(`invalid: assignee-unreadable:${riley} — x`), + refusedWith(""), + fields, + { op: "update", base: unread as Task }, + ), + ).rejects.toThrow( + "Riley can’t see where this task lives, so they can’t be assigned. Nothing was saved.", + ); + await expect( + save(`invalid: assignee-agent:${riley} — an agent can't be an assignee`), + ).rejects.toThrow( + "Only people can be assigned, and Riley is an agent. Nothing was saved.", + ); + await expect( + save("invalid: too-many-assignees: — a revision names at most 4 assignees"), + ).rejects.toThrow("A task can have up to 4 people assigned."); + await expect( + save("invalid: signer-agent: — an agent can't sign an artifact"), + ).rejects.toThrow("Only a person can save a task, not an agent."); + // A code it doesn't know, or text with no code: a plain line, never the + // relay's words or a key. Those go to the log, and to an agent's tool. + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + for (const reason of [ + `invalid: something-new:${riley} — artifact jargon`, + "invalid: bad artifact tag", + ]) { + const error = await save(reason).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(TaskRefused); + expect((error as TaskRefused).message).toBe( + "This change isn’t allowed. Nothing was saved.", + ); + expect((error as TaskRefused).relay).toBe(reason); + expect(warn).toHaveBeenLastCalledWith( + "The relay refused a task save:", + reason, + ); + } + warn.mockRestore(); +}); + +it("resends once with the creator the relay keeps", async () => { + const forged = head("d".repeat(64)); + forged.tags.push(["creator", "9".repeat(64)]); + const base = taskOf(forged) as Task; + let calls = 0; + const { session: relay, sign } = session(async () => { + calls++; + if (calls === 1) + throw new PublishRejected( + "rejected", + `invalid: creator-changed:${riley} — creator cannot change; resend with the named creator`, + ); + return ""; + }); + const saved = await saveTask(relay, relay, fields, { op: "update", base }); + expect(saved.status).toBe("saved"); + expect(tagsOf(sign, 0)).toContainEqual(["creator", "9".repeat(64)]); + expect(tagsOf(sign, 1)).toContainEqual(["creator", riley]); + expect(saved.status === "saved" && saved.task.creator).toBe(riley); + + // "none": the relay knows no creator, so the resend names none. + calls = 0; + const unknown = session(async () => { + calls++; + if (calls === 1) + throw new PublishRejected( + "rejected", + "invalid: creator-changed:none — creator cannot change", + ); + return ""; + }); + await saveTask(unknown.session, unknown.session, fields, { + op: "update", + base, + }); + expect(tagsOf(unknown.sign, 1).some(([name]) => name === "creator")).toBe( + false, + ); +}); + +it("resends a creator only once", async () => { + const base = taskOf(head("d".repeat(64))) as Task; + let calls = 0; + const relay = session(async () => { + calls++; + throw new PublishRejected( + "rejected", + `invalid: creator-changed:${riley} — creator cannot change`, + ); + }).session; + await expect( + saveTask(relay, relay, fields, { op: "update", base }), + ).rejects.toThrow("This change isn’t allowed. Nothing was saved."); + expect(calls).toBe(2); +}); + it("finds a create that landed unseen instead of making a second task", async () => { const { session: relay, sign } = session(async () => { throw new Error("socket closed"); diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts index 225580ea88..5116daaeaf 100644 --- a/src/bundled/tasks/store.ts +++ b/src/bundled/tasks/store.ts @@ -10,6 +10,8 @@ import type { RelayEvent } from "../../features/relay/events"; import type { RelaySession } from "../../features/relay/session"; import { checkedFields, + isPubkey, + MAX_ASSIGNEES, TASK_TYPE, type Task, type TaskFields, @@ -18,7 +20,7 @@ import { taskOf, taskTags, } from "./model"; -import { canHoldTasks, readPlaces } from "./places"; +import { canHoldTasks, type Place, placeLabel, readPlaces } from "./places"; export type TasksState = Readonly<{ status: "loading" | "live" | "error"; @@ -237,27 +239,38 @@ export async function saveTask( if (!place) throw new Error("You can’t see that place. Nothing was saved."); if (!canHoldTasks(place)) throw new Error(NOT_A_TASK_PLACE); } - const event = await writer.sign( - { - kind: ARTIFACT_KIND, - created_at: Math.floor(Date.now() / 1000), - content: taskContent(checked), - tags: [ - ["ar", "1"], - ["d", id], - ["h", home], - ["type", TASK_TYPE], - ["title", checked.title], - ["op", target.op], - ...(base ? [["prev", base.revision]] : []), - ...taskTags(checked), - ...(creator ? [["creator", creator]] : []), - ...(via ? [["via", via]] : []), - ], - }, - signal, - ); - const delivery = await deliver(writer, event, signal); + const send = async (creator: string | undefined) => { + const event = await writer.sign( + { + kind: ARTIFACT_KIND, + created_at: Math.floor(Date.now() / 1000), + content: taskContent(checked), + tags: [ + ["ar", "1"], + ["d", id], + ["h", home], + ["type", TASK_TYPE], + ["title", checked.title], + ["op", target.op], + ...(base ? [["prev", base.revision]] : []), + ...taskTags(checked), + ...(creator ? [["creator", creator]] : []), + ...(via ? [["via", via]] : []), + ], + }, + signal, + ); + return { event, delivery: await deliver(writer, event, signal) }; + }; + let { event, delivery } = await send(creator); + // The relay keeps the creator a task was made by. A tag saved before it + // checked can disagree; its refusal names the one it keeps, so resend once + // with that, and the task carries the right creator from then on. + const kept = + delivery.status === "refused" + ? keptCreator(delivery.message, creator) + : undefined; + if (kept !== undefined) ({ event, delivery } = await send(kept ?? undefined)); if (delivery.status === "accepted") { const task = taskOf(event); if (!task) throw new Error("Couldn’t read the saved task."); @@ -280,16 +293,97 @@ export async function saveTask( "Someone else changed or removed this task. Nothing was saved.", ); } - throw new Error( - delivery.status === "refused" && delivery.refusal === "permission" - ? target.op === "move" + if (delivery.status === "refused" && delivery.refusal === "permission") + throw new Error( + target.op === "move" ? "You can only move a task between places you can post in." - : "You can only view tasks here." - : delivery.status === "refused" && delivery.refusal === "too-large" - ? "This task is too large to save. Shorten the description." - : // The relay's own reason, such as an assignee who can't see it. - delivery.status === "refused" && delivery.refusal === "invalid" - ? `Couldn’t save the task: ${delivery.message}` - : "Couldn’t save the task. Try again.", - ); + : "You can only view tasks here.", + ); + if (delivery.status === "refused" && delivery.refusal === "too-large") + throw new Error("This task is too large to save. Shorten the description."); + if (delivery.status === "refused" && delivery.refusal === "invalid") { + console.warn("The relay refused a task save:", delivery.message); + const places = await readPlaces(reader, [home], signal).catch( + () => new Map(), + ); + const place = places.get(home); + throw new TaskRefused( + refusedText( + delivery.message, + session, + place ? placeLabel(place, places) : undefined, + ), + delivery.message, + ); + } + throw new Error("Couldn’t save the task. Try again."); +} + +/** A save the relay refused as invalid: `message` in plain words for + * people, `relay` the relay's own text, for an agent to act on. */ +export class TaskRefused extends Error { + constructor( + message: string, + readonly relay: string, + ) { + super(message); + this.name = "TaskRefused"; + } +} + +/** A NIP-AR reason code and the keys it names, from a relay refusal of the + * form `invalid: : — `; undefined for any other text. */ +function reasonOf(message: string) { + const match = /^invalid: ([a-z][a-z-]*):(\S*) — /.exec(message); + if (!match) return undefined; + return { + code: match[1] ?? "", + keys: match[2] ? match[2].split(",") : [], + }; +} + +/** The creator to resend with after `creator-changed`: a pubkey, `null` for + * none, or undefined when this refusal isn't one to resend. */ +function keptCreator(message: string, sent: string | undefined) { + const reason = reasonOf(message); + if (reason?.code !== "creator-changed" || reason.keys.length !== 1) + return undefined; + const key = reason.keys[0]; + const kept = key === "none" ? null : key && isPubkey(key) ? key : undefined; + return kept === undefined || (kept ?? undefined) === sent ? undefined : kept; +} + +/** What to tell someone when the relay refuses a save as invalid: its + * reason in plain words, naming people the app knows and the task's place, + * `where`, when known. Never the relay's own text or a key. */ +function refusedText( + message: string, + session: RelaySession, + where: string | undefined, +) { + const reason = reasonOf(message); + const known = session.profiles.snapshot(); + const names = reason?.keys.map((key) => known.get(key)?.name); + const named = + names?.length && names.every((name) => !!name) + ? new Intl.ListFormat("en", { type: "conjunction" }).format( + names as string[], + ) + : undefined; + switch (reason?.code) { + case "assignee-unreadable": + return named + ? `${named} can’t see ${where ?? "where this task lives"}, so they can’t be assigned. Nothing was saved.` + : `One of the people assigned can’t see ${where ?? "where this task lives"}. Nothing was saved.`; + case "assignee-agent": + return named + ? `Only people can be assigned, and ${named} ${names?.length === 1 ? "is an agent" : "are agents"}. Nothing was saved.` + : "Only people can be assigned, not agents. Nothing was saved."; + case "too-many-assignees": + return `A task can have up to ${MAX_ASSIGNEES} people assigned. Nothing was saved.`; + case "signer-agent": + return "Only a person can save a task, not an agent. Nothing was saved."; + default: + return "This change isn’t allowed. Nothing was saved."; + } } diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts index 31ab7f91b8..101a87d418 100644 --- a/src/bundled/tasks/tools.test.ts +++ b/src/bundled/tasks/tools.test.ts @@ -441,12 +441,12 @@ it("names a project member a move shuts out", async () => { expect(assignees(signed[0])).toEqual([]); }); -it("shows the relay's reason when it refuses an assignee anyway", async () => { +it("says the relay's reason in plain words when it refuses an assignee anyway", async () => { const { call } = setup( async () => { throw new PublishRejected( "rejected", - "invalid: assignee can't read this task", + `invalid: assignee-unreadable:${person} — an assignee can't see this artifact`, ); }, () => [head("d".repeat(64))], @@ -454,10 +454,19 @@ it("shows the relay's reason when it refuses an assignee anyway", async () => { await expect( call("tasks_update", { id, assignees: [person] }), ).rejects.toThrow( - "Couldn’t save the task: invalid: assignee can't read this task", + `Riley can’t see #design, so they can’t be assigned. Nothing was saved. The relay said: invalid: assignee-unreadable:${person} — an assignee can't see this artifact`, ); }); +it("keeps someone assigned who lost access when an edit adds nobody new", async () => { + const { call, signed } = setup( + async () => "", + () => [head("d".repeat(64), [["assignee", leo]])], + ); + await call("tasks_update", { id, assignees: [leo, person] }); + expect(assignees(signed[0])).toEqual([leo, person]); +}); + it("previews a move, by place, and moves only with its confirm", async () => { const { call, signed } = setup( async () => "", diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts index 80114077f0..dbcbd39256 100644 --- a/src/bundled/tasks/tools.ts +++ b/src/bundled/tasks/tools.ts @@ -34,7 +34,13 @@ import { readPlaces, readReaders, } from "./places"; -import { readTask, readTasks, saveTask, type TaskSource } from "./store"; +import { + readTask, + readTasks, + saveTask, + TaskRefused, + type TaskSource, +} from "./store"; import { holdsWords, sameness } from "./similar"; type Agents = Pick; @@ -64,6 +70,15 @@ const deadline = (client: Client) => ? AbortSignal.any([client.signal, AbortSignal.timeout(STEP_TIMEOUT)]) : AbortSignal.timeout(STEP_TIMEOUT); +/** Saves as `saveTask` does, but a refusal also carries the relay's own + * text: an agent can act on it, where a person gets only the plain line. */ +const save: typeof saveTask = (...args) => + saveTask(...args).catch((reason: unknown) => { + throw reason instanceof TaskRefused + ? new Error(`${reason.message} The relay said: ${reason.relay}`) + : reason; + }); + /** The agent's own reads, as task reads take them. */ function agentReads(client: Client, session: RelaySession): TaskSource { return { @@ -261,7 +276,7 @@ export function addTaskTools(agents: Agents) { home && home !== task.home ? { op: "move" as const, base: task, home } : { op: "update" as const, base: task }; - const result = await saveTask(session, reads, edit(task), target, signal); + const result = await save(session, reads, edit(task), target, signal); if (result.status === "saved") return result.task; // Someone else saved first; the agent's own read found their version. // A task that moved meanwhile isn't changed in its new place unseen. @@ -436,7 +451,7 @@ export function addTaskTools(agents: Agents) { .join("\n")}${unsure}`; // Named before saving, so a retry after an unclear outcome can check. const id = crypto.randomUUID(); - const result = await saveTask( + const result = await save( session, reads, fields, @@ -529,8 +544,16 @@ export function addTaskTools(agents: Agents) { "Done or Cancelled needs evidence: say in one line why, such as the merged pull request or who said it's finished", ); const task = await current(reads, id, signal); + // Only the people it adds: someone assigned who has since lost access + // doesn't block an edit, as the relay rules too. if (assignees) - await checkAssignees(session, reads, task.home, assignees, signal); + await checkAssignees( + session, + reads, + task.home, + assignees.filter((key) => !task.assignees.includes(key)), + signal, + ); // The evidence comes first: no comment, no close. if (closing && evidence && task.status !== status) await postAgentComment(