Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
128 changes: 127 additions & 1 deletion src/bundled/tasks/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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"]]) => ({
Expand Down Expand Up @@ -77,6 +78,7 @@ function session(publish: () => Promise<string>, heads: object[] = []) {
relayAuthor: relayKey,
snapshotRead: read,
configArtifactWriter: { sign, publish: vi.fn(publish) },
profiles: { snapshot: () => new Map([[riley, { name: "Riley" }]]) },
} as unknown as RelaySession,
};
}
Expand Down Expand Up @@ -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");
Expand Down
160 changes: 127 additions & 33 deletions src/bundled/tasks/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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";
Expand Down Expand Up @@ -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.");
Expand All @@ -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<string, Place>(),
);
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: <code>:<keys> — <text>`; 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.";
}
}
15 changes: 12 additions & 3 deletions src/bundled/tasks/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,23 +441,32 @@ 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))],
);
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 () => "",
Expand Down
Loading
Loading