From 9840870e42dde9ba43c4dbf8a7e2d0367d0c5e37 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 00:13:04 -0800
Subject: [PATCH 01/18] feat(design-system): compact Combobox trigger and menu
minimum width
Add `Combobox.Trigger variant="compact"`, matching Select's compact variant:
an outlined capsule whose label is announced rather than shown, for rows of
compact controls such as a task's status and assignees.
Give every Combobox menu the compact Select's minimum width, so a narrow
trigger such as an avatar stack no longer squeezes names mid-word.
Co-authored-by: Vogue <86a9516b8bdd0bbb22ab9340ed157fccdf422ae31bbb2fe2d59aba37c886f5d3@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/shared/design-system/DESIGN.md | 5 ++
src/shared/design-system/styles/forms.css | 9 ++++
.../design-system/ui/ChoiceControls.test.tsx | 24 +++++++++
src/shared/design-system/ui/Combobox.tsx | 51 ++++++++++++++++--
.../design-system/ui/FormSpecimens.tsx | 54 +++++++++++++++++++
5 files changed, 138 insertions(+), 5 deletions(-)
diff --git a/src/shared/design-system/DESIGN.md b/src/shared/design-system/DESIGN.md
index 48c6f68b85..65d50bb890 100644
--- a/src/shared/design-system/DESIGN.md
+++ b/src/shared/design-system/DESIGN.md
@@ -1131,6 +1131,11 @@ filtering, custom-value commits, and async requests with the feature. Its Contro
owns the label, input and integrated browse caret; Popup and Item own the shared
menu presentation. For a closed dropdown with search inside, use Combobox.Trigger
and Combobox.Popup with search; opening focuses the popup search input.
+In a row of compact controls, such as beside a compact Select, use
+`Combobox.Trigger variant="compact"`: the same outlined capsule as a compact
+Select, with its label announced rather than shown. Combobox menus keep the
+compact Select's minimum width, so a narrow trigger such as an avatar stack never
+squeezes its choices.
Use its loading state while discovering options, and keep
retry/cancel actions with the feature. Do not style a native select as an Input
or attach a separate round button to mimic a combobox.
diff --git a/src/shared/design-system/styles/forms.css b/src/shared/design-system/styles/forms.css
index c7b8b04175..66416bfd47 100644
--- a/src/shared/design-system/styles/forms.css
+++ b/src/shared/design-system/styles/forms.css
@@ -433,6 +433,15 @@
width: var(--anchor-width);
overflow-wrap: anywhere;
}
+ /* A combobox menu can open from a trigger narrower than its choices, such as
+ a compact avatar trigger. Keep the compact Select's minimum so names never
+ break mid-word. */
+ .buzz-select-popup[data-combobox-size] {
+ min-width: min(
+ max(var(--anchor-width), 11.25rem),
+ calc(100vw - var(--space-6))
+ );
+ }
/* Roughly four avatar-and-detail rows plus search. The viewport may make
the list shorter; keep search fixed and every result scrollable. */
.buzz-select-popup[data-combobox-size="compact"] {
diff --git a/src/shared/design-system/ui/ChoiceControls.test.tsx b/src/shared/design-system/ui/ChoiceControls.test.tsx
index 70d54c8201..de3b7cf71e 100644
--- a/src/shared/design-system/ui/ChoiceControls.test.tsx
+++ b/src/shared/design-system/ui/ChoiceControls.test.tsx
@@ -395,3 +395,27 @@ it("defaults combobox queries to exact text while permitting explicit correction
expect(input).toHaveAttribute("autocapitalize", "sentences");
expect(input).toHaveAttribute("spellcheck", "true");
});
+
+it("names a compact Combobox trigger without showing its label", async () => {
+ const user = userEvent.setup();
+ render(
+
+
+ Nobody
+
+
+
+ {(item: (typeof options)[number]) => (
+
+ {item.label}
+
+ )}
+
+
+ ,
+ );
+ const trigger = screen.getByRole("combobox", { name: "Assignees" });
+ expect(screen.queryByText("Assignees")).not.toBeInTheDocument();
+ await user.click(trigger);
+ expect(await screen.findByRole("option", { name: "One" })).toBeVisible();
+});
diff --git a/src/shared/design-system/ui/Combobox.tsx b/src/shared/design-system/ui/Combobox.tsx
index 5607a5d3e7..250d0217cd 100644
--- a/src/shared/design-system/ui/Combobox.tsx
+++ b/src/shared/design-system/ui/Combobox.tsx
@@ -4,6 +4,7 @@ import { CaretDownIcon, CircleNotchIcon, CheckIcon } from "../icons";
import { Field } from "./Field";
import { InputGroup } from "./InputGroup";
import { IconButton } from "./IconButton";
+import { Button } from "./Button";
/** Shared presentation; callers retain filtering, custom values and async work. */
function Control({
@@ -94,20 +95,60 @@ function Control({
);
}
-/** A button-style field for comboboxes whose search input lives in the popup. */
+/** A button-style trigger for comboboxes whose search input lives in the popup.
+ * `field` is a labelled form field. `compact` matches Select's compact
+ * variant: a small outlined capsule whose label is announced, not shown, for
+ * rows of adjacent controls. */
function Trigger({
label,
children,
- error,
disabled,
+ ...props
}: {
label: string;
children: ReactNode;
- error?: ReactNode;
disabled?: boolean | undefined;
-}) {
+} & (
+ | { variant?: "field"; error?: ReactNode }
+ | { variant: "compact"; error?: never }
+)) {
+ if (props.variant === "compact")
+ return (
+
+ (
+
+
+
+ {children}
+
+
+
+
+
+
+ )}
+ />
+
+ );
return (
-
+
(["Riley"]);
+ return (
+
+
+
+
+ {chosen.length ? chosen.map((name) => name[0]).join(", ") : "Nobody"}
+
+
+
+ {(item: string) => (
+
+ {item}
+
+ )}
+
+
+
+
+ );
+}
+
export function ComboboxExamples() {
const [state, setState] = useState("ready");
return (
@@ -779,6 +824,15 @@ ${workspaceComboboxCode}`}
+
+ {initials}
+`}
+ >
+
+
Date: Mon, 16 Nov 2026 09:23:20 -0800
Subject: [PATCH 02/18] fix(design-system): keep the compact Combobox trigger
at Select's height
An avatar stack inside the compact trigger sat on the text baseline, which
grew the line box and made the trigger 37px beside a 32px compact Select.
Align artwork in a compact value to the line box, and tuck identity artwork
toward the leading edge as small identity buttons do. The viewer specimen now
uses a real avatar stack.
Co-authored-by: Vogue <86a9516b8bdd0bbb22ab9340ed157fccdf422ae31bbb2fe2d59aba37c886f5d3@buzz.block.builderlab.xyz>
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/shared/design-system/styles/forms.css | 15 +++++++++++++++
.../fixtures/design-system/ui/FormSpecimens.tsx | 17 +++++++++++++++--
2 files changed, 30 insertions(+), 2 deletions(-)
diff --git a/src/shared/design-system/styles/forms.css b/src/shared/design-system/styles/forms.css
index 66416bfd47..cfc040fd53 100644
--- a/src/shared/design-system/styles/forms.css
+++ b/src/shared/design-system/styles/forms.css
@@ -392,6 +392,21 @@
display: flex;
flex-shrink: 0;
}
+ /* Artwork in a compact value, such as a Combobox trigger's avatar stack,
+ aligns to the line box instead of the text baseline, so the trigger keeps
+ the compact Select's height. Identity artwork tucks toward the leading
+ edge, as small identity buttons do. */
+ .buzz-select[data-variant="compact"]
+ .buzz-select-value
+ > :is([data-avatar-stack], svg) {
+ vertical-align: top;
+ }
+ .buzz-select[data-variant="compact"]
+ .buzz-button[data-size="sm"]:has(
+ .buzz-select-value > [data-avatar-stack]:first-child
+ ) {
+ padding-inline-start: var(--space-1h);
+ }
.buzz-select-popup[data-variant="compact"] {
min-width: min(
max(var(--anchor-width), 11.25rem),
diff --git a/tests/fixtures/design-system/ui/FormSpecimens.tsx b/tests/fixtures/design-system/ui/FormSpecimens.tsx
index b431033ee0..620d988205 100644
--- a/tests/fixtures/design-system/ui/FormSpecimens.tsx
+++ b/tests/fixtures/design-system/ui/FormSpecimens.tsx
@@ -14,6 +14,7 @@ import { Select } from "../../../../src/shared/design-system/ui/Select";
import { PreferenceRow } from "../../../../src/shared/design-system/ui/PreferenceRow";
import { SettingsGroup } from "../../../../src/shared/design-system/ui/SettingsGroup";
import { Combobox } from "../../../../src/shared/design-system/ui/Combobox";
+import { AvatarStack } from "../../../../src/shared/design-system/ui/AvatarStack";
import { Button } from "../../../../src/shared/design-system/ui/Button";
import { IconButton } from "../../../../src/shared/design-system/ui/IconButton";
@@ -787,7 +788,19 @@ function CompactTriggerExample() {
onValueChange={setChosen}
>
- {chosen.length ? chosen.map((name) => name[0]).join(", ") : "Nobody"}
+ {chosen.length ? (
+ ({
+ id: name,
+ name,
+ shape: "circle",
+ }))}
+ />
+ ) : (
+ "Nobody"
+ )}
@@ -828,7 +841,7 @@ ${workspaceComboboxCode}`}
title="Compact trigger"
description="In a row of compact controls, the trigger matches a compact Select and announces its label. The menu keeps a minimum width, so short triggers never squeeze names."
code={`
- {initials}
+
`}
>
From 397a9571f2ad252c2934c40ff2b3e76c1889d954 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sat, 14 Nov 2026 13:50:01 -1000
Subject: [PATCH 03/18] feat(solo): let plugins ask the owner to share a Solo
chat
Plugins can call `ctx.reflect.get("chatSharing").requestShare(session,
channelId)` to ask the viewer to make one of their own Solo chats View
only. The app shows its existing "Share this chat?" confirmation with the
same disclosure, and only the chat's owner can confirm. An agent tool
that calls it raises the same dialog in the owner's app and cannot skip
it. Requests end when the calling plugin stops.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/app/App.tsx | 2 +
src/app/services.ts | 7 +
src/features/solo/ShareRequestDialog.test.tsx | 168 ++++++++++++++++++
src/features/solo/ShareRequestDialog.tsx | 95 ++++++++++
src/features/solo/share-requests.ts | 151 ++++++++++++++++
5 files changed, 423 insertions(+)
create mode 100644 src/features/solo/ShareRequestDialog.test.tsx
create mode 100644 src/features/solo/ShareRequestDialog.tsx
create mode 100644 src/features/solo/share-requests.ts
diff --git a/src/app/App.tsx b/src/app/App.tsx
index 331703994a..770841db2c 100644
--- a/src/app/App.tsx
+++ b/src/app/App.tsx
@@ -31,6 +31,7 @@ import { MediaMenuDownloadNotice } from "../features/messages/MediaDownloadActio
import { CreationReview } from "../bundled/agents/CreationReview";
import { UpdateReview } from "../bundled/agents/UpdateReview";
import { TeamUpdateReview } from "../bundled/agents/TeamUpdateReview";
+import { ShareRequestDialog } from "../features/solo/ShareRequestDialog";
import { InterruptedNotice } from "../features/agents/InterruptedNotice";
import {
useCallback,
@@ -770,6 +771,7 @@ function ConnectedAppContent({ services }: { services: AppServices }) {
+
{!settings && startup === "recovery" ? (
) : !settings &&
diff --git a/src/app/services.ts b/src/app/services.ts
index a7bcc0f12e..90112751b4 100644
--- a/src/app/services.ts
+++ b/src/app/services.ts
@@ -73,6 +73,10 @@ import {
createPluginInstallerService,
} from "../plugins/installer";
import { withTimeout } from "../plugins/timeout";
+import {
+ createChatSharingService,
+ createShareRequests,
+} from "../features/solo/share-requests";
import { createExternalApps } from "../features/agents/external-connection";
export function createServices() {
@@ -111,6 +115,8 @@ export function createServices() {
navigation.open({ version: 1, kind: "settings", section: "plugins" }),
});
createPluginInstallerService(ctx, { core: pluginInstallCore });
+ const shareRequests = createShareRequests();
+ createChatSharingService(ctx, shareRequests);
const sidebarScope = new SidebarScopeService(ctx);
const sidebarRows = new SidebarRowsService(ctx);
const panels = new PanelsService(ctx);
@@ -321,6 +327,7 @@ export function createServices() {
pages,
sidebarSections,
pluginInstallRequests,
+ shareRequests,
sidebarScope,
sidebarRows,
panels,
diff --git a/src/features/solo/ShareRequestDialog.test.tsx b/src/features/solo/ShareRequestDialog.test.tsx
new file mode 100644
index 0000000000..701f4ab08d
--- /dev/null
+++ b/src/features/solo/ShareRequestDialog.test.tsx
@@ -0,0 +1,168 @@
+// @vitest-environment jsdom
+import { Context } from "@deepseek-ai/cordis";
+import { act, cleanup, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, expect, it, vi } from "vitest";
+import type { RelaySession } from "../relay/session";
+import type {
+ ChannelDetails,
+ ChannelDetailsDraft,
+} from "../relay/channel-details-protocol";
+import { ShareRequestDialog } from "./ShareRequestDialog";
+import {
+ type ChatSharing,
+ createChatSharingService,
+ createShareRequests,
+} from "./share-requests";
+
+afterEach(cleanup);
+
+const id = "11111111-1111-4111-8111-111111111111";
+const viewer = "a".repeat(64);
+
+function fixture(
+ visibility: "public" | "private" = "private",
+ creator = viewer,
+) {
+ let base: ChannelDetails = {
+ channelId: id,
+ version: "version",
+ name: "Chat",
+ description: "",
+ visibility,
+ joinRole: "member",
+ canEdit: true,
+ labels: ["buzz.solo"],
+ };
+ let fail = false;
+ const save = vi.fn(
+ async (_base: ChannelDetails, draft: ChannelDetailsDraft) => {
+ if (fail) throw new Error("Relay refused the change.");
+ base = { ...base, ...draft, version: "saved" };
+ },
+ );
+ const session = {
+ viewer,
+ channels: {
+ list: () => ({
+ channels: [{ id, channelType: "solo", creator, members: [creator] }],
+ }),
+ },
+ channelDetails: {
+ load: vi.fn(async () => base),
+ save,
+ check: vi.fn(async () => {}),
+ snapshot: () => undefined,
+ },
+ } as unknown as RelaySession;
+ return {
+ session,
+ save,
+ failNext(value: boolean) {
+ fail = value;
+ },
+ };
+}
+
+it("shows the app's confirmation and makes the chat View only only when confirmed", async () => {
+ const f = fixture();
+ const requests = createShareRequests();
+ render( );
+ const outcome = requests.request(f.session, id);
+ expect(await screen.findByText("Share this chat?")).toBeTruthy();
+ expect(
+ screen.getByText(
+ /full history, Canvas, workspace folders, and agent instructions/,
+ ),
+ ).toBeTruthy();
+ expect(f.save).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole("button", { name: "Share" }));
+ expect(await outcome).toBe("shared");
+ expect(f.save).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ visibility: "private" }),
+ expect.objectContaining({ visibility: "public", joinRole: "guest" }),
+ expect.any(AbortSignal),
+ expect.any(Function),
+ );
+ expect(screen.queryByText("Share this chat?")).toBeNull();
+});
+
+it("changes nothing when the viewer cancels", async () => {
+ const f = fixture();
+ const requests = createShareRequests();
+ render( );
+ const outcome = requests.request(f.session, id);
+ await userEvent.click(await screen.findByRole("button", { name: "Cancel" }));
+ expect(await outcome).toBe("cancelled");
+ expect(f.save).not.toHaveBeenCalled();
+});
+
+it("keeps the dialog open with the error so the viewer can retry", async () => {
+ const f = fixture();
+ f.failNext(true);
+ const requests = createShareRequests();
+ render( );
+ const outcome = requests.request(f.session, id);
+ await userEvent.click(await screen.findByRole("button", { name: "Share" }));
+ expect((await screen.findByRole("alert")).textContent).toBe(
+ "Relay refused the change.",
+ );
+ f.failNext(false);
+ await userEvent.click(screen.getByRole("button", { name: "Retry" }));
+ expect(await outcome).toBe("shared");
+});
+
+it("resolves without a dialog when the chat is already open", async () => {
+ const f = fixture("public");
+ const requests = createShareRequests();
+ render( );
+ expect(await requests.request(f.session, id)).toBe("shared");
+ expect(requests.snapshot()).toEqual([]);
+ expect(screen.queryByText("Share this chat?")).toBeNull();
+});
+
+it("refuses without a dialog for a chat the viewer does not own", async () => {
+ const f = fixture("private", "b".repeat(64));
+ const requests = createShareRequests();
+ expect(await requests.request(f.session, id)).toBe("unavailable");
+ expect(requests.snapshot()).toEqual([]);
+ expect(f.save).not.toHaveBeenCalled();
+});
+
+it("asks once for repeated requests about the same chat", async () => {
+ const f = fixture();
+ const requests = createShareRequests();
+ render( );
+ const first = requests.request(f.session, id);
+ await screen.findByText("Share this chat?");
+ const second = requests.request(f.session, id);
+ expect(requests.snapshot()).toHaveLength(1);
+ await userEvent.click(screen.getByRole("button", { name: "Share" }));
+ expect(await first).toBe("shared");
+ expect(await second).toBe("shared");
+ expect(f.save).toHaveBeenCalledOnce();
+});
+
+it("withdraws a plugin's request when the plugin stops", async () => {
+ const f = fixture();
+ const root = new Context();
+ const requests = createShareRequests();
+ createChatSharingService(root, requests);
+ let sharing: ChatSharing | undefined;
+ const fiber = root
+ .extend({ pluginOwner: { id: "example.tasks", revision: "one" } })
+ .plugin((ctx) => {
+ sharing = ctx.reflect.get("chatSharing");
+ });
+ await fiber.await();
+ render( );
+ if (!sharing) throw new Error("chatSharing is unavailable");
+ const outcome = sharing.requestShare(f.session, id);
+ await screen.findByText("Share this chat?");
+ await act(async () => {
+ await fiber.dispose();
+ });
+ expect(await outcome).toBe("cancelled");
+ expect(screen.queryByText("Share this chat?")).toBeNull();
+ expect(f.save).not.toHaveBeenCalled();
+});
diff --git a/src/features/solo/ShareRequestDialog.tsx b/src/features/solo/ShareRequestDialog.tsx
new file mode 100644
index 0000000000..aad44fb965
--- /dev/null
+++ b/src/features/solo/ShareRequestDialog.tsx
@@ -0,0 +1,95 @@
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import type { ChannelDetailsDraft } from "../relay/channel-details-protocol";
+import { AlertDialog } from "../../shared/design-system/ui/AlertDialog";
+import { Button } from "../../shared/design-system/ui/Button";
+import { soloShareDisclosure } from "./labels";
+import { shareSoloChatAccess } from "./share";
+import type { ShareRequest, ShareRequests } from "./share-requests";
+
+/** The viewer confirms a `chatSharing` request with the app's own wording. */
+export function ShareRequestDialog({ requests }: { requests: ShareRequests }) {
+ const pending = useSyncExternalStore(requests.subscribe, requests.snapshot);
+ const request = pending[0];
+ if (!request) return null;
+ return (
+
+ );
+}
+
+function ShareRequestConfirmation({
+ request,
+ requests,
+}: {
+ request: ShareRequest;
+ requests: ShareRequests;
+}) {
+ const cancel = useRef(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ // An uncertain save is checked on retry, never republished.
+ const attempts = useRef(new Map());
+ const controller = useRef(new AbortController());
+ useEffect(() => {
+ const active = controller.current;
+ return () => active.abort();
+ }, []);
+ const decline = () => requests.settle(request.id, "cancelled");
+ const confirm = async () => {
+ if (busy) return;
+ setBusy(true);
+ setError("");
+ const { signal } = controller.current;
+ try {
+ await shareSoloChatAccess(request.session, request.details.channelId, {
+ signal,
+ confirmed: request.details,
+ attempts: attempts.current,
+ });
+ requests.settle(request.id, "shared");
+ } catch (reason) {
+ if (signal.aborted) return;
+ setError(
+ reason instanceof Error ? reason.message : "Couldn’t share this chat.",
+ );
+ setBusy(false);
+ }
+ };
+ return (
+
+ This changes the chat from Private to View only.{" "}
+ {soloShareDisclosure()}
+ >
+ }
+ pending={busy}
+ onClose={decline}
+ initialFocus={cancel}
+ actions={
+ <>
+
+ Cancel
+
+ void confirm()}
+ >
+ {error ? "Retry" : "Share"}
+
+ >
+ }
+ >
+ {error ? (
+
+ {error}
+
+ ) : null}
+
+ );
+}
diff --git a/src/features/solo/share-requests.ts b/src/features/solo/share-requests.ts
new file mode 100644
index 0000000000..1ea9ecda31
--- /dev/null
+++ b/src/features/solo/share-requests.ts
@@ -0,0 +1,151 @@
+import { Service, type Context } from "@deepseek-ai/cordis";
+import type { ChannelDetails } from "../relay/channel-details-protocol";
+import type { RelaySession } from "../relay/session";
+import { shareSoloChatAccess } from "./share";
+
+export type ChatShareOutcome = "shared" | "cancelled" | "unavailable";
+
+/** The handle plugins read with `ctx.reflect.get("chatSharing")`. */
+export type ChatSharing = Readonly<{
+ /**
+ * Ask the viewer to make one of their own Solo chats View only. The app
+ * shows its "Share this chat?" confirmation; nothing changes unless the
+ * viewer confirms. Resolves `"shared"` once the chat is View only or public
+ * (at once, without a dialog, when it already is), `"cancelled"` when the
+ * viewer declines or the caller stops, and `"unavailable"` when the viewer
+ * cannot share it. Never rejects.
+ */
+ requestShare(
+ session: RelaySession,
+ channelId: string,
+ ): Promise;
+}>;
+
+declare module "@deepseek-ai/cordis" {
+ interface Context {
+ /** Read with `ctx.reflect.get("chatSharing")` for old-host compatibility. */
+ chatSharing?: ChatSharing;
+ }
+}
+
+/** A confirmation waiting for the viewer, with the access it was asked about. */
+export type ShareRequest = Readonly<{
+ id: string;
+ session: RelaySession;
+ details: ChannelDetails;
+}>;
+
+type Pending = ShareRequest & {
+ readonly done: Promise;
+ readonly resolve: (outcome: ChatShareOutcome) => void;
+ readonly controller: AbortController;
+};
+
+// Each request holds a dialog open for the viewer, so callers cannot queue
+// without bound.
+const PENDING_MAX = 16;
+
+export type ShareRequests = ReturnType;
+
+/** The app-owned queue behind `chatSharing`: one confirmation at a time. */
+export function createShareRequests() {
+ let pending: readonly Pending[] = [];
+ let next = 0;
+ const listeners = new Set<() => void>();
+ const notify = () => {
+ for (const listener of listeners) listener();
+ };
+ const settle = (id: string, outcome: ChatShareOutcome) => {
+ const item = pending.find((entry) => entry.id === id);
+ if (!item) return;
+ pending = pending.filter((entry) => entry !== item);
+ item.controller.abort();
+ item.resolve(outcome);
+ notify();
+ };
+
+ async function request(
+ session: RelaySession,
+ channelId: string,
+ lifetime?: (end: () => void) => () => void,
+ ): Promise {
+ const same = pending.find(
+ (entry) =>
+ entry.session === session && entry.details.channelId === channelId,
+ );
+ if (same) return same.done;
+ const controller = new AbortController();
+ const stop = lifetime?.(() => controller.abort());
+ try {
+ // The same check both share dialogs make: only the viewer's own Solo
+ // chat, with its current signed access.
+ let details: ChannelDetails | undefined;
+ try {
+ details = await shareSoloChatAccess(session, channelId, {
+ signal: controller.signal,
+ attempts: new Map(),
+ });
+ } catch {
+ return controller.signal.aborted ? "cancelled" : "unavailable";
+ }
+ if (!details || details.visibility === "public") return "shared";
+ if (pending.length >= PENDING_MAX) return "unavailable";
+ const raced = pending.find(
+ (entry) =>
+ entry.session === session && entry.details.channelId === channelId,
+ );
+ if (raced) return await raced.done;
+ let resolve!: (outcome: ChatShareOutcome) => void;
+ const done = new Promise((settled) => {
+ resolve = settled;
+ });
+ const id = `share-${++next}`;
+ pending = [
+ ...pending,
+ { id, session, details, done, resolve, controller },
+ ];
+ controller.signal.addEventListener(
+ "abort",
+ () => settle(id, "cancelled"),
+ { once: true },
+ );
+ notify();
+ return await done;
+ } finally {
+ stop?.();
+ }
+ }
+
+ return {
+ request,
+ /** The confirmations waiting for the viewer, oldest first. */
+ snapshot: (): readonly ShareRequest[] => pending,
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => void listeners.delete(listener);
+ },
+ settle,
+ };
+}
+
+/** Provide `chatSharing`, tying each request to its caller's lifetime. */
+export function createChatSharingService(
+ ctx: Context,
+ requests: ShareRequests,
+): ChatSharing {
+ class ChatSharingService extends Service implements ChatSharing {
+ constructor() {
+ super(ctx, "chatSharing");
+ }
+
+ // A method, so Cordis supplies the caller's context for its lifetime.
+ requestShare(session: RelaySession, channelId: string) {
+ const caller = this.ctx;
+ return requests.request(session, channelId, (end) => {
+ const stop = caller.effect(() => end);
+ return () => void stop();
+ });
+ }
+ }
+ return new ChatSharingService();
+}
From 138a74ea9073a0504ea05b9ea780a4a972950b2c Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sat, 14 Nov 2026 14:09:30 -1000
Subject: [PATCH 04/18] feat(tasks): add a bundled Tasks plugin
Tasks hold the context for a piece of work and link the conversations
about it. Each task is a NIP-AR artifact in one open system channel an
admin sets up; saves are compare-and-set on the revision the editor
opened, so a concurrent edit is reported, never overwritten.
- Tasks page: filter by status and mine, master/detail that collapses to
one pane with Back at narrow widths.
- Conversation panel: tasks linked here, new task from this chat, link
to an existing task.
- Agent tools: tasks_create, tasks_read, tasks_update, tasks_link.
- Linking a private Solo chat goes through the app's chatSharing
confirmation; other conversations link without changing access.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/index.ts | 7 +
src/bundled/tasks/README.md | 16 +
src/bundled/tasks/StatusIcon.tsx | 22 +
src/bundled/tasks/TaskView.test.tsx | 129 ++++++
src/bundled/tasks/TaskView.tsx | 513 ++++++++++++++++++++++++
src/bundled/tasks/Tasks.module.css | 145 +++++++
src/bundled/tasks/TasksGate.tsx | 66 +++
src/bundled/tasks/TasksPage.tsx | 331 +++++++++++++++
src/bundled/tasks/TasksPanel.tsx | 180 +++++++++
src/bundled/tasks/index.tsx | 123 ++++++
src/bundled/tasks/linking.test.ts | 26 ++
src/bundled/tasks/linking.ts | 23 ++
src/bundled/tasks/manifest.json | 7 +
src/bundled/tasks/model.test.ts | 144 +++++++
src/bundled/tasks/model.ts | 172 ++++++++
src/bundled/tasks/react.ts | 97 +++++
src/bundled/tasks/store.test.ts | 94 +++++
src/bundled/tasks/store.ts | 189 +++++++++
src/bundled/tasks/tasks-channel.ts | 96 +++++
src/bundled/tasks/tools.test.ts | 139 +++++++
src/bundled/tasks/tools.ts | 347 ++++++++++++++++
src/shared/design-system/icons/index.ts | 6 +
22 files changed, 2872 insertions(+)
create mode 100644 src/bundled/tasks/README.md
create mode 100644 src/bundled/tasks/StatusIcon.tsx
create mode 100644 src/bundled/tasks/TaskView.test.tsx
create mode 100644 src/bundled/tasks/TaskView.tsx
create mode 100644 src/bundled/tasks/Tasks.module.css
create mode 100644 src/bundled/tasks/TasksGate.tsx
create mode 100644 src/bundled/tasks/TasksPage.tsx
create mode 100644 src/bundled/tasks/TasksPanel.tsx
create mode 100644 src/bundled/tasks/index.tsx
create mode 100644 src/bundled/tasks/linking.test.ts
create mode 100644 src/bundled/tasks/linking.ts
create mode 100644 src/bundled/tasks/manifest.json
create mode 100644 src/bundled/tasks/model.test.ts
create mode 100644 src/bundled/tasks/model.ts
create mode 100644 src/bundled/tasks/react.ts
create mode 100644 src/bundled/tasks/store.test.ts
create mode 100644 src/bundled/tasks/store.ts
create mode 100644 src/bundled/tasks/tasks-channel.ts
create mode 100644 src/bundled/tasks/tools.test.ts
create mode 100644 src/bundled/tasks/tools.ts
diff --git a/src/bundled/index.ts b/src/bundled/index.ts
index d49af2cd6d..3c5478d072 100644
--- a/src/bundled/index.ts
+++ b/src/bundled/index.ts
@@ -13,6 +13,8 @@ import * as huddles from "./huddles";
import builderlabManifest from "./builderlab/manifest.json";
import * as builderlab from "./builderlab";
import * as todos from "./todos";
+import tasksManifest from "./tasks/manifest.json";
+import * as tasks from "./tasks";
import diffsManifest from "./diffs/manifest.json";
import * as diffs from "./diffs";
import mermaidManifest from "./mermaid/manifest.json";
@@ -138,6 +140,11 @@ export const bundledPlugins: readonly BundledPlugin[] = [
module: todos,
enabledByDefault: false,
},
+ {
+ manifest: { ...tasksManifest, apiVersion: 1 },
+ module: tasks,
+ enabledByDefault: false,
+ },
{
manifest: { ...diffsManifest, apiVersion: 1 },
module: diffs,
diff --git a/src/bundled/tasks/README.md b/src/bundled/tasks/README.md
new file mode 100644
index 0000000000..c5bc1963f8
--- /dev/null
+++ b/src/bundled/tasks/README.md
@@ -0,0 +1,16 @@
+# Tasks
+
+A task holds the context for a piece of work and links the conversations about it, so anyone can pick it up later.
+
+## Getting started
+
+1. A community admin opens **Tasks** once and chooses **Set up Tasks**.
+2. Choose **New task**, give it a title and a description, and add images if they help.
+3. In a chat or channel, choose **Tasks** in its header to see the tasks linked there, make one from the chat, or link the chat to an existing task.
+
+You can also ask your agent to make a task from a conversation.
+
+- Everyone in the community can see and edit every task.
+- Linking a private Solo chat makes it View only: anyone in the community can read it, and only its members can post. You confirm that first. Unlinking doesn't change it back.
+- Linking a private channel doesn't change who can read it. People who can't read it see only that a private channel is linked.
+- If someone else saves a task while you're editing it, your text is kept and you choose what to save.
diff --git a/src/bundled/tasks/StatusIcon.tsx b/src/bundled/tasks/StatusIcon.tsx
new file mode 100644
index 0000000000..3319dbcf6e
--- /dev/null
+++ b/src/bundled/tasks/StatusIcon.tsx
@@ -0,0 +1,22 @@
+import {
+ CheckCircleIcon,
+ CircleHalfIcon,
+ CircleIcon,
+ XCircleIcon,
+} from "../../shared/design-system/icons/index";
+import type { TaskStatus } from "./model";
+
+/** Each status has its own glyph; none borrows a warning or error meaning. */
+export function StatusIcon({ status }: { status: TaskStatus }) {
+ const props = { size: 16, "aria-hidden": true } as const;
+ switch (status) {
+ case "open":
+ return ;
+ case "in_progress":
+ return ;
+ case "done":
+ return ;
+ case "wont_do":
+ return ;
+ }
+}
diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx
new file mode 100644
index 0000000000..c6cd916f2b
--- /dev/null
+++ b/src/bundled/tasks/TaskView.test.tsx
@@ -0,0 +1,129 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import { PublishRejected } from "../../features/relay/outbox";
+import type { RelaySession } from "../../features/relay/session";
+import { TASK_TYPE, type Task, taskOf } from "./model";
+import { TaskView } from "./TaskView";
+
+afterEach(cleanup);
+
+const viewer = "a".repeat(64);
+const chat = "11111111-1111-4111-8111-111111111111";
+const revision = (id: string, title: string, content: object = {}) => ({
+ id,
+ pubkey: "b".repeat(64),
+ sig: "",
+ created_at: 5,
+ kind: 45010,
+ content: JSON.stringify({ version: 1, author: viewer, ...content }),
+ tags: [
+ ["d", "task-1"],
+ ["type", TASK_TYPE],
+ ["title", title],
+ ],
+});
+const mine = taskOf(revision("d".repeat(64), "Fix the header")) as Task;
+const theirs = revision("c".repeat(64), "Their title");
+
+function setup(publish: () => Promise) {
+ const signed: { tags: string[][] }[] = [];
+ const session = {
+ viewer,
+ profiles: { snapshot: () => new Map() },
+ channels: { list: () => ({ channels: [] }) },
+ snapshotRead: vi.fn(async () => [theirs]),
+ configArtifactWriter: {
+ sign: vi.fn(async (template: { tags: string[][] }) => {
+ signed.push(template);
+ return { ...template, id: "f".repeat(64), pubkey: viewer, sig: "" };
+ }),
+ publish: vi.fn(publish),
+ },
+ } as unknown as RelaySession;
+ return { session, signed };
+}
+
+it("keeps the person's text on a conflict, then saves over the newer version", async () => {
+ let refuse = true;
+ const { session, signed } = setup(async () => {
+ if (refuse) throw new PublishRejected("rejected", "conflict: stale prev");
+ return "";
+ });
+ const onSaved = vi.fn();
+ render(
+ "shared"}
+ openConversation={() => {}}
+ onSaved={onSaved}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.change(screen.getByLabelText("Title"), {
+ target: { value: "My title" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Someone else changed this task. Your text is kept.",
+ );
+ expect(screen.getByLabelText("Title")).toHaveValue("My title");
+ refuse = false;
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ await vi.waitFor(() => expect(onSaved).toHaveBeenCalled());
+ expect(signed[1]?.tags).toContainEqual(["prev", theirs.id]);
+ expect(signed[1]?.tags).toContainEqual(["title", "My title"]);
+});
+
+it("shows their version when asked", async () => {
+ const { session } = setup(async () => {
+ throw new PublishRejected("rejected", "conflict: stale prev");
+ });
+ render(
+ "shared"}
+ openConversation={() => {}}
+ onSaved={() => {}}
+ />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Show their version" }),
+ );
+ expect(screen.getByLabelText("Title")).toHaveValue("Their title");
+ expect(screen.queryByRole("alert")).toBeNull();
+});
+
+it("links the current chat only once it may be linked", async () => {
+ const { session, signed } = setup(async () => "");
+ const readyToLink = vi
+ .fn<(id: string) => Promise<"shared" | "cancelled" | "unavailable">>()
+ .mockResolvedValueOnce("cancelled")
+ .mockResolvedValueOnce("shared");
+ const onSaved = vi.fn();
+ render(
+ {}}
+ onSaved={onSaved}
+ />,
+ );
+ const link = screen.getByRole("button", { name: "Link this chat" });
+ fireEvent.click(link);
+ await vi.waitFor(() => expect(readyToLink).toHaveBeenCalledTimes(1));
+ expect(signed).toHaveLength(0);
+ fireEvent.click(link);
+ await vi.waitFor(() => expect(onSaved).toHaveBeenCalled());
+ expect(onSaved.mock.calls[0]?.[0].links).toEqual([chat]);
+});
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
new file mode 100644
index 0000000000..9ff35d18b5
--- /dev/null
+++ b/src/bundled/tasks/TaskView.tsx
@@ -0,0 +1,513 @@
+import { type ReactNode, useId, useRef, useState } from "react";
+import type { RelaySession } from "../../features/relay/session";
+import { useChannelReference } from "../../features/conversation/channel-reference";
+import { DOCUMENT_PROFILE } from "../../features/markdown/document-profile";
+import {
+ MarkdownDocument,
+ sharedComponents,
+} from "../../features/markdown/MarkdownDocument";
+import { AttachmentImage } from "../../features/messages/AttachmentImage";
+import { useIdentityNames } from "../../features/identity-names/react";
+import { formatPublicKey } from "../../shared/identity/public-key";
+import { relativeTimestamp } from "../../shared/relative-timestamp";
+import { Button } from "../../shared/design-system/ui/Button";
+import { Field } from "../../shared/design-system/ui/Field";
+import { InlineHeader } from "../../shared/design-system/ui/Header";
+import { IconButton } from "../../shared/design-system/ui/IconButton";
+import { Input } from "../../shared/design-system/ui/Input";
+import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
+import { Select } from "../../shared/design-system/ui/Select";
+import { Textarea } from "../../shared/design-system/ui/Textarea";
+import { useToastNotification } from "../../shared/design-system/ui/Toast";
+import {
+ ChatCircleIcon,
+ HashIcon,
+ ImageIcon,
+ LinkIcon,
+ LockIcon,
+ XIcon,
+} from "../../shared/design-system/icons/index";
+import {
+ statuses,
+ statusLabels,
+ type Task,
+ type TaskFields,
+ type TaskImage,
+ type TaskStatus,
+} from "./model";
+import { StatusIcon } from "./StatusIcon";
+import { saveTask } from "./store";
+import type { ChatShareOutcome } from "../../features/solo/share-requests";
+import styles from "./Tasks.module.css";
+
+const empty: TaskFields = {
+ title: "",
+ description: "",
+ status: "open",
+ images: [],
+ links: [],
+};
+const fieldsOf = (task: Task): TaskFields => ({
+ title: task.title,
+ description: task.description,
+ status: task.status,
+ images: task.images,
+ links: task.links,
+});
+
+export type TaskViewProps = {
+ session: RelaySession;
+ /** The tasks channel. */
+ channel: string;
+ /** The task's current revision; undefined starts a new task. */
+ task: Task | undefined;
+ /** The conversation this view sits beside, which "Link this chat" links. */
+ currentChat?: string | undefined;
+ /** Resolves "shared" once `channelId` may be linked; a private Solo chat
+ * first asks its owner to make it View only. */
+ readyToLink(channelId: string): Promise;
+ openConversation(channelId: string): void;
+ onSaved(task: Task): void;
+ /** Conversations a new task starts linked to, already cleared to link. */
+ newLinks?: readonly string[] | undefined;
+ /** Leaves a new task without saving it. */
+ onDiscard?: (() => void) | undefined;
+};
+
+/** One task: read by default, with an explicit edit mode. Every save names the
+ * revision it started from, so a concurrent edit is reported, never lost. */
+export function TaskView(props: TaskViewProps) {
+ const { session, channel, task } = props;
+ const notify = useToastNotification();
+ const [editing, setEditing] = useState(!task);
+ const [saving, setSaving] = useState(false);
+ const save = async (fields: TaskFields, base: Task | undefined) => {
+ setSaving(true);
+ try {
+ const result = await saveTask(session, channel, fields, base);
+ if (result.status === "saved") props.onSaved(result.task);
+ return result;
+ } finally {
+ setSaving(false);
+ }
+ };
+ // Immediate changes in read mode: status and links.
+ const change = async (next: Partial) => {
+ if (!task || saving) return false;
+ try {
+ const result = await save({ ...fieldsOf(task), ...next }, task);
+ if (result.status === "saved") return true;
+ notify("Someone else changed this task. Try again.", "error");
+ } catch (reason) {
+ notify(
+ reason instanceof Error ? reason.message : "Couldn’t save the task.",
+ "error",
+ );
+ }
+ return false;
+ };
+ if (editing || !task)
+ return (
+ {
+ setEditing(false);
+ if (!saved && !task) props.onDiscard?.();
+ }}
+ />
+ );
+ const link = async (channelId: string) => {
+ const outcome = await props.readyToLink(channelId);
+ if (outcome === "shared")
+ await change({ links: [...task.links, channelId] });
+ else if (outcome === "unavailable")
+ notify("Only this chat’s owner can link it to a task.", "error");
+ };
+ const unlink = async (channelId: string) => {
+ const solo =
+ session.channels.list().channels.find((item) => item.id === channelId)
+ ?.channelType === "solo";
+ const unlinked = await change({
+ links: task.links.filter((item) => item !== channelId),
+ });
+ // Unlinking never changes access back.
+ if (unlinked && solo)
+ notify(
+ "Unlinked. The chat stays View only. Change that in the chat’s People settings.",
+ "success",
+ );
+ };
+ const linkedHere =
+ props.currentChat !== undefined && task.links.includes(props.currentChat);
+ return (
+
+
+
{task.title}
+
+
+
+ }
+ disabled={saving}
+ groups={[
+ {
+ label: "Status",
+ options: statuses.map((status) => ({
+ value: status,
+ label: statusLabels[status],
+ leading: ,
+ })),
+ },
+ ]}
+ onValueChange={(value) =>
+ void change({ status: value as TaskStatus })
+ }
+ />
+ setEditing(true)} disabled={saving}>
+ Edit
+
+
+ {task.description.trim() ? (
+
+ ) : (
+ No description.
+ )}
+ {task.images.length > 0 && (
+
+ )}
+
+
+ {task.links.length ? (
+
+ {task.links.map((channelId) => (
+
+ props.openConversation(channelId)}
+ />
+ }
+ disabled={saving}
+ onClick={() => void unlink(channelId)}
+ />
+
+ ))}
+
+ ) : (
+
+ No conversations are linked yet.
+
+ )}
+ {props.currentChat && !linkedHere ? (
+
+ void link(props.currentChat as string)}
+ >
+
+ Link this chat
+
+
+ ) : null}
+
+
+ );
+}
+
+function TaskByline({ session, task }: { session: RelaySession; task: Task }) {
+ const name = useIdentityNames(session.names);
+ const label = (pubkey: string) =>
+ pubkey === session.viewer
+ ? "you"
+ : name(
+ pubkey,
+ session.profiles.snapshot().get(pubkey)?.name ??
+ formatPublicKey(pubkey) ??
+ "someone",
+ );
+ return (
+
+ Created by {label(task.author)} · Updated{" "}
+ {relativeTimestamp(task.updatedAt * 1000)} by {label(task.editor)}
+
+ );
+}
+
+function TaskImages({
+ session,
+ images,
+ remove,
+}: {
+ session: RelaySession;
+ images: readonly TaskImage[];
+ remove?: ((image: TaskImage) => void) | undefined;
+}) {
+ return (
+
+ {images.map((image) => {
+ const [width, height] = image.dim?.split("x").map(Number) ?? [];
+ return (
+
+
+ {remove ? (
+ }
+ onClick={() => remove(image)}
+ />
+ ) : null}
+
+ );
+ })}
+
+ );
+}
+
+/** A linked conversation as the viewer may see it: its name when readable,
+ * "Private channel" with no name when not. */
+function LinkedConversation({
+ session,
+ channelId,
+ open,
+}: {
+ session: RelaySession;
+ channelId: string;
+ open(): void;
+}) {
+ const reference = useChannelReference(session.channels, channelId);
+ let icon: ReactNode = ;
+ let label = "Loading…";
+ let trailing: string | undefined;
+ if (reference.state === "found") {
+ const solo = reference.channelType === "solo";
+ icon = solo ? (
+
+ ) : (
+
+ );
+ label = reference.name || (solo ? "Solo chat" : "Channel");
+ trailing = solo ? "Solo chat" : "Channel";
+ } else if (reference.state === "withheld") {
+ icon = ;
+ label = "Private channel";
+ trailing = "No access";
+ }
+ const readable = reference.state === "found" && reference.readable !== false;
+ return (
+
+ );
+}
+
+function TaskEditor({
+ session,
+ task,
+ newLinks,
+ saving,
+ save,
+ onDone,
+}: TaskViewProps & {
+ saving: boolean;
+ save(fields: TaskFields, base: Task | undefined): ReturnType;
+ onDone(saved: boolean): void;
+}) {
+ const id = useId();
+ const [draft, setDraft] = useState(
+ task ? fieldsOf(task) : { ...empty, links: newLinks ?? [] },
+ );
+ // The revision this draft builds on; a conflict moves it to theirs.
+ const [base, setBase] = useState(task);
+ const [conflict, setConflict] = useState<{ theirs?: Task | undefined }>();
+ const [error, setError] = useState("");
+ const [uploading, setUploading] = useState(false);
+ const files = useRef(null);
+ const update = (next: Partial) =>
+ setDraft((current) => ({ ...current, ...next }));
+ const submit = async () => {
+ setError("");
+ try {
+ const result = await save(draft, base);
+ if (result.status === "saved") onDone(true);
+ else {
+ // Keep the person's text; the next Save is a deliberate overwrite.
+ setConflict({ theirs: result.current });
+ if (result.current) setBase(result.current);
+ }
+ } catch (reason) {
+ setError(
+ reason instanceof Error ? reason.message : "Couldn’t save the task.",
+ );
+ }
+ };
+ const upload = async (list: FileList | null) => {
+ // Media access is community-wide; the tasks channel's roster need not
+ // include the viewer, and saving the task is the guarded write.
+ const uploadImage = session.attachments?.uploadForNewChat;
+ const chosen = [...(list ?? [])].filter((file) =>
+ file.type.startsWith("image/"),
+ );
+ if (!chosen.length) return;
+ if (!uploadImage) {
+ setError("Images can’t be uploaded in this community.");
+ return;
+ }
+ setUploading(true);
+ setError("");
+ try {
+ const uploaded = await Promise.all(
+ chosen.map((file) => uploadImage(file, AbortSignal.timeout(120_000))),
+ );
+ setDraft((current) => ({
+ ...current,
+ images: [
+ ...current.images,
+ ...uploaded.map((item) => ({
+ url: item.url,
+ type: item.type,
+ ...(item.dim ? { dim: item.dim } : {}),
+ })),
+ ],
+ }));
+ } catch {
+ setError("Couldn’t upload the image. Try again.");
+ } finally {
+ setUploading(false);
+ if (files.current) files.current.value = "";
+ }
+ };
+ const busy = saving || uploading;
+ return (
+
+ );
+}
diff --git a/src/bundled/tasks/Tasks.module.css b/src/bundled/tasks/Tasks.module.css
new file mode 100644
index 0000000000..6d0c729d20
--- /dev/null
+++ b/src/bundled/tasks/Tasks.module.css
@@ -0,0 +1,145 @@
+.page {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+}
+.body {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-4);
+ padding: var(--space-4);
+}
+
+/* List beside the open task; a narrow pane shows one at a time. */
+.board {
+ container: tasks-board / inline-size;
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: minmax(0, 1fr);
+}
+.board[data-detail] {
+ grid-template-columns: minmax(16rem, 22rem) minmax(0, 1fr);
+}
+.list,
+.detail {
+ min-width: 0;
+ min-height: 0;
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ padding: var(--space-4);
+}
+.detail {
+ border-inline-start: 1px solid var(--border-standard);
+}
+.back {
+ display: none;
+}
+@container tasks-board (max-width: 40rem) {
+ .board[data-detail] {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ .board[data-detail] > .list {
+ display: none;
+ }
+ .detail {
+ border-inline-start: 0;
+ }
+ .back {
+ display: block;
+ }
+}
+
+.toolbar,
+.actionRow {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2);
+}
+.spacer {
+ flex: 1;
+}
+.rows {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+.linkRow {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ min-width: 0;
+}
+.linkRow > :first-child {
+ flex: 1;
+ min-width: 0;
+}
+
+/* One task, read or edited. */
+.task {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-5);
+ min-width: 0;
+}
+.taskHeading {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ min-width: 0;
+}
+.taskHeading h2 {
+ margin: 0;
+ overflow-wrap: anywhere;
+}
+.taskActions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2);
+}
+.section {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ min-width: 0;
+}
+.images {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+.image {
+ position: relative;
+ max-width: 100%;
+}
+
+/* In the flow of the form, so nothing above it can cover it. */
+.notice {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-2) var(--space-3);
+ padding: var(--space-3);
+ border: 1px solid var(--border-warning);
+ border-radius: var(--radius-card);
+ background: var(--affordance-warning);
+ color: var(--text-warning);
+}
+.notice > p {
+ flex: 1 1 12rem;
+ margin: 0;
+}
diff --git a/src/bundled/tasks/TasksGate.tsx b/src/bundled/tasks/TasksGate.tsx
new file mode 100644
index 0000000000..88fd587c13
--- /dev/null
+++ b/src/bundled/tasks/TasksGate.tsx
@@ -0,0 +1,66 @@
+import type { ReactNode } from "react";
+import type { RelaySession } from "../../features/relay/session";
+import { ClipboardCheckIcon } from "../../shared/design-system/icons/index";
+import { Button } from "../../shared/design-system/ui/Button";
+import { EmptyState } from "../../shared/design-system/ui/EmptyState";
+import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion";
+import { useTasksChannel } from "./react";
+import styles from "./Tasks.module.css";
+
+/** Finds the community's tasks channel before showing `children`, or explains
+ * why there is none yet. The page and the panel share it. */
+export function TasksGate({
+ session,
+ children,
+}: {
+ session: RelaySession;
+ children(channel: string): ReactNode;
+}) {
+ const channel = useTasksChannel(session);
+ if (channel.status === "found") return children(channel.channelId);
+ if (channel.status === "missing")
+ return (
+
+ }
+ title="Tasks isn’t set up yet"
+ description={
+ channel.canSetUp
+ ? "Set up Tasks once for everyone in this community. You’ll own the hidden channel that holds them."
+ : "Ask a community admin to set up Tasks."
+ }
+ action={
+ channel.canSetUp ? (
+
+ Set up Tasks
+
+ ) : undefined
+ }
+ />
+
+ );
+ return (
+
+
+ {channel.error}
+
+ Try again
+
+
+ ) : undefined
+ }
+ >
+ {null}
+
+
+ );
+}
diff --git a/src/bundled/tasks/TasksPage.tsx b/src/bundled/tasks/TasksPage.tsx
new file mode 100644
index 0000000000..899870b50d
--- /dev/null
+++ b/src/bundled/tasks/TasksPage.tsx
@@ -0,0 +1,331 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import type { Navigation } from "../../features/navigation/controller";
+import type { NavigationScope } from "../../features/navigation/targets";
+import type { PageProps } from "../../features/pages/service";
+import {
+ useChannelRoster,
+ useRelayConnection,
+} from "../../features/relay/react";
+import type { RelayData } from "../../features/relay/service";
+import type { RelaySession } from "../../features/relay/session";
+import type { ChatSharing } from "../../features/solo/share-requests";
+import {
+ ArrowLeftIcon,
+ CaretDownIcon,
+ ClipboardCheckIcon,
+ PlusIcon,
+} from "../../shared/design-system/icons/index";
+import { Button } from "../../shared/design-system/ui/Button";
+import { EmptyState } from "../../shared/design-system/ui/EmptyState";
+import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion";
+import {
+ MenuGroup,
+ MenuGroupLabel,
+ MenuPopup,
+ MenuRadioGroup,
+ MenuRadioItem,
+ MenuRoot,
+ MenuSeparator,
+ MenuTrigger,
+} from "../../shared/design-system/ui/Menu";
+import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
+import { Panel } from "../../shared/design-system/ui/Panel";
+import {
+ PanelHeader,
+ PanelHeaderLabel,
+} from "../../shared/design-system/ui/PanelHeader";
+import { readyToLink } from "./linking";
+import { filterTasks, type TaskFilter } from "./model";
+import { useTasksWithSaved } from "./react";
+import { StatusIcon } from "./StatusIcon";
+import { TasksGate } from "./TasksGate";
+import { TaskView } from "./TaskView";
+import styles from "./Tasks.module.css";
+
+type TasksPageProps = Pick & {
+ relay: RelayData;
+ navigator: Navigation;
+ sharing: ChatSharing | undefined;
+};
+
+export function TasksPage({
+ relay,
+ navigation,
+ navigator,
+ sharing,
+}: TasksPageProps) {
+ const connection = useRelayConnection(relay);
+ const request = useMemo(
+ () => navigation?.forSession(relay, connection),
+ [navigation, relay, connection],
+ );
+ const scope = useMemo(
+ () =>
+ connection.viewer && connection.scope
+ ? {
+ viewer: connection.viewer,
+ communityOrigin: connection.scope.slice(
+ 0,
+ -(connection.viewer.length + 1),
+ ),
+ }
+ : undefined,
+ [connection.viewer, connection.scope],
+ );
+ // A page opened without a community takes the one it connected to.
+ useEffect(() => {
+ if (
+ request?.target.kind !== "page" ||
+ request.target.scope !== undefined ||
+ connection.status !== "ready" ||
+ !scope
+ )
+ return;
+ request.resolve({ ...request.target, scope });
+ }, [request, connection.status, scope]);
+ return (
+
+
+
}
+ />
+ }
+ />
+ {connection.status === "ready" && scope ? (
+
+ {(channel) => (
+
+ readyToLink(connection.session, sharing, channelId)
+ }
+ openConversation={(channelId) =>
+ void navigator.open({
+ version: 1,
+ kind: "conversation",
+ scope,
+ channelId,
+ })
+ }
+ />
+ )}
+
+ ) : (
+
+
+ {connection.status === "connecting"
+ ? "Connecting to your community…"
+ : "Connect to a community to see its tasks."}
+
+ {connection.status === "error" ? (
+ <>
+
+ {connection.error}
+
+
relay.tryAgain()}>
+ Retry connection
+
+ >
+ ) : null}
+
+ )}
+
+
+ );
+}
+
+const statusFilterLabels = { open: "Open", done: "Done" } as const;
+const allOpen: TaskFilter = { status: "open", mine: false };
+
+/** Tasks I'm in: conversations whose signed roster includes me. */
+function useMyChannels(session: RelaySession) {
+ const { channels } = useChannelRoster(session.channels);
+ return useMemo(
+ () =>
+ new Set(
+ channels
+ .filter((item) => item.viewerRole && item.viewerRole !== "guest")
+ .map((item) => item.id),
+ ),
+ [channels],
+ );
+}
+
+function TaskBoard({
+ session,
+ channel,
+ readyToLink,
+ openConversation,
+}: {
+ session: RelaySession;
+ channel: string;
+ readyToLink: TaskViewLink;
+ openConversation(channelId: string): void;
+}) {
+ const state = useTasksWithSaved(session, channel);
+ const mine = useMyChannels(session);
+ const [filter, setFilter] = useState(allOpen);
+ const [selected, setSelected] = useState();
+ const shown = filterTasks(state.tasks, filter, session.viewer ?? "", mine);
+ const task =
+ selected === "new"
+ ? undefined
+ : state.tasks.find((item) => item.id === selected);
+ const detail = selected === "new" || task !== undefined;
+ const back = useCallback(() => setSelected(undefined), []);
+ return (
+
+
+
+
+
+ {statusFilterLabels[filter.status]}
+ {filter.mine ? " · Mine" : ""}
+
+
+ }
+ />
+
+
+ Status
+
+ setFilter((current) => ({
+ ...current,
+ status: value === "done" ? "done" : "open",
+ }))
+ }
+ >
+
+ Open
+
+
+ Done
+
+
+
+
+
+ Show
+
+ setFilter((current) => ({
+ ...current,
+ mine: value === "mine",
+ }))
+ }
+ >
+
+ Everyone’s
+
+
+ Mine
+
+
+
+
+
+
+
setSelected("new")}
+ >
+
+ New task
+
+
+
+ {state.error}
+
+ ) : undefined
+ }
+ >
+ {state.status === "loading" ? null : shown.length ? (
+
+ {shown.map((item) => (
+
+ }
+ label={item.title || "Untitled task"}
+ trailing={
+ item.links.length
+ ? `${item.links.length} linked`
+ : undefined
+ }
+ selected={item.id === selected}
+ onClick={() => setSelected(item.id)}
+ />
+
+ ))}
+
+ ) : (
+ }
+ title={
+ state.tasks.length
+ ? "No tasks match this filter"
+ : "No tasks yet"
+ }
+ description={
+ state.tasks.length
+ ? "Change the filter to see other tasks."
+ : "A task holds the context for a piece of work and the conversations about it. You can also ask your agent to make one."
+ }
+ action={
+ state.tasks.length ? (
+ setFilter(allOpen)}>
+ Show all open tasks
+
+ ) : (
+ setSelected("new")}>New task
+ )
+ }
+ />
+ )}
+
+
+ {detail ? (
+
+
+ {
+ state.setSaved(next);
+ setSelected(next.id);
+ }}
+ onDiscard={back}
+ />
+
+ ) : null}
+
+ );
+}
+
+type TaskViewLink = Parameters[0]["readyToLink"];
diff --git a/src/bundled/tasks/TasksPanel.tsx b/src/bundled/tasks/TasksPanel.tsx
new file mode 100644
index 0000000000..19ad2aab8f
--- /dev/null
+++ b/src/bundled/tasks/TasksPanel.tsx
@@ -0,0 +1,180 @@
+import { useState } from "react";
+import type { RelaySession } from "../../features/relay/session";
+import {
+ ArrowLeftIcon,
+ LinkIcon,
+ ClipboardCheckIcon,
+ PlusIcon,
+} from "../../shared/design-system/icons/index";
+import { Button } from "../../shared/design-system/ui/Button";
+import { EmptyState } from "../../shared/design-system/ui/EmptyState";
+import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion";
+import {
+ MenuItem,
+ MenuPopup,
+ MenuRoot,
+ MenuTrigger,
+} from "../../shared/design-system/ui/Menu";
+import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
+import { useToastNotification } from "../../shared/design-system/ui/Toast";
+import { isOpenStatus, type Task } from "./model";
+import { useTasksWithSaved } from "./react";
+import { saveTask } from "./store";
+import { StatusIcon } from "./StatusIcon";
+import { TaskView, type TaskViewProps } from "./TaskView";
+import styles from "./Tasks.module.css";
+
+/** Open tasks the "Link to a task" menu offers, newest first. */
+const LINK_CHOICES = 20;
+
+/** Tasks beside one conversation: those linked to it, and ways to make or
+ * link one from here. A task opens in place, with Back. */
+export function TasksPanel({
+ session,
+ channel,
+ chat,
+ readyToLink,
+ openConversation,
+}: {
+ session: RelaySession;
+ /** The tasks channel. */
+ channel: string;
+ /** The conversation this panel sits beside. */
+ chat: string;
+} & Pick) {
+ const state = useTasksWithSaved(session, channel);
+ const notify = useToastNotification();
+ // "new" carries the links a new task starts with, cleared to link.
+ const [open, setOpen] = useState();
+ const [linking, setLinking] = useState(false);
+ const linked = state.tasks
+ .filter((task) => task.links.includes(chat))
+ .sort((a, b) => b.updatedAt - a.updatedAt);
+ const choices = state.tasks
+ .filter((task) => isOpenStatus(task.status) && !task.links.includes(chat))
+ .sort((a, b) => b.updatedAt - a.updatedAt)
+ .slice(0, LINK_CHOICES);
+ const cleared = async () => {
+ const outcome = await readyToLink(chat);
+ if (outcome === "unavailable")
+ notify("Only this chat’s owner can link it to a task.", "error");
+ return outcome === "shared";
+ };
+ const linkTo = async (task: Task) => {
+ if (linking) return;
+ setLinking(true);
+ try {
+ if (!(await cleared())) return;
+ const result = await saveTask(
+ session,
+ channel,
+ { ...task, links: [...task.links, chat] },
+ task,
+ );
+ if (result.status === "saved") state.setSaved(result.task);
+ else notify("Someone else changed this task. Try again.", "error");
+ } catch (reason) {
+ notify(
+ reason instanceof Error ? reason.message : "Couldn’t link the task.",
+ "error",
+ );
+ } finally {
+ setLinking(false);
+ }
+ };
+ const task =
+ typeof open === "string"
+ ? state.tasks.find((item) => item.id === open)
+ : undefined;
+ if (open && (typeof open === "object" || task))
+ return (
+
+
+
setOpen(undefined)}>
+
+ Back
+
+
+
{
+ state.setSaved(next);
+ setOpen(next.id);
+ }}
+ onDiscard={() => setOpen(undefined)}
+ />
+
+ );
+ return (
+
+
+
{
+ if (await cleared()) setOpen({ newLinks: [chat] });
+ }}
+ >
+
+ New task from this chat
+
+
+
+
+ Link to a task
+
+ }
+ />
+
+ {choices.map((item) => (
+ void linkTo(item)}>
+ {item.title || "Untitled task"}
+
+ ))}
+
+
+
+
+ {state.error}
+
+ ) : undefined
+ }
+ >
+ {state.status === "loading" ? null : linked.length ? (
+
+ {linked.map((item) => (
+
+ }
+ label={item.title || "Untitled task"}
+ onClick={() => setOpen(item.id)}
+ />
+
+ ))}
+
+ ) : (
+ }
+ title="No tasks linked here"
+ description="Make a task from this chat, or link it to one that already exists."
+ />
+ )}
+
+
+ );
+}
diff --git a/src/bundled/tasks/index.tsx b/src/bundled/tasks/index.tsx
new file mode 100644
index 0000000000..d20057a2c1
--- /dev/null
+++ b/src/bundled/tasks/index.tsx
@@ -0,0 +1,123 @@
+import { useSyncExternalStore } from "react";
+import type {
+ ChannelLauncherProps,
+ PanelProps,
+} from "../../features/panels/service";
+import type { RelaySnapshot } from "../../features/relay/service";
+import type { ChatSharing } from "../../features/solo/share-requests";
+import type { PluginModule } from "../../plugins/api";
+import { ClipboardCheckIcon } from "../../shared/design-system/icons/index";
+import { IconButton } from "../../shared/design-system/ui/IconButton";
+import { readyToLink } from "./linking";
+import { TasksGate } from "./TasksGate";
+import { TasksPage } from "./TasksPage";
+import { TasksPanel } from "./TasksPanel";
+import { addTaskTools } from "./tools";
+
+export const inject = ["pages", "panels", "relay", "navigation", "agents"];
+
+const scopeOf = (state: RelaySnapshot) =>
+ state.viewer && state.scope
+ ? {
+ viewer: state.viewer,
+ communityOrigin: state.scope.slice(0, -(state.viewer.length + 1)),
+ }
+ : undefined;
+
+export const apply: PluginModule["apply"] = (ctx) => {
+ let active = true;
+ ctx.effect(() => () => {
+ active = false;
+ });
+ // Read when used, so a host without it degrades to "can't link Solo chats".
+ const sharing = () =>
+ ctx.reflect.get("chatSharing") as ChatSharing | undefined;
+
+ ctx.pages.register({
+ id: "tasks",
+ title: "Tasks",
+ layout: "workspace",
+ primary: true,
+ placement: "dock",
+ component: (props) => (
+
+ ),
+ });
+
+ function Launcher({
+ context,
+ toggle,
+ pressed,
+ available,
+ }: ChannelLauncherProps) {
+ return (
+ }
+ aria-label="Toggle tasks"
+ title="Tasks"
+ aria-expanded={pressed}
+ onClick={(event) => {
+ event.currentTarget.focus();
+ if (active && available()) toggle(context.channelId);
+ }}
+ />
+ );
+ }
+ function Panel({ channelContext }: PanelProps) {
+ const state = useSyncExternalStore(ctx.relay.subscribe, ctx.relay.snapshot);
+ const scope = scopeOf(state);
+ if (
+ !channelContext ||
+ !scope ||
+ state.status !== "ready" ||
+ state.scope !== channelContext.scope
+ )
+ return (
+ Connect to this conversation to see its tasks.
+ );
+ const session = state.session;
+ return (
+
+ {(channel) => (
+
+ readyToLink(session, sharing(), channelId)
+ }
+ openConversation={(channelId) =>
+ void ctx.navigation.open({
+ version: 1,
+ kind: "conversation",
+ scope,
+ channelId,
+ })
+ }
+ />
+ )}
+
+ );
+ }
+ ctx.panels.register({
+ id: "tasks",
+ title: "Tasks",
+ matches: () => false,
+ channelLauncher: Launcher,
+ channelPlacement: "side",
+ component: Panel,
+ });
+
+ addTaskTools(ctx.agents, sharing);
+};
diff --git a/src/bundled/tasks/linking.test.ts b/src/bundled/tasks/linking.test.ts
new file mode 100644
index 0000000000..71667682e2
--- /dev/null
+++ b/src/bundled/tasks/linking.test.ts
@@ -0,0 +1,26 @@
+import { expect, it, vi } from "vitest";
+import type { ChannelSummary } from "../../features/relay/contracts";
+import type { RelaySession } from "../../features/relay/session";
+import { readyToLink } from "./linking";
+
+const session = (channels: Partial[]) =>
+ ({ channels: { list: () => ({ channels }) } }) as unknown as RelaySession;
+
+it("asks the owner only before linking a Solo chat that isn't public", async () => {
+ const requestShare = vi.fn(async () => "cancelled" as const);
+ const sharing = { requestShare };
+ const relay = session([
+ { id: "solo", channelType: "solo", visibility: "private" },
+ { id: "shared", channelType: "solo", visibility: "public" },
+ { id: "unknown", channelType: "solo" },
+ { id: "channel", channelType: "stream", visibility: "private" },
+ ]);
+ expect(await readyToLink(relay, sharing, "channel")).toBe("shared");
+ expect(await readyToLink(relay, sharing, "shared")).toBe("shared");
+ expect(await readyToLink(relay, sharing, "elsewhere")).toBe("shared");
+ expect(requestShare).not.toHaveBeenCalled();
+ expect(await readyToLink(relay, sharing, "solo")).toBe("cancelled");
+ expect(await readyToLink(relay, sharing, "unknown")).toBe("cancelled");
+ expect(requestShare).toHaveBeenCalledTimes(2);
+ expect(await readyToLink(relay, undefined, "solo")).toBe("unavailable");
+});
diff --git a/src/bundled/tasks/linking.ts b/src/bundled/tasks/linking.ts
new file mode 100644
index 0000000000..48bc065d7c
--- /dev/null
+++ b/src/bundled/tasks/linking.ts
@@ -0,0 +1,23 @@
+// Linking records a conversation's id on a task; it never adds anyone to the
+// conversation. Only a private Solo chat needs the owner's consent first: its
+// owner makes it View only through the app's "Share this chat?" confirmation.
+import type { RelaySession } from "../../features/relay/session";
+import type {
+ ChatShareOutcome,
+ ChatSharing,
+} from "../../features/solo/share-requests";
+
+/** Whether `channelId` may be linked now, asking to share it when needed. */
+export async function readyToLink(
+ session: RelaySession,
+ sharing: ChatSharing | undefined,
+ channelId: string,
+): Promise {
+ const channel = session.channels
+ .list()
+ .channels.find((item) => item.id === channelId);
+ // Unknown visibility is not public: ask, and let the app's check decide.
+ if (channel?.channelType !== "solo" || channel.visibility === "public")
+ return "shared";
+ return sharing ? sharing.requestShare(session, channelId) : "unavailable";
+}
diff --git a/src/bundled/tasks/manifest.json b/src/bundled/tasks/manifest.json
new file mode 100644
index 0000000000..d25e067d87
--- /dev/null
+++ b/src/bundled/tasks/manifest.json
@@ -0,0 +1,7 @@
+{
+ "id": "buzz.tasks",
+ "name": "Tasks",
+ "apiVersion": 1,
+ "description": "Shared tasks that hold the context for a piece of work and link the conversations about it.",
+ "discovery": { "category": "productivity", "tags": ["tasks"] }
+}
diff --git a/src/bundled/tasks/model.test.ts b/src/bundled/tasks/model.test.ts
new file mode 100644
index 0000000000..17cdfbdf81
--- /dev/null
+++ b/src/bundled/tasks/model.test.ts
@@ -0,0 +1,144 @@
+import { expect, it } from "vitest";
+import {
+ checkedFields,
+ filterTasks,
+ type Task,
+ TASK_TYPE,
+ taskContent,
+ taskOf,
+} from "./model";
+
+const author = "a".repeat(64);
+const editor = "b".repeat(64);
+const chat = "11111111-1111-4111-8111-111111111111";
+const other = "22222222-2222-4222-8222-222222222222";
+
+const revision = (content: unknown, tags: string[][] = []) => ({
+ id: "e".repeat(64),
+ pubkey: editor,
+ sig: "",
+ created_at: 10,
+ kind: 45010,
+ content: typeof content === "string" ? content : JSON.stringify(content),
+ tags: [
+ ["ar", "1"],
+ ["d", "task-1"],
+ ["h", "tasks"],
+ ["type", TASK_TYPE],
+ ["title", "Fix the header"],
+ ["op", "update"],
+ ...tags,
+ ],
+});
+
+it("reads a revision as the task it snapshots", () => {
+ const task = taskOf(
+ revision({
+ version: 1,
+ author,
+ description: "It clips.",
+ status: "in_progress",
+ images: [
+ { url: "https://example.org/a.png", type: "image/png", dim: "10x20" },
+ ],
+ links: [chat, chat, other],
+ }),
+ );
+ expect(task).toEqual({
+ id: "task-1",
+ title: "Fix the header",
+ description: "It clips.",
+ status: "in_progress",
+ images: [
+ { url: "https://example.org/a.png", type: "image/png", dim: "10x20" },
+ ],
+ links: [chat, other],
+ author,
+ revision: "e".repeat(64),
+ editor,
+ updatedAt: 10,
+ });
+});
+
+it("drops what an untrusted record can't safely show", () => {
+ const task = taskOf(
+ revision({
+ author: "not a key",
+ status: "deleted",
+ images: [
+ { url: "http://example.org/a.png" },
+ { url: "javascript:alert(1)" },
+ { url: "https://example.org/b.png", type: "text/html", dim: "big" },
+ ],
+ links: ["general", 7, chat],
+ }),
+ );
+ expect(task?.author).toBe(editor);
+ expect(task?.status).toBe("open");
+ expect(task?.images).toEqual([{ url: "https://example.org/b.png" }]);
+ expect(task?.links).toEqual([chat]);
+ expect(taskOf(revision("not json"))).toBeUndefined();
+ expect(taskOf(revision([]))).toBeUndefined();
+ expect(
+ taskOf({
+ ...revision({}),
+ tags: [
+ ["d", "x"],
+ ["type", "other"],
+ ],
+ }),
+ ).toBeUndefined();
+});
+
+it("checks fields before saving, with reasons people can act on", () => {
+ const fields = {
+ title: " Fix the header ",
+ description: "",
+ status: "open" as const,
+ images: [],
+ links: [chat, chat],
+ };
+ expect(checkedFields(fields)).toEqual({
+ ...fields,
+ title: "Fix the header",
+ links: [chat],
+ });
+ expect(() => checkedFields({ ...fields, title: " " })).toThrow(
+ "Give the task a title.",
+ );
+ expect(() => checkedFields({ ...fields, title: "x".repeat(201) })).toThrow(
+ "under 200",
+ );
+ expect(JSON.parse(taskContent(fields, author))).toEqual({
+ version: 1,
+ author,
+ description: "",
+ status: "open",
+ images: [],
+ links: [chat, chat],
+ });
+});
+
+it("filters by status and by what's mine, newest first", () => {
+ const base = taskOf(revision({ author })) as Task;
+ const task = (id: string, extra: Partial): Task => ({
+ ...base,
+ id,
+ ...extra,
+ });
+ const tasks = [
+ task("mine", { updatedAt: 1 }),
+ task("linked", { author: editor, links: [chat], updatedAt: 3 }),
+ task("theirs", { author: editor, updatedAt: 2 }),
+ task("done", { status: "wont_do", updatedAt: 4 }),
+ ];
+ const ids = (filter: Parameters[1]) =>
+ filterTasks(tasks, filter, author, new Set([chat])).map((item) => item.id);
+ expect(ids({ status: "open", mine: false })).toEqual([
+ "linked",
+ "theirs",
+ "mine",
+ ]);
+ expect(ids({ status: "open", mine: true })).toEqual(["linked", "mine"]);
+ expect(ids({ status: "done", mine: false })).toEqual(["done"]);
+});
diff --git a/src/bundled/tasks/model.ts b/src/bundled/tasks/model.ts
new file mode 100644
index 0000000000..b18ad6b51d
--- /dev/null
+++ b/src/bundled/tasks/model.ts
@@ -0,0 +1,172 @@
+// A task is one NIP-AR artifact (kind 45010) of type `buzz.task` in the
+// community's tasks channel. Its content is the complete snapshot; the relay
+// keeps the revision history and refuses an edit whose `prev` is stale.
+import { ARTIFACT_KIND } from "../../features/agents/agent-config-artifacts";
+import type { EventData } from "../../features/relay/events";
+
+export const TASK_TYPE = "buzz.task";
+const CONTENT_VERSION = 1;
+
+export const statuses = ["open", "in_progress", "done", "wont_do"] as const;
+export type TaskStatus = (typeof statuses)[number];
+export const statusLabels: Readonly> = {
+ open: "Open",
+ in_progress: "In progress",
+ done: "Done",
+ wont_do: "Won’t do",
+};
+/** Open includes In progress; Done includes Won't do. */
+export const isOpenStatus = (status: TaskStatus) =>
+ status === "open" || status === "in_progress";
+
+export type TaskImage = Readonly<{
+ url: string;
+ type?: string | undefined;
+ dim?: string | undefined;
+}>;
+
+/** What people edit. Links are channel ids: linkage, never membership. */
+export type TaskFields = Readonly<{
+ title: string;
+ description: string;
+ status: TaskStatus;
+ images: readonly TaskImage[];
+ links: readonly string[];
+}>;
+
+export type Task = TaskFields &
+ Readonly<{
+ /** The artifact's `d`. */
+ id: string;
+ /** Who created it, as its creator's client recorded. */
+ author: string;
+ /** The current revision: its id is the next edit's `prev`. */
+ revision: string;
+ /** Who signed the current revision, and when. */
+ editor: string;
+ updatedAt: number;
+ }>;
+
+const MAX_TITLE = 200;
+const MAX_IMAGES = 32;
+const MAX_LINKS = 64;
+const HEX64 = /^[0-9a-f]{64}$/;
+const CHANNEL =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+const tag = (event: EventData, name: string) =>
+ event.tags.find((entry) => entry[0] === name)?.[1];
+
+const text = (value: unknown) => (typeof value === "string" ? value : "");
+
+/** Only HTTPS links render; anything else in an untrusted record is dropped. */
+export function imageOf(value: unknown): TaskImage | undefined {
+ if (!value || typeof value !== "object") return undefined;
+ const { url, type, dim } = value as Record;
+ if (typeof url !== "string") return undefined;
+ try {
+ if (new URL(url).protocol !== "https:") return undefined;
+ } catch {
+ return undefined;
+ }
+ return {
+ url,
+ ...(typeof type === "string" && type.startsWith("image/") ? { type } : {}),
+ ...(typeof dim === "string" && /^\d{1,5}x\d{1,5}$/.test(dim)
+ ? { dim }
+ : {}),
+ };
+}
+
+export const isChannelId = (value: unknown): value is string =>
+ typeof value === "string" && CHANNEL.test(value);
+
+/** A current revision as a task, or undefined when it is not a readable one. */
+export function taskOf(event: EventData & { id: string }): Task | undefined {
+ if (event.kind !== ARTIFACT_KIND || tag(event, "type") !== TASK_TYPE)
+ return undefined;
+ const id = tag(event, "d");
+ if (!id) return undefined;
+ let content: Record;
+ try {
+ const parsed: unknown = JSON.parse(event.content);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
+ return undefined;
+ content = parsed as Record;
+ } catch {
+ return undefined;
+ }
+ const status = statuses.find((item) => item === content.status) ?? "open";
+ const author = text(content.author);
+ return {
+ id,
+ title: (tag(event, "title") ?? "").slice(0, MAX_TITLE),
+ description: text(content.description),
+ status,
+ images: (Array.isArray(content.images) ? content.images : [])
+ .flatMap((item) => imageOf(item) ?? [])
+ .slice(0, MAX_IMAGES),
+ links: [
+ ...new Set(
+ (Array.isArray(content.links) ? content.links : []).filter(isChannelId),
+ ),
+ ].slice(0, MAX_LINKS),
+ author: HEX64.test(author) ? author : event.pubkey,
+ revision: event.id,
+ editor: event.pubkey,
+ updatedAt: event.created_at,
+ };
+}
+
+/** Fields checked and trimmed for saving; throws with a person-readable reason. */
+export function checkedFields(fields: TaskFields): TaskFields {
+ const title = fields.title.trim().replace(/\s+/g, " ");
+ if (!title) throw new Error("Give the task a title.");
+ if (title.length > MAX_TITLE)
+ throw new Error(`Keep the title under ${MAX_TITLE} characters.`);
+ if (fields.images.length > MAX_IMAGES)
+ throw new Error(`A task holds up to ${MAX_IMAGES} images.`);
+ if (fields.links.length > MAX_LINKS)
+ throw new Error(`A task links up to ${MAX_LINKS} conversations.`);
+ return {
+ title,
+ description: fields.description,
+ status: fields.status,
+ images: fields.images,
+ links: [...new Set(fields.links)],
+ };
+}
+
+/** The revision's content: the complete snapshot, author preserved. */
+export const taskContent = (fields: TaskFields, author: string) =>
+ JSON.stringify({
+ version: CONTENT_VERSION,
+ author,
+ description: fields.description,
+ status: fields.status,
+ images: fields.images,
+ links: fields.links,
+ });
+
+export type TaskFilter = Readonly<{
+ status: "open" | "done";
+ mine: boolean;
+}>;
+
+/** Mine: tasks I created, or that link a conversation I'm in. */
+export function filterTasks(
+ tasks: readonly Task[],
+ filter: TaskFilter,
+ viewer: string,
+ myChannels: ReadonlySet,
+) {
+ return tasks
+ .filter(
+ (task) =>
+ isOpenStatus(task.status) === (filter.status === "open") &&
+ (!filter.mine ||
+ task.author === viewer ||
+ task.links.some((link) => myChannels.has(link))),
+ )
+ .sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));
+}
diff --git a/src/bundled/tasks/react.ts b/src/bundled/tasks/react.ts
new file mode 100644
index 0000000000..62eb91b2f2
--- /dev/null
+++ b/src/bundled/tasks/react.ts
@@ -0,0 +1,97 @@
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+ useSyncExternalStore,
+} from "react";
+import type { RelaySession } from "../../features/relay/session";
+import type { Task } from "./model";
+import { type TasksState, type TasksView, watchTasks } from "./store";
+import {
+ findTasksChannel,
+ setUpTasksChannel,
+ type TasksChannel,
+} from "./tasks-channel";
+
+const loadingState: TasksState = { status: "loading", tasks: [] };
+const loading: TasksView = {
+ snapshot: () => loadingState,
+ subscribe: () => () => {},
+ dispose: () => {},
+};
+
+/** Every current task in `channel`, live while mounted. The watch starts in
+ * an effect so each mount owns, and disposes, exactly the one it opened. */
+export function useTasks(session: RelaySession, channel: string) {
+ const [view, setView] = useState(loading);
+ useEffect(() => {
+ const next = watchTasks(session, channel);
+ setView(next);
+ return next.dispose;
+ }, [session, channel]);
+ return useSyncExternalStore(view.subscribe, view.snapshot, view.snapshot);
+}
+
+/** Tasks from the live view, with this device's last save shown until the
+ * relay's copy catches up with it. */
+export function useTasksWithSaved(session: RelaySession, channel: string) {
+ const state = useTasks(session, channel);
+ const [saved, setSaved] = useState();
+ const tasks = useMemo(() => {
+ if (!saved) return state.tasks;
+ const live = state.tasks.find((task) => task.id === saved.id);
+ return live && live.updatedAt >= saved.updatedAt
+ ? state.tasks
+ : [...state.tasks.filter((task) => task.id !== saved.id), saved];
+ }, [state.tasks, saved]);
+ return { ...state, tasks, setSaved };
+}
+
+export type TasksChannelState =
+ | Readonly<{ status: "loading" }>
+ | Readonly<{ status: "error"; error: string; retry(): void }>
+ | Readonly<{ status: "found"; channelId: string }>
+ | Readonly<{
+ status: "missing";
+ canSetUp: boolean;
+ settingUp: boolean;
+ setUp(): void;
+ }>;
+
+const message = (reason: unknown) =>
+ reason instanceof Error ? reason.message : "Couldn’t open Tasks.";
+
+/** The community's tasks channel, and the admin's one-time setup. */
+export function useTasksChannel(session: RelaySession): TasksChannelState {
+ const [attempt, setAttempt] = useState(0);
+ const [result, setResult] = useState<
+ TasksChannel | { status: "error"; error: string } | undefined
+ >();
+ const [settingUp, setSettingUp] = useState(false);
+ const retry = useCallback(() => setAttempt((count) => count + 1), []);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a retry is a new attempt.
+ useEffect(() => {
+ const controller = new AbortController();
+ setResult(undefined);
+ findTasksChannel(session, controller.signal).then(
+ (found) => !controller.signal.aborted && setResult(found),
+ (reason: unknown) =>
+ !controller.signal.aborted &&
+ setResult({ status: "error", error: message(reason) }),
+ );
+ return () => controller.abort();
+ }, [session, attempt]);
+ const setUp = useCallback(() => {
+ setSettingUp(true);
+ setUpTasksChannel(session, AbortSignal.timeout(30_000))
+ .then(setResult, (reason: unknown) =>
+ setResult({ status: "error", error: message(reason) }),
+ )
+ .finally(() => setSettingUp(false));
+ }, [session]);
+ if (!result) return { status: "loading" };
+ if (result.status === "error") return { ...result, retry };
+ if (result.status === "found") return result;
+ return { ...result, settingUp, setUp };
+}
diff --git a/src/bundled/tasks/store.test.ts b/src/bundled/tasks/store.test.ts
new file mode 100644
index 0000000000..8533bedb45
--- /dev/null
+++ b/src/bundled/tasks/store.test.ts
@@ -0,0 +1,94 @@
+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 { saveTask } from "./store";
+
+const viewer = "a".repeat(64);
+const fields: TaskFields = {
+ title: "Fix the header",
+ description: "It clips.",
+ status: "open",
+ images: [],
+ links: [],
+};
+const head = (id: string, content: object) => ({
+ id,
+ pubkey: "b".repeat(64),
+ sig: "",
+ created_at: 5,
+ kind: 45010,
+ content: JSON.stringify({ version: 1, author: viewer, ...content }),
+ tags: [
+ ["ar", "1"],
+ ["d", "task-1"],
+ ["h", "tasks"],
+ ["type", TASK_TYPE],
+ ["title", "Fix the header"],
+ ["op", "update"],
+ ],
+});
+
+function session(publish: () => Promise, heads: object[] = []) {
+ const sign = vi.fn(async (template: object) => ({
+ ...template,
+ id: "f".repeat(64),
+ pubkey: viewer,
+ sig: "",
+ }));
+ return {
+ sign,
+ session: {
+ viewer,
+ snapshotRead: vi.fn(async () => heads),
+ configArtifactWriter: { sign, publish: vi.fn(publish) },
+ } as unknown as RelaySession,
+ };
+}
+
+it("creates a task, then edits only the revision it opened", async () => {
+ const { session: relay, sign } = session(async () => "");
+ const created = await saveTask(relay, "tasks", fields, undefined);
+ expect(created.status).toBe("saved");
+ const tags = sign.mock.calls[0]?.[0] as unknown as { tags: string[][] };
+ expect(tags.tags).toContainEqual(["op", "create"]);
+ expect(tags.tags.some(([name]) => name === "prev")).toBe(false);
+ if (created.status !== "saved") return;
+ await saveTask(relay, "tasks", { ...fields, status: "done" }, created.task);
+ const update = sign.mock.calls[1]?.[0] as unknown as { tags: string[][] };
+ expect(update.tags).toContainEqual(["op", "update"]);
+ expect(update.tags).toContainEqual(["prev", created.task.revision]);
+ expect(update.tags).toContainEqual(["d", created.task.id]);
+});
+
+it("reports someone else's save as a conflict with their version", async () => {
+ const theirs = head("c".repeat(64), { description: "Theirs." });
+ const { session: relay } = session(async () => {
+ throw new PublishRejected("rejected", "conflict: stale prev");
+ }, [theirs]);
+ const base = taskOf(head("d".repeat(64), {})) as Task;
+ const result = await saveTask(relay, "tasks", fields, base);
+ expect(result).toEqual({ status: "conflict", current: taskOf(theirs) });
+});
+
+it("confirms an uncertain save from the head, else says it failed", async () => {
+ const base = taskOf(head("d".repeat(64), {})) as Task;
+ const landed = session(async () => {
+ throw new Error("socket closed");
+ }, [head("f".repeat(64), {})]);
+ expect((await saveTask(landed.session, "tasks", fields, base)).status).toBe(
+ "saved",
+ );
+ const lost = session(async () => {
+ throw new Error("socket closed");
+ }, [head("d".repeat(64), {})]);
+ await expect(saveTask(lost.session, "tasks", fields, base)).rejects.toThrow(
+ "Couldn’t save the task. Try again.",
+ );
+ const refused = session(async () => {
+ throw new PublishRejected("rejected", "restricted: not a member");
+ });
+ await expect(
+ saveTask(refused.session, "tasks", fields, base),
+ ).rejects.toThrow("You can’t edit tasks in this community.");
+});
diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts
new file mode 100644
index 0000000000..00b598a56a
--- /dev/null
+++ b/src/bundled/tasks/store.ts
@@ -0,0 +1,189 @@
+// Reading and saving tasks in one tasks channel. Reads follow the relay's
+// NIP-AR sync where it has one; saves are compare-and-set on the head the
+// editor opened, so a concurrent edit is reported, never overwritten.
+import {
+ ARTIFACT_KIND,
+ deliver,
+ readHead,
+} from "../../features/agents/agent-config-artifacts";
+import type { RelayEvent } from "../../features/relay/events";
+import type { RelaySession } from "../../features/relay/session";
+import {
+ checkedFields,
+ TASK_TYPE,
+ type Task,
+ type TaskFields,
+ taskContent,
+ taskOf,
+} from "./model";
+
+export type TasksState = Readonly<{
+ status: "loading" | "live" | "error";
+ tasks: readonly Task[];
+ error?: string | undefined;
+}>;
+
+export type TasksView = Readonly<{
+ snapshot(): TasksState;
+ subscribe(listener: () => void): () => void;
+ dispose(): void;
+}>;
+
+/** The session reader's cap on one finite read. */
+const READ_LIMIT = 500;
+
+const toTasks = (events: readonly RelayEvent[]) =>
+ events.flatMap((event) => taskOf(event) ?? []);
+
+/** Every current task in `channel`, kept current while subscribed. */
+export function watchTasks(session: RelaySession, channel: string): TasksView {
+ const listeners = new Set<() => void>();
+ let state: TasksState = { status: "loading", tasks: [] };
+ const set = (next: TasksState) => {
+ state = next;
+ for (const listener of listeners) listener();
+ };
+ const filter = {
+ artifact: "current" as const,
+ kinds: [ARTIFACT_KIND],
+ "#h": [channel],
+ "#type": [TASK_TYPE],
+ };
+ const sync = session.artifacts.sync(filter);
+ let fallback: AbortController | undefined;
+ // A relay without sync gets one finite read; saves on this device still
+ // show through `saved`.
+ const readOnce = () => {
+ if (fallback || !session.snapshotRead) {
+ if (!session.snapshotRead)
+ set({
+ status: "error",
+ tasks: [],
+ error: "Tasks aren’t available in this community.",
+ });
+ return;
+ }
+ const controller = new AbortController();
+ fallback = controller;
+ session
+ .snapshotRead([{ ...filter, limit: READ_LIMIT }], {
+ signal: controller.signal,
+ })
+ .then((events) => {
+ if (!controller.signal.aborted)
+ set({ status: "live", tasks: toTasks(events) });
+ })
+ .catch((reason: unknown) => {
+ if (!controller.signal.aborted)
+ set({
+ status: "error",
+ tasks: state.tasks,
+ error:
+ reason instanceof Error ? reason.message : "Couldn’t load tasks.",
+ });
+ });
+ };
+ const apply = () => {
+ const current = sync.snapshot();
+ switch (current.status) {
+ case "unsupported":
+ readOnce();
+ return;
+ case "live":
+ case "stale":
+ set({ status: "live", tasks: toTasks(current.events) });
+ return;
+ case "restricted":
+ case "error":
+ set({
+ status: "error",
+ tasks: toTasks(current.events),
+ error: current.error ?? "Couldn’t load tasks.",
+ });
+ return;
+ case "loading":
+ return;
+ }
+ };
+ const stop = sync.subscribe(apply);
+ apply();
+ return {
+ snapshot: () => state,
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => void listeners.delete(listener);
+ },
+ dispose() {
+ stop();
+ sync.dispose();
+ fallback?.abort();
+ listeners.clear();
+ },
+ };
+}
+
+export type SaveResult =
+ | Readonly<{ status: "saved"; task: Task }>
+ /** Someone else saved first; `current` is their version when readable. */
+ | Readonly<{ status: "conflict"; current?: Task | undefined }>;
+
+/** Creates a task (no `base`) or saves `fields` over the `base` revision. */
+export async function saveTask(
+ session: RelaySession,
+ channel: string,
+ fields: TaskFields,
+ base: Task | undefined,
+ signal: AbortSignal = AbortSignal.timeout(20_000),
+): Promise {
+ const read = session.snapshotRead;
+ const writer = session.configArtifactWriter;
+ const viewer = session.viewer;
+ if (!read || !writer || !viewer)
+ throw new Error("This community connection can’t save tasks.");
+ const checked = checkedFields(fields);
+ const event = await writer.sign(
+ {
+ kind: ARTIFACT_KIND,
+ created_at: Math.floor(Date.now() / 1000),
+ content: taskContent(checked, base?.author ?? viewer),
+ tags: [
+ ["ar", "1"],
+ ["d", base?.id ?? crypto.randomUUID()],
+ ["h", channel],
+ ["type", TASK_TYPE],
+ ["title", checked.title],
+ ["op", base ? "update" : "create"],
+ ...(base ? [["prev", base.revision]] : []),
+ ],
+ },
+ signal,
+ );
+ const delivery = await deliver(writer, event, signal);
+ if (delivery.status === "accepted") {
+ const task = taskOf(event);
+ if (!task) throw new Error("Couldn’t read the saved task.");
+ return { status: "saved", task };
+ }
+ if (delivery.status === "refused" && delivery.refusal === "conflict") {
+ const head = base
+ ? await readHead(read, channel, base.id, signal).catch(() => undefined)
+ : undefined;
+ return { status: "conflict", current: head && taskOf(head) };
+ }
+ if (delivery.status === "uncertain" && base) {
+ // The relay accepts a replay of an accepted revision, so the head shows
+ // whether this one landed.
+ const head = await readHead(read, channel, base.id, signal).catch(
+ () => undefined,
+ );
+ const task = head?.id === event.id ? taskOf(head) : undefined;
+ if (task) return { status: "saved", task };
+ }
+ throw new Error(
+ delivery.status === "refused" && delivery.refusal === "permission"
+ ? "You can’t edit tasks in this community."
+ : delivery.status === "refused" && delivery.refusal === "too-large"
+ ? "This task is too large to save. Shorten the description."
+ : "Couldn’t save the task. Try again.",
+ );
+}
diff --git a/src/bundled/tasks/tasks-channel.ts b/src/bundled/tasks/tasks-channel.ts
new file mode 100644
index 0000000000..9b58929645
--- /dev/null
+++ b/src/bundled/tasks/tasks-channel.ts
@@ -0,0 +1,96 @@
+// The community's tasks live in one open NIP-CL system channel: hidden from
+// channel lists, readable and writable by everyone in the community. Its
+// creator owns it, so only a channel a community owner or admin created
+// counts; the oldest such channel is the community's (NIP-CL "Choosing one
+// channel"), so concurrent setups converge.
+import {
+ MEMBERSHIP_KIND,
+ membersFromSnapshot,
+} from "../../features/communities/roster";
+import { compareChannelAge } from "../../features/relay/channel-labels";
+import type { ChannelSummary } from "../../features/relay/contracts";
+import type { RelaySession } from "../../features/relay/session";
+
+export const TASKS_LABEL = "buzz.tasks";
+const TASKS_CHANNEL_NAME = "Tasks";
+/** Communities have few admins; more than this is not looked through. */
+const MAX_ADMINS = 32;
+
+export type TasksChannel =
+ | Readonly<{ status: "found"; channelId: string }>
+ /** No admin has set Tasks up; `canSetUp` when the viewer may. */
+ | Readonly<{ status: "missing"; canSetUp: boolean }>;
+
+/** The community's owners and admins, from the relay-signed roster. */
+async function readAdmins(session: RelaySession, signal: AbortSignal) {
+ const author = session.relayAuthor;
+ if (!author) throw new Error("This community can’t confirm its admins.");
+ const events = await session.read(
+ [{ kinds: [MEMBERSHIP_KIND], authors: [author], limit: 1 }],
+ { fresh: true, signal },
+ );
+ const latest = [...events].sort(
+ (a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id),
+ )[0];
+ return (latest ? membersFromSnapshot(latest, author) : [])
+ .filter((member) => member.role === "owner" || member.role === "admin")
+ .map((member) => member.pubkey)
+ .slice(0, MAX_ADMINS);
+}
+
+const isTasksChannel = (channel: ChannelSummary, admins: Set) =>
+ channel.channelType === "system" &&
+ !channel.private &&
+ !channel.archived &&
+ !!channel.creator &&
+ admins.has(channel.creator) &&
+ !!channel.labels?.includes(TASKS_LABEL);
+
+/** Finds the community's tasks channel. Throws when it can't tell. */
+export async function findTasksChannel(
+ session: RelaySession,
+ signal: AbortSignal,
+): Promise {
+ const findLabeled = session.channels.findLabeled;
+ if (!findLabeled)
+ throw new Error("Tasks aren’t available in this community.");
+ const admins = await readAdmins(session, signal);
+ const trusted = new Set(admins);
+ const found = (
+ await Promise.all(
+ admins.map((creator) =>
+ findLabeled(
+ { creator, label: TASKS_LABEL },
+ { consistency: "strong", signal },
+ ),
+ ),
+ )
+ )
+ .flat()
+ .filter((channel) => isTasksChannel(channel, trusted))
+ .sort(compareChannelAge)[0];
+ if (found) return { status: "found", channelId: found.id };
+ return {
+ status: "missing",
+ canSetUp: !!session.viewer && trusted.has(session.viewer),
+ };
+}
+
+/** An admin sets Tasks up once for the whole community. */
+export async function setUpTasksChannel(
+ session: RelaySession,
+ signal: AbortSignal,
+): Promise {
+ const existing = await findTasksChannel(session, signal);
+ if (existing.status === "found" || !existing.canSetUp) return existing;
+ await session.channelCreation.create({
+ name: TASKS_CHANNEL_NAME,
+ visibility: "open",
+ labels: [TASKS_LABEL],
+ system: true,
+ });
+ const created = await findTasksChannel(session, signal);
+ if (created.status !== "found")
+ throw new Error("The tasks channel isn’t readable yet. Try again.");
+ return created;
+}
diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts
new file mode 100644
index 0000000000..53ee4975ce
--- /dev/null
+++ b/src/bundled/tasks/tools.test.ts
@@ -0,0 +1,139 @@
+import { expect, it, vi } from "vitest";
+import { PublishRejected } from "../../features/relay/outbox";
+import type { RelaySession } from "../../features/relay/session";
+import { TASK_TYPE } from "./model";
+import { addTaskTools } from "./tools";
+
+vi.mock("./tasks-channel", () => ({
+ findTasksChannel: async () => ({ status: "found", channelId: "tasks" }),
+}));
+
+const viewer = "a".repeat(64);
+const solo = "11111111-1111-4111-8111-111111111111";
+const head = (id: string, content: object) => ({
+ id,
+ pubkey: viewer,
+ sig: "",
+ created_at: 5,
+ kind: 45010,
+ content: JSON.stringify({ version: 1, author: viewer, ...content }),
+ tags: [
+ ["d", "task-1"],
+ ["type", TASK_TYPE],
+ ["title", "Fix the header"],
+ ],
+});
+
+function setup(
+ publish: () => Promise,
+ heads: () => object[],
+ share: "shared" | "cancelled" = "shared",
+) {
+ const signed: { content: string; tags: string[][] }[] = [];
+ const session = {
+ viewer,
+ channels: {
+ list: () => ({
+ channels: [
+ {
+ id: solo,
+ name: "Header",
+ channelType: "solo",
+ visibility: "private",
+ },
+ ],
+ }),
+ },
+ snapshotRead: vi.fn(async () => heads()),
+ configArtifactWriter: {
+ sign: vi.fn(async (template: { content: string; tags: string[][] }) => {
+ signed.push(template);
+ return {
+ ...template,
+ id: `${signed.length}`.padStart(64, "f"),
+ pubkey: viewer,
+ sig: "",
+ };
+ }),
+ publish: vi.fn(publish),
+ },
+ } as unknown as RelaySession;
+ const tools = new Map<
+ string,
+ (args: Record) => Promise
+ >();
+ const requestShare = vi.fn(async () => share);
+ addTaskTools(
+ {
+ relay: () =>
+ ({ snapshot: () => ({ status: "ready", session }) }) as never,
+ addTool: (tool) => {
+ tools.set(tool.name, (args) =>
+ tool.call(
+ { key: "agent", signal: new AbortController().signal } as never,
+ { channel: solo },
+ args,
+ ),
+ );
+ },
+ },
+ () => ({ requestShare }),
+ );
+ return { tools, signed, requestShare };
+}
+
+it("creates nothing when the owner declines to share the chat", async () => {
+ const { tools, signed, requestShare } = setup(
+ async () => "",
+ () => [],
+ "cancelled",
+ );
+ await expect(
+ tools.get("tasks_create")?.({ title: "Fix the header" }),
+ ).rejects.toThrow("chose not to share");
+ expect(requestShare).toHaveBeenCalledOnce();
+ expect(signed).toHaveLength(0);
+});
+
+it("creates a task linked to this chat once shared", async () => {
+ const { tools, signed } = setup(
+ async () => "",
+ () => [],
+ );
+ const reply = await tools.get("tasks_create")?.({
+ title: "Fix the header",
+ images: ["https://example.org/a.png"],
+ });
+ expect(reply).toContain("Created task");
+ expect(JSON.parse(signed[0]?.content ?? "")).toMatchObject({
+ links: [solo],
+ images: [{ url: "https://example.org/a.png" }],
+ });
+});
+
+it("reapplies an update over someone else's newer save", async () => {
+ let current = head("d".repeat(64), {
+ description: "Theirs.",
+ status: "open",
+ });
+ let calls = 0;
+ const { tools, signed } = setup(
+ async () => {
+ if (calls++ === 0) {
+ current = head("c".repeat(64), {
+ description: "Newer.",
+ status: "open",
+ });
+ throw new PublishRejected("rejected", "conflict: stale prev");
+ }
+ return "";
+ },
+ () => [current],
+ );
+ await tools.get("tasks_update")?.({ id: "task-1", status: "done" });
+ expect(signed[1]?.tags).toContainEqual(["prev", "c".repeat(64)]);
+ expect(JSON.parse(signed[1]?.content ?? "")).toMatchObject({
+ description: "Newer.",
+ status: "done",
+ });
+});
diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts
new file mode 100644
index 0000000000..8aa522f22e
--- /dev/null
+++ b/src/bundled/tasks/tools.ts
@@ -0,0 +1,347 @@
+// Agent tools. Each runs in the owner's app and writes as the owner, the way
+// the owner's own edits do. Linking a private Solo chat still waits for the
+// owner to confirm the app's "Share this chat?" dialog; an agent can't skip it.
+import {
+ ARTIFACT_KIND,
+ readHead,
+} from "../../features/agents/agent-config-artifacts";
+import type { Agents as AgentsService } from "../../features/agents/service";
+import type { RelaySession } from "../../features/relay/session";
+import type { ChatSharing } from "../../features/solo/share-requests";
+import { readyToLink } from "./linking";
+import {
+ imageOf,
+ isChannelId,
+ isOpenStatus,
+ statuses,
+ statusLabels,
+ TASK_TYPE,
+ type Task,
+ type TaskFields,
+ type TaskStatus,
+ taskOf,
+} from "./model";
+import { saveTask } from "./store";
+import { findTasksChannel } from "./tasks-channel";
+
+type Agents = Pick;
+type Args = Record;
+
+/** How many times an agent's change is reapplied over someone else's edit. */
+const ATTEMPTS = 3;
+const LIST_LIMIT = 50;
+
+const statusOf = (value: unknown): TaskStatus | undefined =>
+ statuses.find((status) => status === value);
+
+const textArg = (args: Args, name: string) => {
+ const value = args[name];
+ if (value === undefined) return undefined;
+ if (typeof value !== "string") throw new Error(`${name} must be text`);
+ return value;
+};
+
+function imagesArg(args: Args) {
+ if (args.images === undefined) return undefined;
+ if (!Array.isArray(args.images))
+ throw new Error("images must be a list of https media links");
+ return args.images.map((item) => {
+ const image = imageOf(typeof item === "string" ? { url: item } : item);
+ if (!image) throw new Error("Each image must be an https media link");
+ return image;
+ });
+}
+
+function describe(task: Task, session: RelaySession) {
+ const channels = session.channels.list().channels;
+ const links = task.links.map((id) => {
+ const channel = channels.find((item) => item.id === id);
+ return channel
+ ? `- ${channel.name} (${channel.channelType ?? "channel"}, ${id})`
+ : `- A conversation you can't read (${id})`;
+ });
+ return [
+ `# ${task.title}`,
+ `id: ${task.id}`,
+ `status: ${statusLabels[task.status]}`,
+ `author: ${task.author}`,
+ `updated: ${new Date(task.updatedAt * 1000).toISOString()} by ${task.editor}`,
+ "",
+ task.description || "(No description.)",
+ ...(task.images.length
+ ? ["", "## Images", ...task.images.map((image) => `- ${image.url}`)]
+ : []),
+ "",
+ "## Linked conversations",
+ ...(links.length ? links : ["(None.)"]),
+ ].join("\n");
+}
+
+export function addTaskTools(
+ agents: Agents,
+ sharing: () => ChatSharing | undefined,
+) {
+ /** The owner's session for this agent's community, and its tasks channel. */
+ async function open(client: { key: string; signal?: AbortSignal }) {
+ const relay = agents.relay(client.key)?.snapshot();
+ if (relay?.status !== "ready")
+ throw new Error("Tasks need this conversation's community");
+ const signal = client.signal ?? AbortSignal.timeout(60_000);
+ const found = await findTasksChannel(relay.session, signal);
+ if (found.status !== "found")
+ throw new Error(
+ found.canSetUp
+ ? "Tasks isn't set up in this community. Ask your owner to open Tasks and set it up."
+ : "Tasks isn't set up in this community. A community admin needs to set it up.",
+ );
+ return { session: relay.session, channel: found.channelId, signal };
+ }
+
+ async function current(
+ session: RelaySession,
+ channel: string,
+ id: string,
+ signal: AbortSignal,
+ ) {
+ const read = session.snapshotRead;
+ if (!read) throw new Error("This community can't read tasks");
+ const head = await readHead(read, channel, id, signal);
+ const task = head && taskOf(head);
+ if (!task) throw new Error(`No task ${id} here`);
+ return task;
+ }
+
+ /** Applies `edit` to the newest revision, again over anyone else's save. */
+ async function change(
+ session: RelaySession,
+ channel: string,
+ id: string,
+ edit: (task: Task) => TaskFields,
+ signal: AbortSignal,
+ ) {
+ let task = await current(session, channel, id, signal);
+ for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
+ signal.throwIfAborted();
+ const result = await saveTask(session, channel, edit(task), task, signal);
+ if (result.status === "saved") return result.task;
+ task = result.current ?? (await current(session, channel, id, signal));
+ }
+ throw new Error("Others keep changing this task. Try again.");
+ }
+
+ async function cleared(session: RelaySession, chat: string) {
+ const outcome = await readyToLink(session, sharing(), chat);
+ if (outcome === "cancelled")
+ throw new Error(
+ "Your owner chose not to share this chat, so it wasn't linked.",
+ );
+ if (outcome === "unavailable")
+ throw new Error("Only this chat's owner can link it to a task.");
+ }
+
+ agents.addTool({
+ name: "tasks_create",
+ description:
+ "Creates a task in this community's Tasks: a title, a Markdown description of what was noticed and why, and image links. Links this conversation unless link is false. Linking a private Solo chat makes it View only for the community, so your owner sees a confirmation first; nothing is created if they decline.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ title: { type: "string", description: "Short title" },
+ description: {
+ type: "string",
+ description: "Markdown: the context someone needs to pick this up",
+ },
+ images: {
+ type: "array",
+ items: { type: "string" },
+ description: "https media links of images, as messages attach them",
+ },
+ link: {
+ type: "boolean",
+ description: "Link this conversation (default true)",
+ },
+ },
+ required: ["title"],
+ additionalProperties: false,
+ },
+ async call(client, context, args) {
+ const title = textArg(args, "title") ?? "";
+ const images = imagesArg(args) ?? [];
+ const { session, channel, signal } = await open(client);
+ const chat = args.link === false ? undefined : context.channel;
+ if (chat) await cleared(session, chat);
+ signal.throwIfAborted();
+ const result = await saveTask(
+ session,
+ channel,
+ {
+ title,
+ description: textArg(args, "description") ?? "",
+ status: "open",
+ images,
+ links: chat ? [chat] : [],
+ },
+ undefined,
+ signal,
+ );
+ if (result.status !== "saved")
+ throw new Error("Couldn't create the task");
+ return `Created task ${result.task.id}.\n\n${describe(result.task, session)}`;
+ },
+ });
+
+ agents.addTool({
+ name: "tasks_read",
+ description:
+ "Reads one task with its description, images and linked conversations, or without id lists tasks (open by default).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string", description: "The task's id" },
+ status: {
+ type: "string",
+ enum: ["open", "done", "all"],
+ description: "Without id: which tasks to list",
+ },
+ linked_here: {
+ type: "boolean",
+ description: "Without id: only tasks linked to this conversation",
+ },
+ },
+ additionalProperties: false,
+ },
+ async call(client, context, args) {
+ const { session, channel, signal } = await open(client);
+ const id = textArg(args, "id");
+ if (id)
+ return describe(await current(session, channel, id, signal), session);
+ const read = session.snapshotRead;
+ if (!read) throw new Error("This community can't read tasks");
+ const which =
+ args.status === "done" || args.status === "all" ? args.status : "open";
+ const here = args.linked_here === true ? context.channel : undefined;
+ const tasks = (
+ await read(
+ [
+ {
+ artifact: "current",
+ kinds: [ARTIFACT_KIND],
+ "#h": [channel],
+ "#type": [TASK_TYPE],
+ limit: 500,
+ },
+ ],
+ { signal },
+ )
+ )
+ .flatMap((event) => taskOf(event) ?? [])
+ .filter(
+ (task) =>
+ (which === "all" ||
+ isOpenStatus(task.status) === (which === "open")) &&
+ (!here || task.links.includes(here)),
+ )
+ .sort((a, b) => b.updatedAt - a.updatedAt);
+ if (!tasks.length) return "No tasks match.";
+ return tasks
+ .slice(0, LIST_LIMIT)
+ .map(
+ (task) =>
+ `- ${task.id}: ${task.title} (${statusLabels[task.status]}, ${task.links.length} linked)`,
+ )
+ .concat(
+ tasks.length > LIST_LIMIT
+ ? [`…and ${tasks.length - LIST_LIMIT} more`]
+ : [],
+ )
+ .join("\n");
+ },
+ });
+
+ agents.addTool({
+ name: "tasks_update",
+ description:
+ "Changes a task's title, description, status or images. Omitted fields stay as they are; images replaces the whole list.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string" },
+ title: { type: "string" },
+ description: { type: "string", description: "Markdown" },
+ status: { type: "string", enum: [...statuses] },
+ images: {
+ type: "array",
+ items: { type: "string" },
+ description: "https media links",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ async call(client, _context, args) {
+ const id = textArg(args, "id") ?? "";
+ const title = textArg(args, "title");
+ const description = textArg(args, "description");
+ const status =
+ args.status === undefined ? undefined : statusOf(args.status);
+ if (args.status !== undefined && !status)
+ throw new Error(`status must be one of ${statuses.join(", ")}`);
+ const images = imagesArg(args);
+ const { session, channel, signal } = await open(client);
+ const task = await change(
+ session,
+ channel,
+ id,
+ (base) => ({
+ ...base,
+ ...(title !== undefined && { title }),
+ ...(description !== undefined && { description }),
+ ...(status && { status }),
+ ...(images && { images }),
+ }),
+ signal,
+ );
+ return `Updated.\n\n${describe(task, session)}`;
+ },
+ });
+
+ agents.addTool({
+ name: "tasks_link",
+ description:
+ "Links a conversation to a task, or unlinks it. Defaults to this conversation. Linking never adds anyone to it. Linking a private Solo chat makes it View only for the community, so your owner sees a confirmation first. Unlinking never changes access back.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string", description: "The task's id" },
+ channel: {
+ type: "string",
+ description: "The conversation's channel id (default: this one)",
+ },
+ unlink: { type: "boolean", description: "Unlink instead" },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ async call(client, context, args) {
+ const id = textArg(args, "id") ?? "";
+ const chat = textArg(args, "channel") ?? context.channel;
+ if (!isChannelId(chat)) throw new Error("channel must be a channel id");
+ const unlink = args.unlink === true;
+ const { session, channel, signal } = await open(client);
+ if (!unlink) await cleared(session, chat);
+ const task = await change(
+ session,
+ channel,
+ id,
+ (base) => ({
+ ...base,
+ links: unlink
+ ? base.links.filter((link) => link !== chat)
+ : [...base.links, chat],
+ }),
+ signal,
+ );
+ return `${unlink ? "Unlinked. Its access is unchanged." : "Linked."}\n\n${describe(task, session)}`;
+ },
+ });
+}
diff --git a/src/shared/design-system/icons/index.ts b/src/shared/design-system/icons/index.ts
index 2271f84fc3..99513695b8 100644
--- a/src/shared/design-system/icons/index.ts
+++ b/src/shared/design-system/icons/index.ts
@@ -461,6 +461,12 @@ export const PencilSimpleIcon = defineIcon("tabler", TablerPencilSimpleIcon);
import TablerListChecksIcon from "@tabler/icons-react/dist/esm/icons/IconListCheck.mjs";
export const ListChecksIcon = defineIcon("tabler", TablerListChecksIcon);
+import TablerClipboardCheckIcon from "@tabler/icons-react/dist/esm/icons/IconClipboardCheck.mjs";
+export const ClipboardCheckIcon = defineIcon(
+ "tabler",
+ TablerClipboardCheckIcon,
+);
+
import TablerArchiveIcon from "@tabler/icons-react/dist/esm/icons/IconArchive.mjs";
export const ArchiveIcon = defineIcon("tabler", TablerArchiveIcon);
From 1bea77e8bfc1db292735e175f511185bfdd1108e Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sat, 14 Nov 2026 14:22:42 -1000
Subject: [PATCH 05/18] fix(tasks): ask to share only as a link is saved, and
harden saves
- chatSharing names the chat, honors a caller's abort signal, and keeps
working after a StrictMode remount.
- Tasks asks for consent only when a save adds a link; agent tools check
their input and the task first, and pass cancellation through.
- A new task keeps one id across retries, so an unseen create is found
rather than duplicated; a conflict always carries the newer version.
- Saved-on-this-device overlays are per task and yield once the relay
has that revision or a newer one.
- Unsaved edits survive opening another task; narrow layout queries the
page, not the grid itself; the channel lookup is cached per session.
- Document chatSharing in docs/plugin-architecture.md.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
docs/plugin-architecture.md | 25 ++++
src/app/pages.integration.test.mjs | 1 +
src/bundled/tasks/TaskView.test.tsx | 29 ++++-
src/bundled/tasks/TaskView.tsx | 113 +++++++++++++-----
src/bundled/tasks/Tasks.module.css | 4 +-
src/bundled/tasks/TasksPage.tsx | 16 ++-
src/bundled/tasks/TasksPanel.tsx | 6 +-
src/bundled/tasks/linking.ts | 5 +-
src/bundled/tasks/react.ts | 29 +++--
src/bundled/tasks/store.test.ts | 26 ++++
src/bundled/tasks/store.ts | 36 +++---
src/bundled/tasks/tasks-channel.ts | 13 +-
src/bundled/tasks/tools.ts | 39 +++---
src/features/solo/ShareRequestDialog.test.tsx | 40 ++++++-
src/features/solo/ShareRequestDialog.tsx | 17 ++-
src/features/solo/share-requests.ts | 27 ++++-
16 files changed, 327 insertions(+), 99 deletions(-)
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index 62db444950..1497c0a641 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -405,6 +405,31 @@ an animated GIF or WebP loses its animation; offer the whole image for those.
The host fetches the authenticated media and runs Vision's foreground instance
mask (`media_lift_subject`); the plugin never receives media credentials.
+### Asking to share a Solo chat
+
+A plugin that links or shows a viewer's private Solo chat to others asks the
+host to make it View only. Read the optional `chatSharing` service with
+`ctx.reflect.get("chatSharing")`; it is `undefined` on older hosts.
+
+```ts
+type ChatSharing = {
+ requestShare(
+ session: RelaySession,
+ channelId: string,
+ options?: { signal?: AbortSignal },
+ ): Promise<"shared" | "cancelled" | "unavailable">;
+};
+```
+
+The host shows its own "Share this chat?" confirmation with the chat's name and
+the View only disclosure; nothing changes unless the viewer confirms. Only the
+viewer's own Solo chat can be shared (`"unavailable"` otherwise), and one
+already View only or public resolves `"shared"` with no dialog. Aborting
+`signal`, or the plugin stopping, withdraws the request as `"cancelled"`. Agent
+tools that link chats call it too, so an agent can't skip the confirmation. Ask
+only as the change that needs it is saved, so declining never leaves a chat
+shared for nothing.
+
### Plugin installer
A plugin, such as a catalog or marketplace page, may ask the host to review a plugin
diff --git a/src/app/pages.integration.test.mjs b/src/app/pages.integration.test.mjs
index c033a755bb..3dc74213b7 100644
--- a/src/app/pages.integration.test.mjs
+++ b/src/app/pages.integration.test.mjs
@@ -96,6 +96,7 @@ test("the app runtime exposes ready bundled pages and removes them on disable",
"buzz.file-viewer",
"buzz.drafts-and-sent",
"buzz.changesets",
+ "buzz.tasks",
].includes(plugin.manifest.id),
plugin.manifest.id,
);
diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx
index c6cd916f2b..a7ddca7867 100644
--- a/src/bundled/tasks/TaskView.test.tsx
+++ b/src/bundled/tasks/TaskView.test.tsx
@@ -121,9 +121,36 @@ it("links the current chat only once it may be linked", async () => {
);
const link = screen.getByRole("button", { name: "Link this chat" });
fireEvent.click(link);
- await vi.waitFor(() => expect(readyToLink).toHaveBeenCalledTimes(1));
+ await vi.waitFor(() => expect(link).toBeEnabled());
+ expect(readyToLink).toHaveBeenCalledTimes(1);
expect(signed).toHaveLength(0);
fireEvent.click(link);
await vi.waitFor(() => expect(onSaved).toHaveBeenCalled());
expect(onSaved.mock.calls[0]?.[0].links).toEqual([chat]);
});
+
+it("asks to share a new task's chat only at Create, and saves nothing if declined", async () => {
+ const { session, signed } = setup(async () => "");
+ const readyToLink = vi.fn(async () => "cancelled" as const);
+ render(
+ {}}
+ onSaved={() => {}}
+ />,
+ );
+ fireEvent.change(screen.getByLabelText("Title"), {
+ target: { value: "From this chat" },
+ });
+ expect(readyToLink).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Create task" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "This chat wasn’t shared, so the task wasn’t saved.",
+ );
+ expect(readyToLink).toHaveBeenCalledWith(chat);
+ expect(signed).toHaveLength(0);
+});
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index 9ff35d18b5..278e5f050a 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -1,4 +1,4 @@
-import { type ReactNode, useId, useRef, useState } from "react";
+import { type ReactNode, useEffect, useId, useRef, useState } from "react";
import type { RelaySession } from "../../features/relay/session";
import { useChannelReference } from "../../features/conversation/channel-reference";
import { DOCUMENT_PROFILE } from "../../features/markdown/document-profile";
@@ -47,6 +47,19 @@ const empty: TaskFields = {
images: [],
links: [],
};
+/** An open edit: the text, the revision it builds on, and the task's id. */
+export type TaskDraft = Readonly<{
+ fields: TaskFields;
+ base: Task | undefined;
+ id: string;
+}>;
+
+/** A save, or why it stopped before writing: a link the owner didn't share. */
+type ViewSave =
+ | Awaited>
+ | Readonly<{ status: "declined"; outcome: "cancelled" | "unavailable" }>;
+const declined = "Only this chat’s owner can link it to a task.";
+
const fieldsOf = (task: Task): TaskFields => ({
title: task.title,
description: task.description,
@@ -70,6 +83,9 @@ export type TaskViewProps = {
onSaved(task: Task): void;
/** Conversations a new task starts linked to, already cleared to link. */
newLinks?: readonly string[] | undefined;
+ /** Unsaved edits the list keeps while another task is open. */
+ draft?: TaskDraft | undefined;
+ onDraftChange?: ((draft: TaskDraft | undefined) => void) | undefined;
/** Leaves a new task without saving it. */
onDiscard?: (() => void) | undefined;
};
@@ -79,12 +95,31 @@ export type TaskViewProps = {
export function TaskView(props: TaskViewProps) {
const { session, channel, task } = props;
const notify = useToastNotification();
- const [editing, setEditing] = useState(!task);
+ const [editing, setEditing] = useState(!task || !!props.draft);
const [saving, setSaving] = useState(false);
- const save = async (fields: TaskFields, base: Task | undefined) => {
+ // Consent is asked only as a link is saved, so declining or discarding
+ // never leaves a chat shared with nothing linked to it.
+ const save = async (
+ fields: TaskFields,
+ base: Task | undefined,
+ id?: string,
+ ): Promise => {
setSaving(true);
try {
- const result = await saveTask(session, channel, fields, base);
+ for (const added of fields.links.filter(
+ (link) => !base?.links.includes(link),
+ )) {
+ const outcome = await props.readyToLink(added);
+ if (outcome !== "shared") return { status: "declined", outcome };
+ }
+ const result = await saveTask(
+ session,
+ channel,
+ fields,
+ base,
+ undefined,
+ id,
+ );
if (result.status === "saved") props.onSaved(result.task);
return result;
} finally {
@@ -97,7 +132,9 @@ export function TaskView(props: TaskViewProps) {
try {
const result = await save({ ...fieldsOf(task), ...next }, task);
if (result.status === "saved") return true;
- notify("Someone else changed this task. Try again.", "error");
+ if (result.status === "conflict")
+ notify("Someone else changed this task. Try again.", "error");
+ else if (result.outcome === "unavailable") notify(declined, "error");
} catch (reason) {
notify(
reason instanceof Error ? reason.message : "Couldn’t save the task.",
@@ -113,18 +150,14 @@ export function TaskView(props: TaskViewProps) {
saving={saving}
save={save}
onDone={(saved) => {
+ props.onDraftChange?.(undefined);
setEditing(false);
if (!saved && !task) props.onDiscard?.();
}}
/>
);
- const link = async (channelId: string) => {
- const outcome = await props.readyToLink(channelId);
- if (outcome === "shared")
- await change({ links: [...task.links, channelId] });
- else if (outcome === "unavailable")
- notify("Only this chat’s owner can link it to a task.", "error");
- };
+ const link = (channelId: string) =>
+ change({ links: [...task.links, channelId] });
const unlink = async (channelId: string) => {
const solo =
session.channels.list().channels.find((item) => item.id === channelId)
@@ -336,21 +369,35 @@ function TaskEditor({
session,
task,
newLinks,
+ draft: kept,
+ onDraftChange,
saving,
save,
onDone,
}: TaskViewProps & {
saving: boolean;
- save(fields: TaskFields, base: Task | undefined): ReturnType;
+ save(
+ fields: TaskFields,
+ base: Task | undefined,
+ id?: string,
+ ): Promise;
onDone(saved: boolean): void;
}) {
- const id = useId();
+ const inputId = useId();
const [draft, setDraft] = useState(
- task ? fieldsOf(task) : { ...empty, links: newLinks ?? [] },
+ kept?.fields ??
+ (task ? fieldsOf(task) : { ...empty, links: newLinks ?? [] }),
);
// The revision this draft builds on; a conflict moves it to theirs.
- const [base, setBase] = useState(task);
- const [conflict, setConflict] = useState<{ theirs?: Task | undefined }>();
+ const [base, setBase] = useState(kept ? kept.base : task);
+ // One id for a new task across retries, so a create that landed unseen
+ // is found rather than made twice.
+ const [taskId] = useState(() => kept?.id ?? task?.id ?? crypto.randomUUID());
+ useEffect(
+ () => onDraftChange?.({ fields: draft, base, id: taskId }),
+ [draft, base, taskId, onDraftChange],
+ );
+ const [conflict, setConflict] = useState<{ theirs: Task }>();
const [error, setError] = useState("");
const [uploading, setUploading] = useState(false);
const files = useRef(null);
@@ -359,12 +406,18 @@ function TaskEditor({
const submit = async () => {
setError("");
try {
- const result = await save(draft, base);
+ const result = await save(draft, base, taskId);
if (result.status === "saved") onDone(true);
+ else if (result.status === "declined")
+ setError(
+ result.outcome === "unavailable"
+ ? declined
+ : "This chat wasn’t shared, so the task wasn’t saved.",
+ );
else {
// Keep the person's text; the next Save is a deliberate overwrite.
setConflict({ theirs: result.current });
- if (result.current) setBase(result.current);
+ setBase(result.current);
}
} catch (reason) {
setError(
@@ -430,17 +483,15 @@ function TaskEditor({
Someone else changed this task. Your text is kept. Saving now
replaces their version.
- {conflict.theirs ? (
- {
- if (conflict.theirs) setDraft(fieldsOf(conflict.theirs));
- setConflict(undefined);
- }}
- >
- Show their version
-
- ) : null}
+ {
+ setDraft(fieldsOf(conflict.theirs));
+ setConflict(undefined);
+ }}
+ >
+ Show their version
+
) : null}
@@ -474,7 +525,7 @@ function TaskEditor({
)}
& {
@@ -180,6 +180,16 @@ function TaskBoard({
: state.tasks.find((item) => item.id === selected);
const detail = selected === "new" || task !== undefined;
const back = useCallback(() => setSelected(undefined), []);
+ // Unsaved edits survive opening another task (DESIGN.md master/detail).
+ const drafts = useRef(new Map());
+ const onDraftChange = useCallback(
+ (draft: TaskDraft | undefined) => {
+ if (!selected) return;
+ if (draft) drafts.current.set(selected, draft);
+ else drafts.current.delete(selected);
+ },
+ [selected],
+ );
return (
@@ -316,6 +326,8 @@ function TaskBoard({
task={task}
readyToLink={readyToLink}
openConversation={openConversation}
+ draft={selected ? drafts.current.get(selected) : undefined}
+ onDraftChange={onDraftChange}
onSaved={(next) => {
state.setSaved(next);
setSelected(next.id);
diff --git a/src/bundled/tasks/TasksPanel.tsx b/src/bundled/tasks/TasksPanel.tsx
index 19ad2aab8f..2986ffb54b 100644
--- a/src/bundled/tasks/TasksPanel.tsx
+++ b/src/bundled/tasks/TasksPanel.tsx
@@ -44,7 +44,7 @@ export function TasksPanel({
} & Pick) {
const state = useTasksWithSaved(session, channel);
const notify = useToastNotification();
- // "new" carries the links a new task starts with, cleared to link.
+ // A new task carries the links it starts with; consent waits for Create.
const [open, setOpen] = useState();
const [linking, setLinking] = useState(false);
const linked = state.tasks
@@ -119,9 +119,7 @@ export function TasksPanel({
size="sm"
variant="prominent"
disabled={linking}
- onClick={async () => {
- if (await cleared()) setOpen({ newLinks: [chat] });
- }}
+ onClick={() => setOpen({ newLinks: [chat] })}
>
New task from this chat
diff --git a/src/bundled/tasks/linking.ts b/src/bundled/tasks/linking.ts
index 48bc065d7c..98c1c5594f 100644
--- a/src/bundled/tasks/linking.ts
+++ b/src/bundled/tasks/linking.ts
@@ -12,6 +12,7 @@ export async function readyToLink(
session: RelaySession,
sharing: ChatSharing | undefined,
channelId: string,
+ signal?: AbortSignal,
): Promise {
const channel = session.channels
.list()
@@ -19,5 +20,7 @@ export async function readyToLink(
// Unknown visibility is not public: ask, and let the app's check decide.
if (channel?.channelType !== "solo" || channel.visibility === "public")
return "shared";
- return sharing ? sharing.requestShare(session, channelId) : "unavailable";
+ return sharing
+ ? sharing.requestShare(session, channelId, { signal })
+ : "unavailable";
}
diff --git a/src/bundled/tasks/react.ts b/src/bundled/tasks/react.ts
index 62eb91b2f2..ea11cb2fd3 100644
--- a/src/bundled/tasks/react.ts
+++ b/src/bundled/tasks/react.ts
@@ -33,17 +33,30 @@ export function useTasks(session: RelaySession, channel: string) {
return useSyncExternalStore(view.subscribe, view.snapshot, view.snapshot);
}
-/** Tasks from the live view, with this device's last save shown until the
- * relay's copy catches up with it. */
+/** Tasks from the live view, with this device's saves shown until the
+ * relay's copy has them: the same revision, or a strictly newer one. A tie
+ * keeps the save, the newest this device knows of. */
export function useTasksWithSaved(session: RelaySession, channel: string) {
const state = useTasks(session, channel);
- const [saved, setSaved] = useState();
+ const [saved, setSavedMap] = useState>(new Map());
+ const setSaved = useCallback(
+ (task: Task) =>
+ setSavedMap((current) => new Map(current).set(task.id, task)),
+ [],
+ );
const tasks = useMemo(() => {
- if (!saved) return state.tasks;
- const live = state.tasks.find((task) => task.id === saved.id);
- return live && live.updatedAt >= saved.updatedAt
- ? state.tasks
- : [...state.tasks.filter((task) => task.id !== saved.id), saved];
+ if (!saved.size) return state.tasks;
+ const live = new Map(state.tasks.map((task) => [task.id, task]));
+ for (const task of saved.values()) {
+ const current = live.get(task.id);
+ if (
+ !current ||
+ (current.revision !== task.revision &&
+ current.updatedAt <= task.updatedAt)
+ )
+ live.set(task.id, task);
+ }
+ return [...live.values()];
}, [state.tasks, saved]);
return { ...state, tasks, setSaved };
}
diff --git a/src/bundled/tasks/store.test.ts b/src/bundled/tasks/store.test.ts
index 8533bedb45..d57a202e34 100644
--- a/src/bundled/tasks/store.test.ts
+++ b/src/bundled/tasks/store.test.ts
@@ -92,3 +92,29 @@ it("confirms an uncertain save from the head, else says it failed", async () =>
saveTask(refused.session, "tasks", fields, base),
).rejects.toThrow("You can’t edit tasks in this community.");
});
+
+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");
+ }, [
+ {
+ ...head("f".repeat(64), {}),
+ tags: [
+ ["d", "chosen"],
+ ["type", TASK_TYPE],
+ ["title", "Fix the header"],
+ ],
+ },
+ ]);
+ const result = await saveTask(
+ relay,
+ "tasks",
+ fields,
+ undefined,
+ undefined,
+ "chosen",
+ );
+ expect(result.status).toBe("saved");
+ const template = sign.mock.calls[0]?.[0] as unknown as { tags: string[][] };
+ expect(template.tags).toContainEqual(["d", "chosen"]);
+});
diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts
index 00b598a56a..5cf3e79018 100644
--- a/src/bundled/tasks/store.ts
+++ b/src/bundled/tasks/store.ts
@@ -124,16 +124,19 @@ export function watchTasks(session: RelaySession, channel: string): TasksView {
export type SaveResult =
| Readonly<{ status: "saved"; task: Task }>
- /** Someone else saved first; `current` is their version when readable. */
- | Readonly<{ status: "conflict"; current?: Task | undefined }>;
+ /** Someone else saved first; `current` is their version, the next base. */
+ | Readonly<{ status: "conflict"; current: Task }>;
-/** Creates a task (no `base`) or saves `fields` over the `base` revision. */
+/** Creates task `id` (no `base`) or saves `fields` over the `base` revision.
+ * A new task's caller keeps one `id` across retries, so a create that landed
+ * unseen is found, not made twice. */
export async function saveTask(
session: RelaySession,
channel: string,
fields: TaskFields,
base: Task | undefined,
signal: AbortSignal = AbortSignal.timeout(20_000),
+ id: string = base?.id ?? crypto.randomUUID(),
): Promise {
const read = session.snapshotRead;
const writer = session.configArtifactWriter;
@@ -148,7 +151,7 @@ export async function saveTask(
content: taskContent(checked, base?.author ?? viewer),
tags: [
["ar", "1"],
- ["d", base?.id ?? crypto.randomUUID()],
+ ["d", id],
["h", channel],
["type", TASK_TYPE],
["title", checked.title],
@@ -164,20 +167,21 @@ export async function saveTask(
if (!task) throw new Error("Couldn’t read the saved task.");
return { status: "saved", task };
}
- if (delivery.status === "refused" && delivery.refusal === "conflict") {
- const head = base
- ? await readHead(read, channel, base.id, signal).catch(() => undefined)
- : undefined;
- return { status: "conflict", current: head && taskOf(head) };
- }
- if (delivery.status === "uncertain" && base) {
- // The relay accepts a replay of an accepted revision, so the head shows
- // whether this one landed.
- const head = await readHead(read, channel, base.id, signal).catch(
+ if (
+ (delivery.status === "refused" && delivery.refusal === "conflict") ||
+ delivery.status === "uncertain"
+ ) {
+ // The head shows whether this revision landed, or whose did instead.
+ const head = await readHead(read, channel, id, signal).catch(
() => undefined,
);
- const task = head?.id === event.id ? taskOf(head) : undefined;
- if (task) return { status: "saved", task };
+ const current = head && taskOf(head);
+ if (current?.revision === event.id)
+ return { status: "saved", task: current };
+ if (delivery.status === "refused" && current)
+ return { status: "conflict", current };
+ if (delivery.status === "refused")
+ throw new Error("Someone else changed this task. Try again.");
}
throw new Error(
delivery.status === "refused" && delivery.refusal === "permission"
diff --git a/src/bundled/tasks/tasks-channel.ts b/src/bundled/tasks/tasks-channel.ts
index 9b58929645..747d0fad77 100644
--- a/src/bundled/tasks/tasks-channel.ts
+++ b/src/bundled/tasks/tasks-channel.ts
@@ -46,17 +46,23 @@ const isTasksChannel = (channel: ChannelSummary, admins: Set) =>
admins.has(channel.creator) &&
!!channel.labels?.includes(TASKS_LABEL);
+// Once found, a community's tasks channel stays put for that connection, so
+// each panel and tool call doesn't read the roster and every admin again.
+const found = new WeakMap();
+
/** Finds the community's tasks channel. Throws when it can't tell. */
export async function findTasksChannel(
session: RelaySession,
signal: AbortSignal,
): Promise {
+ const known = found.get(session);
+ if (known) return { status: "found", channelId: known };
const findLabeled = session.channels.findLabeled;
if (!findLabeled)
throw new Error("Tasks aren’t available in this community.");
const admins = await readAdmins(session, signal);
const trusted = new Set(admins);
- const found = (
+ const oldest = (
await Promise.all(
admins.map((creator) =>
findLabeled(
@@ -69,7 +75,10 @@ export async function findTasksChannel(
.flat()
.filter((channel) => isTasksChannel(channel, trusted))
.sort(compareChannelAge)[0];
- if (found) return { status: "found", channelId: found.id };
+ if (oldest) {
+ found.set(session, oldest.id);
+ return { status: "found", channelId: oldest.id };
+ }
return {
status: "missing",
canSetUp: !!session.viewer && trusted.has(session.viewer),
diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts
index 8aa522f22e..d70ffc92b7 100644
--- a/src/bundled/tasks/tools.ts
+++ b/src/bundled/tasks/tools.ts
@@ -10,6 +10,7 @@ import type { RelaySession } from "../../features/relay/session";
import type { ChatSharing } from "../../features/solo/share-requests";
import { readyToLink } from "./linking";
import {
+ checkedFields,
imageOf,
isChannelId,
isOpenStatus,
@@ -129,8 +130,13 @@ export function addTaskTools(
throw new Error("Others keep changing this task. Try again.");
}
- async function cleared(session: RelaySession, chat: string) {
- const outcome = await readyToLink(session, sharing(), chat);
+ async function cleared(
+ session: RelaySession,
+ chat: string,
+ signal: AbortSignal,
+ ) {
+ const outcome = await readyToLink(session, sharing(), chat, signal);
+ signal.throwIfAborted();
if (outcome === "cancelled")
throw new Error(
"Your owner chose not to share this chat, so it wasn't linked.",
@@ -165,22 +171,21 @@ export function addTaskTools(
additionalProperties: false,
},
async call(client, context, args) {
- const title = textArg(args, "title") ?? "";
- const images = imagesArg(args) ?? [];
- const { session, channel, signal } = await open(client);
const chat = args.link === false ? undefined : context.channel;
- if (chat) await cleared(session, chat);
- signal.throwIfAborted();
+ // Checked before the owner is asked, so a bad call never shares a chat.
+ const fields = checkedFields({
+ title: textArg(args, "title") ?? "",
+ description: textArg(args, "description") ?? "",
+ status: "open",
+ images: imagesArg(args) ?? [],
+ links: chat ? [chat] : [],
+ });
+ const { session, channel, signal } = await open(client);
+ if (chat) await cleared(session, chat, signal);
const result = await saveTask(
session,
channel,
- {
- title,
- description: textArg(args, "description") ?? "",
- status: "open",
- images,
- links: chat ? [chat] : [],
- },
+ fields,
undefined,
signal,
);
@@ -328,7 +333,11 @@ export function addTaskTools(
if (!isChannelId(chat)) throw new Error("channel must be a channel id");
const unlink = args.unlink === true;
const { session, channel, signal } = await open(client);
- if (!unlink) await cleared(session, chat);
+ if (!unlink) {
+ // The task must exist before the owner is asked to share for it.
+ await current(session, channel, id, signal);
+ await cleared(session, chat, signal);
+ }
const task = await change(
session,
channel,
diff --git a/src/features/solo/ShareRequestDialog.test.tsx b/src/features/solo/ShareRequestDialog.test.tsx
index 701f4ab08d..c878967a5f 100644
--- a/src/features/solo/ShareRequestDialog.test.tsx
+++ b/src/features/solo/ShareRequestDialog.test.tsx
@@ -2,6 +2,7 @@
import { Context } from "@deepseek-ai/cordis";
import { act, cleanup, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
+import { StrictMode } from "react";
import { afterEach, expect, it, vi } from "vitest";
import type { RelaySession } from "../relay/session";
import type {
@@ -69,7 +70,7 @@ it("shows the app's confirmation and makes the chat View only only when confirme
const requests = createShareRequests();
render( );
const outcome = requests.request(f.session, id);
- expect(await screen.findByText("Share this chat?")).toBeTruthy();
+ expect(await screen.findByText("Share “Chat”?")).toBeTruthy();
expect(
screen.getByText(
/full history, Canvas, workspace folders, and agent instructions/,
@@ -84,7 +85,7 @@ it("shows the app's confirmation and makes the chat View only only when confirme
expect.any(AbortSignal),
expect.any(Function),
);
- expect(screen.queryByText("Share this chat?")).toBeNull();
+ expect(screen.queryByText("Share “Chat”?")).toBeNull();
});
it("changes nothing when the viewer cancels", async () => {
@@ -118,7 +119,7 @@ it("resolves without a dialog when the chat is already open", async () => {
render( );
expect(await requests.request(f.session, id)).toBe("shared");
expect(requests.snapshot()).toEqual([]);
- expect(screen.queryByText("Share this chat?")).toBeNull();
+ expect(screen.queryByText("Share “Chat”?")).toBeNull();
});
it("refuses without a dialog for a chat the viewer does not own", async () => {
@@ -134,7 +135,7 @@ it("asks once for repeated requests about the same chat", async () => {
const requests = createShareRequests();
render( );
const first = requests.request(f.session, id);
- await screen.findByText("Share this chat?");
+ await screen.findByText("Share “Chat”?");
const second = requests.request(f.session, id);
expect(requests.snapshot()).toHaveLength(1);
await userEvent.click(screen.getByRole("button", { name: "Share" }));
@@ -158,11 +159,38 @@ it("withdraws a plugin's request when the plugin stops", async () => {
render( );
if (!sharing) throw new Error("chatSharing is unavailable");
const outcome = sharing.requestShare(f.session, id);
- await screen.findByText("Share this chat?");
+ await screen.findByText("Share “Chat”?");
await act(async () => {
await fiber.dispose();
});
expect(await outcome).toBe("cancelled");
- expect(screen.queryByText("Share this chat?")).toBeNull();
+ expect(screen.queryByText("Share “Chat”?")).toBeNull();
expect(f.save).not.toHaveBeenCalled();
});
+
+it("withdraws a request when its caller's signal aborts", async () => {
+ const f = fixture();
+ const requests = createShareRequests();
+ render( );
+ const controller = new AbortController();
+ const outcome = requests.request(f.session, id, undefined, controller.signal);
+ await screen.findByText("Share “Chat”?");
+ act(() => controller.abort());
+ expect(await outcome).toBe("cancelled");
+ expect(screen.queryByText("Share “Chat”?")).toBeNull();
+ expect(f.save).not.toHaveBeenCalled();
+});
+
+it("still shares after a StrictMode remount", async () => {
+ const f = fixture();
+ const requests = createShareRequests();
+ render(
+
+
+ ,
+ );
+ const outcome = requests.request(f.session, id);
+ await userEvent.click(await screen.findByRole("button", { name: "Share" }));
+ expect(await outcome).toBe("shared");
+ expect(f.save).toHaveBeenCalledOnce();
+});
diff --git a/src/features/solo/ShareRequestDialog.tsx b/src/features/solo/ShareRequestDialog.tsx
index aad44fb965..ad48dd93ce 100644
--- a/src/features/solo/ShareRequestDialog.tsx
+++ b/src/features/solo/ShareRequestDialog.tsx
@@ -32,9 +32,11 @@ function ShareRequestConfirmation({
const [error, setError] = useState("");
// An uncertain save is checked on retry, never republished.
const attempts = useRef(new Map());
- const controller = useRef(new AbortController());
+ // Made in the effect, so a remount (StrictMode) never keeps an aborted one.
+ const controller = useRef(undefined);
useEffect(() => {
- const active = controller.current;
+ const active = new AbortController();
+ controller.current = active;
return () => active.abort();
}, []);
const decline = () => requests.settle(request.id, "cancelled");
@@ -42,7 +44,8 @@ function ShareRequestConfirmation({
if (busy) return;
setBusy(true);
setError("");
- const { signal } = controller.current;
+ const signal = controller.current?.signal;
+ if (!signal || signal.aborted) return;
try {
await shareSoloChatAccess(request.session, request.details.channelId, {
signal,
@@ -60,10 +63,14 @@ function ShareRequestConfirmation({
};
return (
- This changes the chat from Private to View only.{" "}
+ A plugin asked to change this chat from Private to View only.{" "}
{soloShareDisclosure()}
>
}
diff --git a/src/features/solo/share-requests.ts b/src/features/solo/share-requests.ts
index 1ea9ecda31..d8d9539d28 100644
--- a/src/features/solo/share-requests.ts
+++ b/src/features/solo/share-requests.ts
@@ -13,11 +13,12 @@ export type ChatSharing = Readonly<{
* viewer confirms. Resolves `"shared"` once the chat is View only or public
* (at once, without a dialog, when it already is), `"cancelled"` when the
* viewer declines or the caller stops, and `"unavailable"` when the viewer
- * cannot share it. Never rejects.
+ * cannot share it. Never rejects. Aborting `signal` withdraws the request.
*/
requestShare(
session: RelaySession,
channelId: string,
+ options?: Readonly<{ signal?: AbortSignal | undefined }>,
): Promise;
}>;
@@ -68,7 +69,9 @@ export function createShareRequests() {
session: RelaySession,
channelId: string,
lifetime?: (end: () => void) => () => void,
+ signal?: AbortSignal,
): Promise {
+ if (signal?.aborted) return "cancelled";
const same = pending.find(
(entry) =>
entry.session === session && entry.details.channelId === channelId,
@@ -76,6 +79,8 @@ export function createShareRequests() {
if (same) return same.done;
const controller = new AbortController();
const stop = lifetime?.(() => controller.abort());
+ const withdraw = () => controller.abort();
+ signal?.addEventListener("abort", withdraw, { once: true });
try {
// The same check both share dialogs make: only the viewer's own Solo
// chat, with its current signed access.
@@ -113,6 +118,7 @@ export function createShareRequests() {
return await done;
} finally {
stop?.();
+ signal?.removeEventListener("abort", withdraw);
}
}
@@ -139,12 +145,21 @@ export function createChatSharingService(
}
// A method, so Cordis supplies the caller's context for its lifetime.
- requestShare(session: RelaySession, channelId: string) {
+ requestShare(
+ session: RelaySession,
+ channelId: string,
+ options?: Readonly<{ signal?: AbortSignal | undefined }>,
+ ) {
const caller = this.ctx;
- return requests.request(session, channelId, (end) => {
- const stop = caller.effect(() => end);
- return () => void stop();
- });
+ return requests.request(
+ session,
+ channelId,
+ (end) => {
+ const stop = caller.effect(() => end);
+ return () => void stop();
+ },
+ options?.signal,
+ );
}
}
return new ChatSharingService();
From 2ed9cab64099f126ea066fe59545bbcc331291fc Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sat, 14 Nov 2026 14:25:08 -1000
Subject: [PATCH 06/18] feat(tasks): the first person to use Tasks makes its
channel
No admin setup: the Tasks page, panel or an agent tool creates the
community's tasks channel on first use. Every client uses the oldest open
labeled system channel, whoever made it, so racing first uses converge
before any task is saved.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/README.md | 5 +-
src/bundled/tasks/TasksGate.tsx | 31 +------
src/bundled/tasks/react.ts | 44 +++------
src/bundled/tasks/tasks-channel.test.ts | 90 ++++++++++++++++++
src/bundled/tasks/tasks-channel.ts | 118 ++++++++++++------------
src/bundled/tasks/tools.test.ts | 2 +-
src/bundled/tasks/tools.ts | 12 +--
7 files changed, 170 insertions(+), 132 deletions(-)
create mode 100644 src/bundled/tasks/tasks-channel.test.ts
diff --git a/src/bundled/tasks/README.md b/src/bundled/tasks/README.md
index c5bc1963f8..19b2706cd3 100644
--- a/src/bundled/tasks/README.md
+++ b/src/bundled/tasks/README.md
@@ -4,9 +4,8 @@ A task holds the context for a piece of work and links the conversations about i
## Getting started
-1. A community admin opens **Tasks** once and chooses **Set up Tasks**.
-2. Choose **New task**, give it a title and a description, and add images if they help.
-3. In a chat or channel, choose **Tasks** in its header to see the tasks linked there, make one from the chat, or link the chat to an existing task.
+1. Open **Tasks** and choose **New task**, give it a title and a description, and add images if they help.
+2. In a chat or channel, choose **Tasks** in its header to see the tasks linked there, make one from the chat, or link the chat to an existing task.
You can also ask your agent to make a task from a conversation.
diff --git a/src/bundled/tasks/TasksGate.tsx b/src/bundled/tasks/TasksGate.tsx
index 88fd587c13..58a0ed2065 100644
--- a/src/bundled/tasks/TasksGate.tsx
+++ b/src/bundled/tasks/TasksGate.tsx
@@ -1,14 +1,12 @@
import type { ReactNode } from "react";
import type { RelaySession } from "../../features/relay/session";
-import { ClipboardCheckIcon } from "../../shared/design-system/icons/index";
import { Button } from "../../shared/design-system/ui/Button";
-import { EmptyState } from "../../shared/design-system/ui/EmptyState";
import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion";
import { useTasksChannel } from "./react";
import styles from "./Tasks.module.css";
-/** Finds the community's tasks channel before showing `children`, or explains
- * why there is none yet. The page and the panel share it. */
+/** Opens the community's tasks channel before showing `children`, making it
+ * on the community's first use. The page and the panel share it. */
export function TasksGate({
session,
children,
@@ -18,31 +16,6 @@ export function TasksGate({
}) {
const channel = useTasksChannel(session);
if (channel.status === "found") return children(channel.channelId);
- if (channel.status === "missing")
- return (
-
- }
- title="Tasks isn’t set up yet"
- description={
- channel.canSetUp
- ? "Set up Tasks once for everyone in this community. You’ll own the hidden channel that holds them."
- : "Ask a community admin to set up Tasks."
- }
- action={
- channel.canSetUp ? (
-
- Set up Tasks
-
- ) : undefined
- }
- />
-
- );
return (
| Readonly<{ status: "error"; error: string; retry(): void }>
- | Readonly<{ status: "found"; channelId: string }>
- | Readonly<{
- status: "missing";
- canSetUp: boolean;
- settingUp: boolean;
- setUp(): void;
- }>;
-
-const message = (reason: unknown) =>
- reason instanceof Error ? reason.message : "Couldn’t open Tasks.";
+ | Readonly<{ status: "found"; channelId: string }>;
-/** The community's tasks channel, and the admin's one-time setup. */
+/** The community's tasks channel, made on its first use. */
export function useTasksChannel(session: RelaySession): TasksChannelState {
const [attempt, setAttempt] = useState(0);
const [result, setResult] = useState<
- TasksChannel | { status: "error"; error: string } | undefined
+ { channelId: string } | { error: string } | undefined
>();
- const [settingUp, setSettingUp] = useState(false);
const retry = useCallback(() => setAttempt((count) => count + 1), []);
// biome-ignore lint/correctness/useExhaustiveDependencies: a retry is a new attempt.
useEffect(() => {
const controller = new AbortController();
setResult(undefined);
- findTasksChannel(session, controller.signal).then(
- (found) => !controller.signal.aborted && setResult(found),
+ openTasksChannel(session, controller.signal).then(
+ (channelId) => !controller.signal.aborted && setResult({ channelId }),
(reason: unknown) =>
!controller.signal.aborted &&
- setResult({ status: "error", error: message(reason) }),
+ setResult({
+ error:
+ reason instanceof Error ? reason.message : "Couldn’t open Tasks.",
+ }),
);
return () => controller.abort();
}, [session, attempt]);
- const setUp = useCallback(() => {
- setSettingUp(true);
- setUpTasksChannel(session, AbortSignal.timeout(30_000))
- .then(setResult, (reason: unknown) =>
- setResult({ status: "error", error: message(reason) }),
- )
- .finally(() => setSettingUp(false));
- }, [session]);
if (!result) return { status: "loading" };
- if (result.status === "error") return { ...result, retry };
- if (result.status === "found") return result;
- return { ...result, settingUp, setUp };
+ if ("error" in result) return { status: "error", error: result.error, retry };
+ return { status: "found", channelId: result.channelId };
}
diff --git a/src/bundled/tasks/tasks-channel.test.ts b/src/bundled/tasks/tasks-channel.test.ts
new file mode 100644
index 0000000000..e52e469e53
--- /dev/null
+++ b/src/bundled/tasks/tasks-channel.test.ts
@@ -0,0 +1,90 @@
+import { expect, it, vi } from "vitest";
+import type { ChannelSummary } from "../../features/relay/contracts";
+import type { RelaySession } from "../../features/relay/session";
+import { openTasksChannel, TASKS_LABEL } from "./tasks-channel";
+
+const relay = "r".repeat(64);
+const alice = "a".repeat(64);
+const bob = "b".repeat(64);
+const metadata = (id: string, creator: string, labels = [TASKS_LABEL]) => ({
+ id: id.padEnd(64, "0"),
+ pubkey: relay,
+ sig: "",
+ created_at: 1,
+ kind: 39000,
+ content: "",
+ tags: [
+ ["d", id],
+ ["t", "system"],
+ ...labels.map((label) => ["t", label]),
+ ["P", creator],
+ ],
+});
+const channel = (
+ id: string,
+ creator: string,
+ createdAt: number,
+ extra: Partial = {},
+): ChannelSummary => ({
+ id,
+ name: "Tasks",
+ channelType: "system",
+ creator,
+ createdAt,
+ labels: [TASKS_LABEL],
+ ...extra,
+});
+
+function fixture(byCreator: Record) {
+ const events = Object.entries(byCreator).flatMap(([creator, list]) =>
+ list.map((item) => metadata(item.id, creator)),
+ );
+ const create = vi.fn(async () => {
+ byCreator[alice] = [...(byCreator[alice] ?? []), channel("mine", alice, 9)];
+ events.push(metadata("mine", alice));
+ return "mine";
+ });
+ const session = {
+ relayAuthor: relay,
+ snapshotRead: vi.fn(async () => [
+ ...events,
+ metadata("config", bob, ["buzz.agent"]),
+ ]),
+ channels: {
+ findLabeled: vi.fn(
+ async ({ creator }: { creator: string }) => byCreator[creator] ?? [],
+ ),
+ },
+ channelCreation: { create },
+ } as unknown as RelaySession;
+ return { session, create };
+}
+
+it("uses the community's oldest open tasks channel, whoever made it", async () => {
+ const { session, create } = fixture({
+ [alice]: [channel("later", alice, 5)],
+ [bob]: [
+ channel("first", bob, 2),
+ channel("archived", bob, 1, { archived: true }),
+ channel("locked", bob, 1, { private: true }),
+ ],
+ });
+ expect(await openTasksChannel(session, new AbortController().signal)).toBe(
+ "first",
+ );
+ expect(create).not.toHaveBeenCalled();
+});
+
+it("makes the channel on the community's first use", async () => {
+ const { session, create } = fixture({});
+ expect(await openTasksChannel(session, new AbortController().signal)).toBe(
+ "mine",
+ );
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ system: true,
+ visibility: "open",
+ labels: [TASKS_LABEL],
+ }),
+ );
+});
diff --git a/src/bundled/tasks/tasks-channel.ts b/src/bundled/tasks/tasks-channel.ts
index 747d0fad77..f9cb46113e 100644
--- a/src/bundled/tasks/tasks-channel.ts
+++ b/src/bundled/tasks/tasks-channel.ts
@@ -1,70 +1,76 @@
// The community's tasks live in one open NIP-CL system channel: hidden from
-// channel lists, readable and writable by everyone in the community. Its
-// creator owns it, so only a channel a community owner or admin created
-// counts; the oldest such channel is the community's (NIP-CL "Choosing one
-// channel"), so concurrent setups converge.
+// channel lists, readable and writable by everyone in the community. The
+// first person to use Tasks creates it, and its creator owns it. Concurrent
+// first uses can each create one; everyone uses the oldest (NIP-CL "Choosing
+// one channel"), so they converge before any task is saved.
import {
- MEMBERSHIP_KIND,
- membersFromSnapshot,
-} from "../../features/communities/roster";
-import { compareChannelAge } from "../../features/relay/channel-labels";
+ channelIdentity,
+ compareChannelAge,
+} from "../../features/relay/channel-labels";
import type { ChannelSummary } from "../../features/relay/contracts";
import type { RelaySession } from "../../features/relay/session";
export const TASKS_LABEL = "buzz.tasks";
const TASKS_CHANNEL_NAME = "Tasks";
-/** Communities have few admins; more than this is not looked through. */
-const MAX_ADMINS = 32;
+/** One page of open system channels; a community has few. */
+const SYSTEM_CHANNELS_READ = 500;
+/** Different creators only happen when first uses race. */
+const MAX_CREATORS = 8;
-export type TasksChannel =
- | Readonly<{ status: "found"; channelId: string }>
- /** No admin has set Tasks up; `canSetUp` when the viewer may. */
- | Readonly<{ status: "missing"; canSetUp: boolean }>;
-
-/** The community's owners and admins, from the relay-signed roster. */
-async function readAdmins(session: RelaySession, signal: AbortSignal) {
- const author = session.relayAuthor;
- if (!author) throw new Error("This community can’t confirm its admins.");
- const events = await session.read(
- [{ kinds: [MEMBERSHIP_KIND], authors: [author], limit: 1 }],
- { fresh: true, signal },
- );
- const latest = [...events].sort(
- (a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id),
- )[0];
- return (latest ? membersFromSnapshot(latest, author) : [])
- .filter((member) => member.role === "owner" || member.role === "admin")
- .map((member) => member.pubkey)
- .slice(0, MAX_ADMINS);
-}
-
-const isTasksChannel = (channel: ChannelSummary, admins: Set) =>
+const isTasksChannel = (channel: ChannelSummary) =>
channel.channelType === "system" &&
!channel.private &&
!channel.archived &&
- !!channel.creator &&
- admins.has(channel.creator) &&
!!channel.labels?.includes(TASKS_LABEL);
// Once found, a community's tasks channel stays put for that connection, so
-// each panel and tool call doesn't read the roster and every admin again.
+// each panel and tool call doesn't look it up again.
const found = new WeakMap();
-/** Finds the community's tasks channel. Throws when it can't tell. */
+/** The community's tasks channel, or undefined when nobody has made one.
+ * Throws when it can't tell. */
export async function findTasksChannel(
session: RelaySession,
signal: AbortSignal,
-): Promise {
+): Promise {
const known = found.get(session);
- if (known) return { status: "found", channelId: known };
+ if (known) return known;
const findLabeled = session.channels.findLabeled;
- if (!findLabeled)
+ const read = session.snapshotRead;
+ const author = session.relayAuthor;
+ if (!findLabeled || !read || !author)
throw new Error("Tasks aren’t available in this community.");
- const admins = await readAdmins(session, signal);
- const trusted = new Set(admins);
+ // A label alone never returns system channels, and its creator isn't
+ // known yet: ask for system channels, then keep the labeled ones' creators.
+ const events = await read(
+ [
+ {
+ kinds: [39000],
+ authors: [author],
+ "#t": ["system"],
+ limit: SYSTEM_CHANNELS_READ,
+ consistency: "strong",
+ },
+ ],
+ { signal },
+ );
+ const creators = [
+ ...new Set(
+ events.flatMap((event) => {
+ const identity = channelIdentity(event);
+ return event.pubkey === author &&
+ identity.type === "system" &&
+ identity.labels.includes(TASKS_LABEL) &&
+ identity.creator
+ ? [identity.creator]
+ : [];
+ }),
+ ),
+ ].slice(0, MAX_CREATORS);
+ // findLabeled verifies each channel's relay-signed creator and labels.
const oldest = (
await Promise.all(
- admins.map((creator) =>
+ creators.map((creator) =>
findLabeled(
{ creator, label: TASKS_LABEL },
{ consistency: "strong", signal },
@@ -73,33 +79,29 @@ export async function findTasksChannel(
)
)
.flat()
- .filter((channel) => isTasksChannel(channel, trusted))
+ .filter(isTasksChannel)
.sort(compareChannelAge)[0];
- if (oldest) {
- found.set(session, oldest.id);
- return { status: "found", channelId: oldest.id };
- }
- return {
- status: "missing",
- canSetUp: !!session.viewer && trusted.has(session.viewer),
- };
+ if (oldest) found.set(session, oldest.id);
+ return oldest?.id;
}
-/** An admin sets Tasks up once for the whole community. */
-export async function setUpTasksChannel(
+/** The tasks channel, created when this is the community's first use. */
+export async function openTasksChannel(
session: RelaySession,
signal: AbortSignal,
-): Promise {
+): Promise {
const existing = await findTasksChannel(session, signal);
- if (existing.status === "found" || !existing.canSetUp) return existing;
+ if (existing) return existing;
await session.channelCreation.create({
name: TASKS_CHANNEL_NAME,
visibility: "open",
labels: [TASKS_LABEL],
system: true,
});
+ signal.throwIfAborted();
+ // Find again rather than trust the create: a concurrent first use may own
+ // the older channel.
const created = await findTasksChannel(session, signal);
- if (created.status !== "found")
- throw new Error("The tasks channel isn’t readable yet. Try again.");
+ if (!created) throw new Error("Tasks isn’t ready yet. Try again.");
return created;
}
diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts
index 53ee4975ce..07f8d2c6a3 100644
--- a/src/bundled/tasks/tools.test.ts
+++ b/src/bundled/tasks/tools.test.ts
@@ -5,7 +5,7 @@ import { TASK_TYPE } from "./model";
import { addTaskTools } from "./tools";
vi.mock("./tasks-channel", () => ({
- findTasksChannel: async () => ({ status: "found", channelId: "tasks" }),
+ openTasksChannel: async () => "tasks",
}));
const viewer = "a".repeat(64);
diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts
index d70ffc92b7..6cef301a20 100644
--- a/src/bundled/tasks/tools.ts
+++ b/src/bundled/tasks/tools.ts
@@ -23,7 +23,7 @@ import {
taskOf,
} from "./model";
import { saveTask } from "./store";
-import { findTasksChannel } from "./tasks-channel";
+import { openTasksChannel } from "./tasks-channel";
type Agents = Pick;
type Args = Record;
@@ -88,14 +88,8 @@ export function addTaskTools(
if (relay?.status !== "ready")
throw new Error("Tasks need this conversation's community");
const signal = client.signal ?? AbortSignal.timeout(60_000);
- const found = await findTasksChannel(relay.session, signal);
- if (found.status !== "found")
- throw new Error(
- found.canSetUp
- ? "Tasks isn't set up in this community. Ask your owner to open Tasks and set it up."
- : "Tasks isn't set up in this community. A community admin needs to set it up.",
- );
- return { session: relay.session, channel: found.channelId, signal };
+ const channel = await openTasksChannel(relay.session, signal);
+ return { session: relay.session, channel, signal };
}
async function current(
From 2bf8108b75de6f638a679e6f8cc90558c1a47558 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sat, 14 Nov 2026 15:16:17 -1000
Subject: [PATCH 07/18] fix(tasks): address review of the share request and
tasks channel
- The share confirmation names the asking plugin, its reason (the agent and
task), and a chat without a name by a short id.
- Once the viewer chooses Share, the caller can no longer withdraw the
request, so its outcome always matches the chat's access.
- Agent tools wait on the owner's confirmation with no deadline of their own.
- Looking at Tasks never makes the tasks channel; the first saved task does.
Concurrent opens on one connection share a single creation.
- An unclear tasks_create names the task id to check before retrying.
- Tool descriptions say tasks are readable by the whole community.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
docs/plugin-architecture.md | 13 ++-
src/app/services.ts | 11 ++-
src/bundled/tasks/TaskView.test.tsx | 35 ++++++--
src/bundled/tasks/TaskView.tsx | 13 +--
src/bundled/tasks/TasksGate.tsx | 10 +--
src/bundled/tasks/TasksPage.tsx | 10 +--
src/bundled/tasks/TasksPanel.tsx | 17 ++--
src/bundled/tasks/index.tsx | 4 +-
src/bundled/tasks/linking.test.ts | 24 ++++--
src/bundled/tasks/linking.ts | 16 +++-
src/bundled/tasks/react.ts | 52 +++++++++---
src/bundled/tasks/tasks-channel.test.ts | 41 +++++++++-
src/bundled/tasks/tasks-channel.ts | 43 ++++++++--
src/bundled/tasks/tools.test.ts | 58 ++++++++++++-
src/bundled/tasks/tools.ts | 81 ++++++++++++++-----
src/features/solo/ShareRequestDialog.test.tsx | 72 ++++++++++++++---
src/features/solo/ShareRequestDialog.tsx | 22 ++---
src/features/solo/share-requests.ts | 55 +++++++++++--
18 files changed, 471 insertions(+), 106 deletions(-)
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index 1497c0a641..945b330a97 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -416,16 +416,21 @@ type ChatSharing = {
requestShare(
session: RelaySession,
channelId: string,
- options?: { signal?: AbortSignal },
+ options?: { signal?: AbortSignal; reason?: string },
): Promise<"shared" | "cancelled" | "unavailable">;
};
```
-The host shows its own "Share this chat?" confirmation with the chat's name and
-the View only disclosure; nothing changes unless the viewer confirms. Only the
+The host shows its own "Share this chat?" confirmation with the chat's name (or
+a short id), the asking plugin's name, the plugin's one-sentence `reason` as
+its own words, and the View only disclosure; nothing changes unless the viewer
+confirms. Only the
viewer's own Solo chat can be shared (`"unavailable"` otherwise), and one
already View only or public resolves `"shared"` with no dialog. Aborting
-`signal`, or the plugin stopping, withdraws the request as `"cancelled"`. Agent
+`signal`, or the plugin stopping, withdraws the request as `"cancelled"` until
+the viewer chooses Share; from then on only the viewer ends it, so the outcome
+always matches the chat's access. Don't put a deadline on `signal`: the viewer
+answers in their own time. Agent
tools that link chats call it too, so an agent can't skip the confirmation. Ask
only as the change that needs it is saved, so declining never leaves a chat
shared for nothing.
diff --git a/src/app/services.ts b/src/app/services.ts
index 90112751b4..02423fbd6b 100644
--- a/src/app/services.ts
+++ b/src/app/services.ts
@@ -116,7 +116,16 @@ export function createServices() {
});
createPluginInstallerService(ctx, { core: pluginInstallCore });
const shareRequests = createShareRequests();
- createChatSharingService(ctx, shareRequests);
+ createChatSharingService(ctx, shareRequests, (id) => {
+ const { configuration } = plugins.snapshot();
+ const name =
+ configuration.status === "ready"
+ ? configuration.catalog.plugins.find(
+ (plugin) => plugin.manifest.id === id,
+ )?.manifest.name
+ : undefined;
+ return name?.replace(/\s+/g, " ").trim().slice(0, 80) || id;
+ });
const sidebarScope = new SidebarScopeService(ctx);
const sidebarRows = new SidebarRowsService(ctx);
const panels = new PanelsService(ctx);
diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx
index a7ddca7867..119b78da16 100644
--- a/src/bundled/tasks/TaskView.test.tsx
+++ b/src/bundled/tasks/TaskView.test.tsx
@@ -10,6 +10,7 @@ import { TaskView } from "./TaskView";
afterEach(cleanup);
const viewer = "a".repeat(64);
+const tasksChannel = { id: "tasks", open: async () => "tasks" };
const chat = "11111111-1111-4111-8111-111111111111";
const revision = (id: string, title: string, content: object = {}) => ({
id,
@@ -55,7 +56,7 @@ it("keeps the person's text on a conflict, then saves over the newer version", a
render(
"shared"}
openConversation={() => {}}
@@ -85,7 +86,7 @@ it("shows their version when asked", async () => {
render(
"shared"}
openConversation={() => {}}
@@ -111,7 +112,7 @@ it("links the current chat only once it may be linked", async () => {
render(
{
+ const { session, signed } = setup(async () => "");
+ const open = vi.fn(async () => "made");
+ const onSaved = vi.fn();
+ render(
+ "shared"}
+ openConversation={() => {}}
+ onSaved={onSaved}
+ />,
+ );
+ fireEvent.change(screen.getByLabelText("Title"), {
+ target: { value: "Just a title" },
+ });
+ expect(open).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Create task" }));
+ await vi.waitFor(() => expect(onSaved).toHaveBeenCalled());
+ expect(open).toHaveBeenCalledOnce();
+ expect(signed[0]?.tags).toContainEqual(["h", "made"]);
+});
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index 278e5f050a..1050fef1d1 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -36,6 +36,7 @@ import {
type TaskStatus,
} from "./model";
import { StatusIcon } from "./StatusIcon";
+import type { TasksChannel } from "./react";
import { saveTask } from "./store";
import type { ChatShareOutcome } from "../../features/solo/share-requests";
import styles from "./Tasks.module.css";
@@ -70,15 +71,14 @@ const fieldsOf = (task: Task): TaskFields => ({
export type TaskViewProps = {
session: RelaySession;
- /** The tasks channel. */
- channel: string;
+ channel: TasksChannel;
/** The task's current revision; undefined starts a new task. */
task: Task | undefined;
/** The conversation this view sits beside, which "Link this chat" links. */
currentChat?: string | undefined;
/** Resolves "shared" once `channelId` may be linked; a private Solo chat
* first asks its owner to make it View only. */
- readyToLink(channelId: string): Promise;
+ readyToLink(channelId: string, task: string): Promise;
openConversation(channelId: string): void;
onSaved(task: Task): void;
/** Conversations a new task starts linked to, already cleared to link. */
@@ -109,12 +109,15 @@ export function TaskView(props: TaskViewProps) {
for (const added of fields.links.filter(
(link) => !base?.links.includes(link),
)) {
- const outcome = await props.readyToLink(added);
+ const outcome = await props.readyToLink(added, fields.title);
if (outcome !== "shared") return { status: "declined", outcome };
}
+ // The community's first saved task makes its tasks channel.
+ const target =
+ channel.id ?? (await channel.open(AbortSignal.timeout(30_000)));
const result = await saveTask(
session,
- channel,
+ target,
fields,
base,
undefined,
diff --git a/src/bundled/tasks/TasksGate.tsx b/src/bundled/tasks/TasksGate.tsx
index 58a0ed2065..7ba08649bb 100644
--- a/src/bundled/tasks/TasksGate.tsx
+++ b/src/bundled/tasks/TasksGate.tsx
@@ -2,20 +2,20 @@ import type { ReactNode } from "react";
import type { RelaySession } from "../../features/relay/session";
import { Button } from "../../shared/design-system/ui/Button";
import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion";
-import { useTasksChannel } from "./react";
+import { type TasksChannel, useTasksChannel } from "./react";
import styles from "./Tasks.module.css";
-/** Opens the community's tasks channel before showing `children`, making it
- * on the community's first use. The page and the panel share it. */
+/** Looks up the community's tasks channel before showing `children`. The
+ * page and the panel share it; the first save makes it. */
export function TasksGate({
session,
children,
}: {
session: RelaySession;
- children(channel: string): ReactNode;
+ children(channel: TasksChannel): ReactNode;
}) {
const channel = useTasksChannel(session);
- if (channel.status === "found") return children(channel.channelId);
+ if (channel.status === "ready") return children(channel.channel);
return (
- readyToLink(connection.session, sharing, channelId)
+ readyToLink={(channelId, task) =>
+ readyToLink(connection.session, sharing, channelId, { task })
}
openConversation={(channelId) =>
void navigator.open({
@@ -165,11 +165,11 @@ function TaskBoard({
openConversation,
}: {
session: RelaySession;
- channel: string;
+ channel: TasksChannel;
readyToLink: TaskViewLink;
openConversation(channelId: string): void;
}) {
- const state = useTasksWithSaved(session, channel);
+ const state = useTasksWithSaved(session, channel.id);
const mine = useMyChannels(session);
const [filter, setFilter] = useState(allOpen);
const [selected, setSelected] = useState();
diff --git a/src/bundled/tasks/TasksPanel.tsx b/src/bundled/tasks/TasksPanel.tsx
index 2986ffb54b..8bf1644b98 100644
--- a/src/bundled/tasks/TasksPanel.tsx
+++ b/src/bundled/tasks/TasksPanel.tsx
@@ -18,7 +18,7 @@ import {
import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
import { useToastNotification } from "../../shared/design-system/ui/Toast";
import { isOpenStatus, type Task } from "./model";
-import { useTasksWithSaved } from "./react";
+import { type TasksChannel, useTasksWithSaved } from "./react";
import { saveTask } from "./store";
import { StatusIcon } from "./StatusIcon";
import { TaskView, type TaskViewProps } from "./TaskView";
@@ -37,12 +37,11 @@ export function TasksPanel({
openConversation,
}: {
session: RelaySession;
- /** The tasks channel. */
- channel: string;
+ channel: TasksChannel;
/** The conversation this panel sits beside. */
chat: string;
} & Pick) {
- const state = useTasksWithSaved(session, channel);
+ const state = useTasksWithSaved(session, channel.id);
const notify = useToastNotification();
// A new task carries the links it starts with; consent waits for Create.
const [open, setOpen] = useState();
@@ -54,8 +53,8 @@ export function TasksPanel({
.filter((task) => isOpenStatus(task.status) && !task.links.includes(chat))
.sort((a, b) => b.updatedAt - a.updatedAt)
.slice(0, LINK_CHOICES);
- const cleared = async () => {
- const outcome = await readyToLink(chat);
+ const cleared = async (task: Task) => {
+ const outcome = await readyToLink(chat, task.title);
if (outcome === "unavailable")
notify("Only this chat’s owner can link it to a task.", "error");
return outcome === "shared";
@@ -64,10 +63,12 @@ export function TasksPanel({
if (linking) return;
setLinking(true);
try {
- if (!(await cleared())) return;
+ if (!(await cleared(task))) return;
+ // A task to link to means the tasks channel exists.
+ if (!channel.id) return;
const result = await saveTask(
session,
- channel,
+ channel.id,
{ ...task, links: [...task.links, chat] },
task,
);
diff --git a/src/bundled/tasks/index.tsx b/src/bundled/tasks/index.tsx
index d20057a2c1..86b03976e0 100644
--- a/src/bundled/tasks/index.tsx
+++ b/src/bundled/tasks/index.tsx
@@ -94,8 +94,8 @@ export const apply: PluginModule["apply"] = (ctx) => {
session={session}
channel={channel}
chat={channelContext.channelId}
- readyToLink={(channelId) =>
- readyToLink(session, sharing(), channelId)
+ readyToLink={(channelId, task) =>
+ readyToLink(session, sharing(), channelId, { task })
}
openConversation={(channelId) =>
void ctx.navigation.open({
diff --git a/src/bundled/tasks/linking.test.ts b/src/bundled/tasks/linking.test.ts
index 71667682e2..4ee81643b4 100644
--- a/src/bundled/tasks/linking.test.ts
+++ b/src/bundled/tasks/linking.test.ts
@@ -15,12 +15,24 @@ it("asks the owner only before linking a Solo chat that isn't public", async ()
{ id: "unknown", channelType: "solo" },
{ id: "channel", channelType: "stream", visibility: "private" },
]);
- expect(await readyToLink(relay, sharing, "channel")).toBe("shared");
- expect(await readyToLink(relay, sharing, "shared")).toBe("shared");
- expect(await readyToLink(relay, sharing, "elsewhere")).toBe("shared");
+ expect(await readyToLink(relay, sharing, "channel", { task: "T" })).toBe(
+ "shared",
+ );
+ expect(await readyToLink(relay, sharing, "shared", { task: "T" })).toBe(
+ "shared",
+ );
+ expect(await readyToLink(relay, sharing, "elsewhere", { task: "T" })).toBe(
+ "shared",
+ );
expect(requestShare).not.toHaveBeenCalled();
- expect(await readyToLink(relay, sharing, "solo")).toBe("cancelled");
- expect(await readyToLink(relay, sharing, "unknown")).toBe("cancelled");
+ expect(await readyToLink(relay, sharing, "solo", { task: "T" })).toBe(
+ "cancelled",
+ );
+ expect(await readyToLink(relay, sharing, "unknown", { task: "T" })).toBe(
+ "cancelled",
+ );
expect(requestShare).toHaveBeenCalledTimes(2);
- expect(await readyToLink(relay, undefined, "solo")).toBe("unavailable");
+ expect(await readyToLink(relay, undefined, "solo", { task: "T" })).toBe(
+ "unavailable",
+ );
});
diff --git a/src/bundled/tasks/linking.ts b/src/bundled/tasks/linking.ts
index 98c1c5594f..fdde2fbc35 100644
--- a/src/bundled/tasks/linking.ts
+++ b/src/bundled/tasks/linking.ts
@@ -7,12 +7,17 @@ import type {
ChatSharing,
} from "../../features/solo/share-requests";
-/** Whether `channelId` may be linked now, asking to share it when needed. */
+/** Whether `channelId` may be linked to the task titled `task`, asking to
+ * share it when needed. `agent` names the agent asking, if one is. */
export async function readyToLink(
session: RelaySession,
sharing: ChatSharing | undefined,
channelId: string,
- signal?: AbortSignal,
+ options: Readonly<{
+ task: string;
+ agent?: string | undefined;
+ signal?: AbortSignal | undefined;
+ }>,
): Promise {
const channel = session.channels
.list()
@@ -21,6 +26,11 @@ export async function readyToLink(
if (channel?.channelType !== "solo" || channel.visibility === "public")
return "shared";
return sharing
- ? sharing.requestShare(session, channelId, { signal })
+ ? sharing.requestShare(session, channelId, {
+ signal: options.signal,
+ reason: options.agent
+ ? `Your agent ${options.agent} wants to link it to the task “${options.task}”.`
+ : `To link it to the task “${options.task}”.`,
+ })
: "unavailable";
}
diff --git a/src/bundled/tasks/react.ts b/src/bundled/tasks/react.ts
index 829884ce62..8031e924b3 100644
--- a/src/bundled/tasks/react.ts
+++ b/src/bundled/tasks/react.ts
@@ -8,20 +8,27 @@ import {
import type { RelaySession } from "../../features/relay/session";
import type { Task } from "./model";
import { type TasksState, type TasksView, watchTasks } from "./store";
-import { openTasksChannel } from "./tasks-channel";
+import { findTasksChannel, openTasksChannel } from "./tasks-channel";
const loadingState: TasksState = { status: "loading", tasks: [] };
-const loading: TasksView = {
- snapshot: () => loadingState,
+const still = (state: TasksState): TasksView => ({
+ snapshot: () => state,
subscribe: () => () => {},
dispose: () => {},
-};
+});
+const loading = still(loadingState);
+/** A community nobody has saved a task in yet. */
+const none = still({ status: "live", tasks: [] });
/** Every current task in `channel`, live while mounted. The watch starts in
* an effect so each mount owns, and disposes, exactly the one it opened. */
-export function useTasks(session: RelaySession, channel: string) {
+export function useTasks(session: RelaySession, channel: string | undefined) {
const [view, setView] = useState(loading);
useEffect(() => {
+ if (!channel) {
+ setView(none);
+ return;
+ }
const next = watchTasks(session, channel);
setView(next);
return next.dispose;
@@ -32,7 +39,10 @@ export function useTasks(session: RelaySession, channel: string) {
/** Tasks from the live view, with this device's saves shown until the
* relay's copy has them: the same revision, or a strictly newer one. A tie
* keeps the save, the newest this device knows of. */
-export function useTasksWithSaved(session: RelaySession, channel: string) {
+export function useTasksWithSaved(
+ session: RelaySession,
+ channel: string | undefined,
+) {
const state = useTasks(session, channel);
const [saved, setSavedMap] = useState>(new Map());
const setSaved = useCallback(
@@ -57,23 +67,30 @@ export function useTasksWithSaved(session: RelaySession, channel: string) {
return { ...state, tasks, setSaved };
}
+/** The community's tasks channel as the page and panel hold it: `id` once
+ * someone has saved a task, and `open` to make it on the first save. */
+export type TasksChannel = Readonly<{
+ id: string | undefined;
+ open(signal: AbortSignal): Promise;
+}>;
+
export type TasksChannelState =
| Readonly<{ status: "loading" }>
| Readonly<{ status: "error"; error: string; retry(): void }>
- | Readonly<{ status: "found"; channelId: string }>;
+ | Readonly<{ status: "ready"; channel: TasksChannel }>;
-/** The community's tasks channel, made on its first use. */
+/** The community's tasks channel, looked up but never made by looking. */
export function useTasksChannel(session: RelaySession): TasksChannelState {
const [attempt, setAttempt] = useState(0);
const [result, setResult] = useState<
- { channelId: string } | { error: string } | undefined
+ { channelId: string | undefined } | { error: string } | undefined
>();
const retry = useCallback(() => setAttempt((count) => count + 1), []);
// biome-ignore lint/correctness/useExhaustiveDependencies: a retry is a new attempt.
useEffect(() => {
const controller = new AbortController();
setResult(undefined);
- openTasksChannel(session, controller.signal).then(
+ findTasksChannel(session, controller.signal).then(
(channelId) => !controller.signal.aborted && setResult({ channelId }),
(reason: unknown) =>
!controller.signal.aborted &&
@@ -84,7 +101,20 @@ export function useTasksChannel(session: RelaySession): TasksChannelState {
);
return () => controller.abort();
}, [session, attempt]);
+ const channelId =
+ result && "channelId" in result ? result.channelId : undefined;
+ const channel = useMemo(
+ () => ({
+ id: channelId,
+ async open(signal) {
+ const id = await openTasksChannel(session, signal);
+ setResult({ channelId: id });
+ return id;
+ },
+ }),
+ [session, channelId],
+ );
if (!result) return { status: "loading" };
if ("error" in result) return { status: "error", error: result.error, retry };
- return { status: "found", channelId: result.channelId };
+ return { status: "ready", channel };
}
diff --git a/src/bundled/tasks/tasks-channel.test.ts b/src/bundled/tasks/tasks-channel.test.ts
index e52e469e53..3407902d46 100644
--- a/src/bundled/tasks/tasks-channel.test.ts
+++ b/src/bundled/tasks/tasks-channel.test.ts
@@ -57,7 +57,7 @@ function fixture(byCreator: Record) {
},
channelCreation: { create },
} as unknown as RelaySession;
- return { session, create };
+ return { session, create, events };
}
it("uses the community's oldest open tasks channel, whoever made it", async () => {
@@ -88,3 +88,42 @@ it("makes the channel on the community's first use", async () => {
}),
);
});
+
+it("makes one channel when the page, panel and tools open together", async () => {
+ const { session, create } = fixture({});
+ const signal = new AbortController().signal;
+ const opened = await Promise.all([
+ openTasksChannel(session, signal),
+ openTasksChannel(session, signal),
+ openTasksChannel(session, signal),
+ ]);
+ expect(opened).toEqual(["mine", "mine", "mine"]);
+ expect(create).toHaveBeenCalledOnce();
+});
+
+it("lets one caller stop waiting without failing the others", async () => {
+ const { session, create } = fixture({});
+ const leaving = new AbortController();
+ const left = openTasksChannel(session, leaving.signal);
+ const staying = openTasksChannel(session, new AbortController().signal);
+ leaving.abort();
+ await expect(left).rejects.toThrow();
+ expect(await staying).toBe("mine");
+ expect(create).toHaveBeenCalledOnce();
+});
+
+it("converges on the older channel when two first saves race", async () => {
+ const byCreator: Record = {};
+ const { session, events } = fixture(byCreator);
+ // Bob's channel lands, older, while Alice is creating hers.
+ const create = session.channelCreation.create as ReturnType;
+ create.mockImplementationOnce(async () => {
+ byCreator[bob] = [channel("bobs", bob, 3)];
+ byCreator[alice] = [channel("mine", alice, 9)];
+ events.push(metadata("bobs", bob), metadata("mine", alice));
+ return "mine";
+ });
+ expect(await openTasksChannel(session, new AbortController().signal)).toBe(
+ "bobs",
+ );
+});
diff --git a/src/bundled/tasks/tasks-channel.ts b/src/bundled/tasks/tasks-channel.ts
index f9cb46113e..2d07f077eb 100644
--- a/src/bundled/tasks/tasks-channel.ts
+++ b/src/bundled/tasks/tasks-channel.ts
@@ -1,8 +1,11 @@
// The community's tasks live in one open NIP-CL system channel: hidden from
// channel lists, readable and writable by everyone in the community. The
-// first person to use Tasks creates it, and its creator owns it. Concurrent
-// first uses can each create one; everyone uses the oldest (NIP-CL "Choosing
-// one channel"), so they converge before any task is saved.
+// first person to save a task creates it, and its creator owns it; looking
+// never does. Concurrent first saves can each create one; everyone uses the
+// oldest (NIP-CL "Choosing one channel"), and each creator looks again after
+// creating, so they converge before any task is saved. What remains: a
+// connection keeps the channel it found, so a channel archived later, or more
+// than MAX_CREATORS racing creators, is only resolved again on reconnect.
import {
channelIdentity,
compareChannelAge,
@@ -26,6 +29,11 @@ const isTasksChannel = (channel: ChannelSummary) =>
// Once found, a community's tasks channel stays put for that connection, so
// each panel and tool call doesn't look it up again.
const found = new WeakMap();
+// One creation per connection at a time: the page, the panel and agent tools
+// opening together share it.
+const opening = new WeakMap>();
+/** How long one shared creation may take, whoever is waiting for it. */
+const OPEN_TIMEOUT = 30_000;
/** The community's tasks channel, or undefined when nobody has made one.
* Throws when it can't tell. */
@@ -85,11 +93,25 @@ export async function findTasksChannel(
return oldest?.id;
}
-/** The tasks channel, created when this is the community's first use. */
-export async function openTasksChannel(
+/** The tasks channel, created when this is the community's first save. */
+export function openTasksChannel(
session: RelaySession,
signal: AbortSignal,
): Promise {
+ signal.throwIfAborted();
+ let shared = opening.get(session);
+ if (!shared) {
+ shared = create(session, AbortSignal.timeout(OPEN_TIMEOUT));
+ opening.set(session, shared);
+ const clear = () => {
+ if (opening.get(session) === shared) opening.delete(session);
+ };
+ shared.then(clear, clear);
+ }
+ return untilAborted(shared, signal);
+}
+
+async function create(session: RelaySession, signal: AbortSignal) {
const existing = await findTasksChannel(session, signal);
if (existing) return existing;
await session.channelCreation.create({
@@ -105,3 +127,14 @@ export async function openTasksChannel(
if (!created) throw new Error("Tasks isn’t ready yet. Try again.");
return created;
}
+
+/** `work`, unless `signal` aborts first; the work itself goes on for others. */
+function untilAborted(work: Promise, signal: AbortSignal): Promise {
+ return new Promise((resolve, reject) => {
+ const stop = () => reject(signal.reason);
+ signal.addEventListener("abort", stop, { once: true });
+ work
+ .then(resolve, reject)
+ .finally(() => signal.removeEventListener("abort", stop));
+ });
+}
diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts
index 07f8d2c6a3..db729cdfb5 100644
--- a/src/bundled/tasks/tools.test.ts
+++ b/src/bundled/tasks/tools.test.ts
@@ -4,8 +4,10 @@ import type { RelaySession } from "../../features/relay/session";
import { TASK_TYPE } from "./model";
import { addTaskTools } from "./tools";
+const channel = vi.hoisted(() => ({ id: "tasks" as string | undefined }));
vi.mock("./tasks-channel", () => ({
- openTasksChannel: async () => "tasks",
+ findTasksChannel: async () => channel.id,
+ openTasksChannel: async () => (channel.id = "tasks"),
}));
const viewer = "a".repeat(64);
@@ -67,6 +69,8 @@ function setup(
{
relay: () =>
({ snapshot: () => ({ status: "ready", session }) }) as never,
+ snapshot: () =>
+ ({ agents: [{ key: "agent", name: "Fizz" }], running: [] }) as never,
addTool: (tool) => {
tools.set(tool.name, (args) =>
tool.call(
@@ -137,3 +141,55 @@ it("reapplies an update over someone else's newer save", async () => {
status: "done",
});
});
+
+it("names the agent and the task when it asks to share another chat", async () => {
+ const other = "22222222-2222-4222-8222-222222222222";
+ const { tools, requestShare } = setup(
+ async () => "",
+ () => [head("d".repeat(64), { status: "open" })],
+ );
+ await tools.get("tasks_link")?.({ id: "task-1", channel: solo });
+ expect(requestShare).toHaveBeenCalledWith(
+ expect.anything(),
+ solo,
+ expect.objectContaining({
+ reason: "Your agent Fizz wants to link it to the task “Fix the header”.",
+ }),
+ );
+ // A conversation that isn't the owner's Solo chat links without asking.
+ requestShare.mockClear();
+ await tools.get("tasks_link")?.({ id: "task-1", channel: other });
+ expect(requestShare).not.toHaveBeenCalled();
+});
+
+it("reads without making the tasks channel", async () => {
+ channel.id = undefined;
+ try {
+ const { tools, signed } = setup(
+ async () => "",
+ () => [],
+ );
+ expect(await tools.get("tasks_read")?.({})).toBe(
+ "No tasks yet in this community.",
+ );
+ expect(channel.id).toBeUndefined();
+ await tools.get("tasks_create")?.({ title: "First", link: false });
+ expect(channel.id).toBe("tasks");
+ expect(signed).toHaveLength(1);
+ } finally {
+ channel.id = "tasks";
+ }
+});
+
+it("tells the agent which id to check after an unclear create", async () => {
+ const { tools, signed } = setup(
+ async () => {
+ throw new Error("network");
+ },
+ () => [],
+ );
+ const failed = tools.get("tasks_create")?.({ title: "Fix", link: false });
+ await expect(failed).rejects.toThrow(/saved as task [0-9a-f-]{36}/);
+ const id = signed[0]?.tags.find((tag) => tag[0] === "d")?.[1];
+ await expect(failed).rejects.toThrow(id);
+});
diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts
index 6cef301a20..4882fda88f 100644
--- a/src/bundled/tasks/tools.ts
+++ b/src/bundled/tasks/tools.ts
@@ -23,14 +23,23 @@ import {
taskOf,
} from "./model";
import { saveTask } from "./store";
-import { openTasksChannel } from "./tasks-channel";
+import { findTasksChannel, openTasksChannel } from "./tasks-channel";
-type Agents = Pick;
+type Agents = Pick;
+type Client = { key: string; signal?: AbortSignal | undefined };
type Args = Record;
/** How many times an agent's change is reapplied over someone else's edit. */
const ATTEMPTS = 3;
const LIST_LIMIT = 50;
+/** How long one step of relay work may take. Waiting on the owner's
+ * confirmation has no deadline but the agent's own. */
+const STEP_TIMEOUT = 60_000;
+
+const deadline = (client: Client) =>
+ client.signal
+ ? AbortSignal.any([client.signal, AbortSignal.timeout(STEP_TIMEOUT)])
+ : AbortSignal.timeout(STEP_TIMEOUT);
const statusOf = (value: unknown): TaskStatus | undefined =>
statuses.find((status) => status === value);
@@ -82,14 +91,27 @@ export function addTaskTools(
agents: Agents,
sharing: () => ChatSharing | undefined,
) {
- /** The owner's session for this agent's community, and its tasks channel. */
- async function open(client: { key: string; signal?: AbortSignal }) {
+ /** The owner's session for this agent's community. */
+ function sessionOf(client: Client) {
const relay = agents.relay(client.key)?.snapshot();
if (relay?.status !== "ready")
throw new Error("Tasks need this conversation's community");
- const signal = client.signal ?? AbortSignal.timeout(60_000);
- const channel = await openTasksChannel(relay.session, signal);
- return { session: relay.session, channel, signal };
+ return relay.session;
+ }
+
+ /** The community's tasks channel; reading never makes it. */
+ async function lookup(client: Client) {
+ const session = sessionOf(client);
+ const signal = deadline(client);
+ const channel = await findTasksChannel(session, signal);
+ return { session, channel, signal };
+ }
+
+ /** The agent's name, so the owner's confirmation says who asks. */
+ function agentName(client: Client) {
+ const { agents: here, running } = agents.snapshot();
+ return [...here, ...running].find((agent) => agent.key === client.key)
+ ?.name;
}
async function current(
@@ -125,12 +147,17 @@ export function addTaskTools(
}
async function cleared(
+ client: Client,
session: RelaySession,
chat: string,
- signal: AbortSignal,
+ task: string,
) {
- const outcome = await readyToLink(session, sharing(), chat, signal);
- signal.throwIfAborted();
+ const outcome = await readyToLink(session, sharing(), chat, {
+ task,
+ agent: agentName(client),
+ signal: client.signal,
+ });
+ client.signal?.throwIfAborted();
if (outcome === "cancelled")
throw new Error(
"Your owner chose not to share this chat, so it wasn't linked.",
@@ -142,7 +169,7 @@ export function addTaskTools(
agents.addTool({
name: "tasks_create",
description:
- "Creates a task in this community's Tasks: a title, a Markdown description of what was noticed and why, and image links. Links this conversation unless link is false. Linking a private Solo chat makes it View only for the community, so your owner sees a confirmation first; nothing is created if they decline.",
+ "Creates a task in this community's Tasks: a title, a Markdown description of what was noticed and why, and image links. Only the title is required. Everyone in the community can read a task, so never put in it what a private conversation shouldn't share. Links this conversation unless link is false. Linking a private Solo chat makes it View only for the community, so your owner sees a confirmation first; nothing is created if they decline.",
inputSchema: {
type: "object",
properties: {
@@ -174,15 +201,24 @@ export function addTaskTools(
images: imagesArg(args) ?? [],
links: chat ? [chat] : [],
});
- const { session, channel, signal } = await open(client);
- if (chat) await cleared(session, chat, signal);
+ const session = sessionOf(client);
+ if (chat) await cleared(client, session, chat, fields.title);
+ const signal = deadline(client);
+ const channel = await openTasksChannel(session, signal);
+ // Named before saving, so a retry after an unclear outcome can check.
+ const id = crypto.randomUUID();
const result = await saveTask(
session,
channel,
fields,
undefined,
signal,
- );
+ id,
+ ).catch((reason: unknown) => {
+ throw new Error(
+ `${reason instanceof Error ? reason.message : "Couldn't create the task."} It may still have been saved as task ${id}: read it with tasks_read before creating it again.`,
+ );
+ });
if (result.status !== "saved")
throw new Error("Couldn't create the task");
return `Created task ${result.task.id}.\n\n${describe(result.task, session)}`;
@@ -210,8 +246,10 @@ export function addTaskTools(
additionalProperties: false,
},
async call(client, context, args) {
- const { session, channel, signal } = await open(client);
+ const { session, channel, signal } = await lookup(client);
const id = textArg(args, "id");
+ if (!channel)
+ return id ? `No task ${id} here` : "No tasks yet in this community.";
if (id)
return describe(await current(session, channel, id, signal), session);
const read = session.snapshotRead;
@@ -286,7 +324,8 @@ export function addTaskTools(
if (args.status !== undefined && !status)
throw new Error(`status must be one of ${statuses.join(", ")}`);
const images = imagesArg(args);
- const { session, channel, signal } = await open(client);
+ const { session, channel, signal } = await lookup(client);
+ if (!channel) throw new Error(`No task ${id} here`);
const task = await change(
session,
channel,
@@ -326,11 +365,13 @@ export function addTaskTools(
const chat = textArg(args, "channel") ?? context.channel;
if (!isChannelId(chat)) throw new Error("channel must be a channel id");
const unlink = args.unlink === true;
- const { session, channel, signal } = await open(client);
+ const found = await lookup(client);
+ const { session, channel } = found;
+ if (!channel) throw new Error(`No task ${id} here`);
if (!unlink) {
// The task must exist before the owner is asked to share for it.
- await current(session, channel, id, signal);
- await cleared(session, chat, signal);
+ const task = await current(session, channel, id, found.signal);
+ await cleared(client, session, chat, task.title);
}
const task = await change(
session,
@@ -342,7 +383,7 @@ export function addTaskTools(
? base.links.filter((link) => link !== chat)
: [...base.links, chat],
}),
- signal,
+ deadline(client),
);
return `${unlink ? "Unlinked. Its access is unchanged." : "Linked."}\n\n${describe(task, session)}`;
},
diff --git a/src/features/solo/ShareRequestDialog.test.tsx b/src/features/solo/ShareRequestDialog.test.tsx
index c878967a5f..8f39e6c234 100644
--- a/src/features/solo/ShareRequestDialog.test.tsx
+++ b/src/features/solo/ShareRequestDialog.test.tsx
@@ -20,6 +20,7 @@ afterEach(cleanup);
const id = "11111111-1111-4111-8111-111111111111";
const viewer = "a".repeat(64);
+const asker = { requester: "Tasks" };
function fixture(
visibility: "public" | "private" = "private",
@@ -69,7 +70,7 @@ it("shows the app's confirmation and makes the chat View only only when confirme
const f = fixture();
const requests = createShareRequests();
render( );
- const outcome = requests.request(f.session, id);
+ const outcome = requests.request(f.session, id, asker);
expect(await screen.findByText("Share “Chat”?")).toBeTruthy();
expect(
screen.getByText(
@@ -92,7 +93,7 @@ it("changes nothing when the viewer cancels", async () => {
const f = fixture();
const requests = createShareRequests();
render( );
- const outcome = requests.request(f.session, id);
+ const outcome = requests.request(f.session, id, asker);
await userEvent.click(await screen.findByRole("button", { name: "Cancel" }));
expect(await outcome).toBe("cancelled");
expect(f.save).not.toHaveBeenCalled();
@@ -103,7 +104,7 @@ it("keeps the dialog open with the error so the viewer can retry", async () => {
f.failNext(true);
const requests = createShareRequests();
render( );
- const outcome = requests.request(f.session, id);
+ const outcome = requests.request(f.session, id, asker);
await userEvent.click(await screen.findByRole("button", { name: "Share" }));
expect((await screen.findByRole("alert")).textContent).toBe(
"Relay refused the change.",
@@ -117,7 +118,7 @@ it("resolves without a dialog when the chat is already open", async () => {
const f = fixture("public");
const requests = createShareRequests();
render( );
- expect(await requests.request(f.session, id)).toBe("shared");
+ expect(await requests.request(f.session, id, asker)).toBe("shared");
expect(requests.snapshot()).toEqual([]);
expect(screen.queryByText("Share “Chat”?")).toBeNull();
});
@@ -125,7 +126,7 @@ it("resolves without a dialog when the chat is already open", async () => {
it("refuses without a dialog for a chat the viewer does not own", async () => {
const f = fixture("private", "b".repeat(64));
const requests = createShareRequests();
- expect(await requests.request(f.session, id)).toBe("unavailable");
+ expect(await requests.request(f.session, id, asker)).toBe("unavailable");
expect(requests.snapshot()).toEqual([]);
expect(f.save).not.toHaveBeenCalled();
});
@@ -134,9 +135,9 @@ it("asks once for repeated requests about the same chat", async () => {
const f = fixture();
const requests = createShareRequests();
render( );
- const first = requests.request(f.session, id);
+ const first = requests.request(f.session, id, asker);
await screen.findByText("Share “Chat”?");
- const second = requests.request(f.session, id);
+ const second = requests.request(f.session, id, asker);
expect(requests.snapshot()).toHaveLength(1);
await userEvent.click(screen.getByRole("button", { name: "Share" }));
expect(await first).toBe("shared");
@@ -148,7 +149,9 @@ it("withdraws a plugin's request when the plugin stops", async () => {
const f = fixture();
const root = new Context();
const requests = createShareRequests();
- createChatSharingService(root, requests);
+ createChatSharingService(root, requests, (plugin) =>
+ plugin === "example.tasks" ? "Tasks" : plugin,
+ );
let sharing: ChatSharing | undefined;
const fiber = root
.extend({ pluginOwner: { id: "example.tasks", revision: "one" } })
@@ -173,7 +176,13 @@ it("withdraws a request when its caller's signal aborts", async () => {
const requests = createShareRequests();
render( );
const controller = new AbortController();
- const outcome = requests.request(f.session, id, undefined, controller.signal);
+ const outcome = requests.request(
+ f.session,
+ id,
+ asker,
+ undefined,
+ controller.signal,
+ );
await screen.findByText("Share “Chat”?");
act(() => controller.abort());
expect(await outcome).toBe("cancelled");
@@ -189,8 +198,51 @@ it("still shares after a StrictMode remount", async () => {
,
);
- const outcome = requests.request(f.session, id);
+ const outcome = requests.request(f.session, id, asker);
await userEvent.click(await screen.findByRole("button", { name: "Share" }));
expect(await outcome).toBe("shared");
expect(f.save).toHaveBeenCalledOnce();
});
+
+it("names who asks, their reason, and a chat without a name", async () => {
+ const f = fixture();
+ const requests = createShareRequests();
+ render( );
+ void requests.request(f.session, id, {
+ requester: "Tasks",
+ reason: "Your agent Fizz wants to link it to the task “Fix the header”.",
+ });
+ await screen.findByText("Share “Chat”?");
+ expect(
+ screen.getByText(/Tasks asked to change “Chat” from Private to View only/),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(
+ "Reason given: Your agent Fizz wants to link it to the task “Fix the header”.",
+ ),
+ ).toBeTruthy();
+});
+
+it("keeps sharing when its caller aborts after the viewer chose Share", async () => {
+ const f = fixture();
+ let finish!: () => void;
+ f.save.mockImplementationOnce(
+ () => new Promise((resolve) => (finish = resolve)),
+ );
+ const requests = createShareRequests();
+ render( );
+ const controller = new AbortController();
+ const outcome = requests.request(
+ f.session,
+ id,
+ asker,
+ undefined,
+ controller.signal,
+ );
+ await userEvent.click(await screen.findByRole("button", { name: "Share" }));
+ await vi.waitFor(() => expect(f.save).toHaveBeenCalledOnce());
+ act(() => controller.abort());
+ expect(screen.getByText("Share “Chat”?")).toBeTruthy();
+ await act(async () => finish());
+ expect(await outcome).toBe("shared");
+});
diff --git a/src/features/solo/ShareRequestDialog.tsx b/src/features/solo/ShareRequestDialog.tsx
index ad48dd93ce..2a25db14dd 100644
--- a/src/features/solo/ShareRequestDialog.tsx
+++ b/src/features/solo/ShareRequestDialog.tsx
@@ -41,11 +41,12 @@ function ShareRequestConfirmation({
}, []);
const decline = () => requests.settle(request.id, "cancelled");
const confirm = async () => {
- if (busy) return;
+ const signal = controller.current?.signal;
+ if (busy || !signal || signal.aborted) return;
setBusy(true);
setError("");
- const signal = controller.current?.signal;
- if (!signal || signal.aborted) return;
+ // The chat may become View only from here, so its caller can't withdraw.
+ requests.confirm(request.id);
try {
await shareSoloChatAccess(request.session, request.details.channelId, {
signal,
@@ -61,16 +62,19 @@ function ShareRequestConfirmation({
setBusy(false);
}
};
+ // A chat without a name is told apart by its id.
+ const chat = request.details.name
+ ? `“${request.details.name}”`
+ : `chat ${request.details.channelId.slice(0, 8)}`;
return (
- A plugin asked to change this chat from Private to View only.{" "}
+ {request.requester} asked to change {chat} from Private to View only.
+ {request.reason ? (
+ Reason given: {request.reason}
+ ) : null}
{soloShareDisclosure()}
>
}
diff --git a/src/features/solo/share-requests.ts b/src/features/solo/share-requests.ts
index d8d9539d28..6cc0d07339 100644
--- a/src/features/solo/share-requests.ts
+++ b/src/features/solo/share-requests.ts
@@ -13,15 +13,22 @@ export type ChatSharing = Readonly<{
* viewer confirms. Resolves `"shared"` once the chat is View only or public
* (at once, without a dialog, when it already is), `"cancelled"` when the
* viewer declines or the caller stops, and `"unavailable"` when the viewer
- * cannot share it. Never rejects. Aborting `signal` withdraws the request.
+ * cannot share it. Never rejects. Aborting `signal` withdraws the request
+ * until the viewer chooses Share; from then on only the viewer ends it.
+ * `reason` is one sentence the dialog shows as the caller's own words.
*/
requestShare(
session: RelaySession,
channelId: string,
- options?: Readonly<{ signal?: AbortSignal | undefined }>,
+ options?: ShareRequestOptions,
): Promise;
}>;
+export type ShareRequestOptions = Readonly<{
+ signal?: AbortSignal | undefined;
+ reason?: string | undefined;
+}>;
+
declare module "@deepseek-ai/cordis" {
interface Context {
/** Read with `ctx.reflect.get("chatSharing")` for old-host compatibility. */
@@ -34,8 +41,19 @@ export type ShareRequest = Readonly<{
id: string;
session: RelaySession;
details: ChannelDetails;
+ /** The asking plugin's name, as the app knows it. */
+ requester: string;
+ /** The caller's own one-sentence reason, if it gave one. */
+ reason?: string | undefined;
}>;
+/** Who asks and why, as the dialog shows them. */
+type Asker = Readonly<{ requester: string; reason?: string | undefined }>;
+
+const MAX_REASON = 200;
+const reasonOf = (reason: string | undefined) =>
+ reason?.replace(/\s+/g, " ").trim().slice(0, MAX_REASON) || undefined;
+
type Pending = ShareRequest & {
readonly done: Promise;
readonly resolve: (outcome: ChatShareOutcome) => void;
@@ -56,10 +74,14 @@ export function createShareRequests() {
const notify = () => {
for (const listener of listeners) listener();
};
+ // Requests the viewer chose Share on: their caller can no longer withdraw
+ // them, since the chat may already be View only.
+ const confirming = new Set();
const settle = (id: string, outcome: ChatShareOutcome) => {
const item = pending.find((entry) => entry.id === id);
if (!item) return;
pending = pending.filter((entry) => entry !== item);
+ confirming.delete(id);
item.controller.abort();
item.resolve(outcome);
notify();
@@ -68,6 +90,7 @@ export function createShareRequests() {
async function request(
session: RelaySession,
channelId: string,
+ asker: Asker,
lifetime?: (end: () => void) => () => void,
signal?: AbortSignal,
): Promise {
@@ -107,11 +130,22 @@ export function createShareRequests() {
const id = `share-${++next}`;
pending = [
...pending,
- { id, session, details, done, resolve, controller },
+ {
+ id,
+ session,
+ details,
+ requester: asker.requester,
+ reason: reasonOf(asker.reason),
+ done,
+ resolve,
+ controller,
+ },
];
controller.signal.addEventListener(
"abort",
- () => settle(id, "cancelled"),
+ () => {
+ if (!confirming.has(id)) settle(id, "cancelled");
+ },
{ once: true },
);
notify();
@@ -131,6 +165,10 @@ export function createShareRequests() {
return () => void listeners.delete(listener);
},
settle,
+ /** The viewer chose Share: from now on only `settle` ends the request. */
+ confirm(id: string) {
+ if (pending.some((entry) => entry.id === id)) confirming.add(id);
+ },
};
}
@@ -138,6 +176,8 @@ export function createShareRequests() {
export function createChatSharingService(
ctx: Context,
requests: ShareRequests,
+ /** A plugin's display name from its id. */
+ pluginName: (id: string) => string,
): ChatSharing {
class ChatSharingService extends Service implements ChatSharing {
constructor() {
@@ -148,12 +188,17 @@ export function createChatSharingService(
requestShare(
session: RelaySession,
channelId: string,
- options?: Readonly<{ signal?: AbortSignal | undefined }>,
+ options?: ShareRequestOptions,
) {
const caller = this.ctx;
+ const owner = caller.pluginOwner?.id;
return requests.request(
session,
channelId,
+ {
+ requester: owner ? pluginName(owner) : "The app",
+ reason: options?.reason,
+ },
(end) => {
const stop = caller.effect(() => end);
return () => void stop();
From 8af55435c0bc3ba8523e0969cb43a11a427abc79 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sat, 14 Nov 2026 15:41:36 -1000
Subject: [PATCH 08/18] fix(tasks): list Tasks in the desktop plugin catalog
The desktop catalog comes from the plugin manager's bundled manifests, so
Tasks was missing there. It stays off by default.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
crates/plugin-manager/src/lib.rs | 2 ++
crates/plugin-manager/tests/management.rs | 1 +
2 files changed, 3 insertions(+)
diff --git a/crates/plugin-manager/src/lib.rs b/crates/plugin-manager/src/lib.rs
index d0adc67712..a31a2ded3f 100644
--- a/crates/plugin-manager/src/lib.rs
+++ b/crates/plugin-manager/src/lib.rs
@@ -454,6 +454,8 @@ pub fn bundled_manifests() -> Vec {
.expect("valid pairing manifest"),
serde_json::from_str(include_str!("../../../src/bundled/todos/manifest.json"))
.expect("todos manifest"),
+ serde_json::from_str(include_str!("../../../src/bundled/tasks/manifest.json"))
+ .expect("tasks manifest"),
serde_json::from_str(include_str!("../../../src/bundled/diffs/manifest.json"))
.expect("bundled diffs manifest"),
serde_json::from_str(include_str!("../../../src/bundled/mermaid/manifest.json"))
diff --git a/crates/plugin-manager/tests/management.rs b/crates/plugin-manager/tests/management.rs
index c4759625ee..26c72b8baf 100644
--- a/crates/plugin-manager/tests/management.rs
+++ b/crates/plugin-manager/tests/management.rs
@@ -1375,6 +1375,7 @@ fn bundled_defaults_preserve_saved_choices_and_only_channels_is_required() {
id,
"buzz.pi"
| "buzz.todos"
+ | "buzz.tasks"
| "buzz.usage"
| "buzz.relay-notes"
| "buzz.reminders"
From 74f7b2911a762620127e019df9f8eebf4f88e5f5 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sun, 15 Nov 2026 21:46:35 -0800
Subject: [PATCH 09/18] feat(tasks): give each task one home, and group tasks
by project
A task now lives in a project, channel or chat, and that place decides
who sees and edits it. The community-wide hidden tasks channel and the
Solo chat share request are gone: links live with the conversation they
point to and never change access.
- Four statuses and up to four people assigned; starting a task assigns you.
- The Tasks page groups and filters by project; a task opens beside the list.
- Moving a task names the places whose people gain or lose access.
- Task links in messages show the task's live title and status.
- Agents get find, create, update and comment. Create checks for an open
match first; Done or Cancelled needs evidence.
Comments wait on a host piece that can open the task's hidden conversation.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
docs/plugin-architecture.md | 30 -
src/app/App.tsx | 2 -
src/app/services.ts | 16 -
src/bundled/tasks/README.md | 17 +-
src/bundled/tasks/StatusIcon.tsx | 4 +-
src/bundled/tasks/TaskLink.tsx | 101 +++
src/bundled/tasks/TaskView.test.tsx | 135 ++-
src/bundled/tasks/TaskView.tsx | 813 +++++++++++++-----
src/bundled/tasks/Tasks.module.css | 68 +-
src/bundled/tasks/TasksGate.tsx | 39 -
src/bundled/tasks/TasksPage.tsx | 405 +++++----
src/bundled/tasks/TasksPanel.tsx | 116 +--
src/bundled/tasks/conversation.ts | 36 +
src/bundled/tasks/index.tsx | 71 +-
src/bundled/tasks/linking.test.ts | 38 -
src/bundled/tasks/linking.ts | 36 -
src/bundled/tasks/links.ts | 143 +++
src/bundled/tasks/model.test.ts | 105 ++-
src/bundled/tasks/model.ts | 94 +-
src/bundled/tasks/places.test.ts | 61 ++
src/bundled/tasks/places.ts | 118 +++
src/bundled/tasks/react.ts | 144 ++--
src/bundled/tasks/route.test.ts | 17 +
src/bundled/tasks/route.ts | 39 +
src/bundled/tasks/similar.ts | 47 +
src/bundled/tasks/store.test.ts | 129 +--
src/bundled/tasks/store.ts | 123 ++-
src/bundled/tasks/tasks-channel.test.ts | 129 ---
src/bundled/tasks/tasks-channel.ts | 140 ---
src/bundled/tasks/tools.test.ts | 286 +++---
src/bundled/tasks/tools.ts | 506 ++++++-----
src/features/solo/ShareRequestDialog.test.tsx | 248 ------
src/features/solo/ShareRequestDialog.tsx | 106 ---
src/features/solo/share-requests.ts | 211 -----
34 files changed, 2371 insertions(+), 2202 deletions(-)
create mode 100644 src/bundled/tasks/TaskLink.tsx
delete mode 100644 src/bundled/tasks/TasksGate.tsx
create mode 100644 src/bundled/tasks/conversation.ts
delete mode 100644 src/bundled/tasks/linking.test.ts
delete mode 100644 src/bundled/tasks/linking.ts
create mode 100644 src/bundled/tasks/links.ts
create mode 100644 src/bundled/tasks/places.test.ts
create mode 100644 src/bundled/tasks/places.ts
create mode 100644 src/bundled/tasks/route.test.ts
create mode 100644 src/bundled/tasks/route.ts
create mode 100644 src/bundled/tasks/similar.ts
delete mode 100644 src/bundled/tasks/tasks-channel.test.ts
delete mode 100644 src/bundled/tasks/tasks-channel.ts
delete mode 100644 src/features/solo/ShareRequestDialog.test.tsx
delete mode 100644 src/features/solo/ShareRequestDialog.tsx
delete mode 100644 src/features/solo/share-requests.ts
diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md
index 945b330a97..62db444950 100644
--- a/docs/plugin-architecture.md
+++ b/docs/plugin-architecture.md
@@ -405,36 +405,6 @@ an animated GIF or WebP loses its animation; offer the whole image for those.
The host fetches the authenticated media and runs Vision's foreground instance
mask (`media_lift_subject`); the plugin never receives media credentials.
-### Asking to share a Solo chat
-
-A plugin that links or shows a viewer's private Solo chat to others asks the
-host to make it View only. Read the optional `chatSharing` service with
-`ctx.reflect.get("chatSharing")`; it is `undefined` on older hosts.
-
-```ts
-type ChatSharing = {
- requestShare(
- session: RelaySession,
- channelId: string,
- options?: { signal?: AbortSignal; reason?: string },
- ): Promise<"shared" | "cancelled" | "unavailable">;
-};
-```
-
-The host shows its own "Share this chat?" confirmation with the chat's name (or
-a short id), the asking plugin's name, the plugin's one-sentence `reason` as
-its own words, and the View only disclosure; nothing changes unless the viewer
-confirms. Only the
-viewer's own Solo chat can be shared (`"unavailable"` otherwise), and one
-already View only or public resolves `"shared"` with no dialog. Aborting
-`signal`, or the plugin stopping, withdraws the request as `"cancelled"` until
-the viewer chooses Share; from then on only the viewer ends it, so the outcome
-always matches the chat's access. Don't put a deadline on `signal`: the viewer
-answers in their own time. Agent
-tools that link chats call it too, so an agent can't skip the confirmation. Ask
-only as the change that needs it is saved, so declining never leaves a chat
-shared for nothing.
-
### Plugin installer
A plugin, such as a catalog or marketplace page, may ask the host to review a plugin
diff --git a/src/app/App.tsx b/src/app/App.tsx
index 770841db2c..331703994a 100644
--- a/src/app/App.tsx
+++ b/src/app/App.tsx
@@ -31,7 +31,6 @@ import { MediaMenuDownloadNotice } from "../features/messages/MediaDownloadActio
import { CreationReview } from "../bundled/agents/CreationReview";
import { UpdateReview } from "../bundled/agents/UpdateReview";
import { TeamUpdateReview } from "../bundled/agents/TeamUpdateReview";
-import { ShareRequestDialog } from "../features/solo/ShareRequestDialog";
import { InterruptedNotice } from "../features/agents/InterruptedNotice";
import {
useCallback,
@@ -771,7 +770,6 @@ function ConnectedAppContent({ services }: { services: AppServices }) {
-
{!settings && startup === "recovery" ? (
) : !settings &&
diff --git a/src/app/services.ts b/src/app/services.ts
index 02423fbd6b..a7bcc0f12e 100644
--- a/src/app/services.ts
+++ b/src/app/services.ts
@@ -73,10 +73,6 @@ import {
createPluginInstallerService,
} from "../plugins/installer";
import { withTimeout } from "../plugins/timeout";
-import {
- createChatSharingService,
- createShareRequests,
-} from "../features/solo/share-requests";
import { createExternalApps } from "../features/agents/external-connection";
export function createServices() {
@@ -115,17 +111,6 @@ export function createServices() {
navigation.open({ version: 1, kind: "settings", section: "plugins" }),
});
createPluginInstallerService(ctx, { core: pluginInstallCore });
- const shareRequests = createShareRequests();
- createChatSharingService(ctx, shareRequests, (id) => {
- const { configuration } = plugins.snapshot();
- const name =
- configuration.status === "ready"
- ? configuration.catalog.plugins.find(
- (plugin) => plugin.manifest.id === id,
- )?.manifest.name
- : undefined;
- return name?.replace(/\s+/g, " ").trim().slice(0, 80) || id;
- });
const sidebarScope = new SidebarScopeService(ctx);
const sidebarRows = new SidebarRowsService(ctx);
const panels = new PanelsService(ctx);
@@ -336,7 +321,6 @@ export function createServices() {
pages,
sidebarSections,
pluginInstallRequests,
- shareRequests,
sidebarScope,
sidebarRows,
panels,
diff --git a/src/bundled/tasks/README.md b/src/bundled/tasks/README.md
index 19b2706cd3..bd6348f3a1 100644
--- a/src/bundled/tasks/README.md
+++ b/src/bundled/tasks/README.md
@@ -1,15 +1,18 @@
# Tasks
-A task holds the context for a piece of work and links the conversations about it, so anyone can pick it up later.
+A task holds the context for a piece of work, so anyone can pick it up later.
## Getting started
-1. Open **Tasks** and choose **New task**, give it a title and a description, and add images if they help.
-2. In a chat or channel, choose **Tasks** in its header to see the tasks linked there, make one from the chat, or link the chat to an existing task.
+1. Open **Tasks** and choose **New task**. Give it a title, choose where it lives, and add a description and images if they help.
+2. In a chat or channel, choose **Tasks** in its header to see the tasks that live there or are linked there, make one, or link an existing one.
-You can also ask your agent to make a task from a conversation.
+You can also ask your agent to make a task from a conversation, or to find what you should work on.
-- Everyone in the community can see and edit every task.
-- Linking a private Solo chat makes it View only: anyone in the community can read it, and only its members can post. You confirm that first. Unlinking doesn't change it back.
-- Linking a private channel doesn't change who can read it. People who can't read it see only that a private channel is linked.
+- Every task lives in one place: a project, a channel or a chat. Whoever can open that place can see the task, and whoever can post there can edit it. Guests can only view.
+- The Tasks page groups tasks by project. A task in a channel or chat filed in a project shows under that project.
+- A task has a status (To do, In progress, Done or Cancelled) and up to four people assigned. Starting a task assigns you.
+- Moving a task changes who can see it. Before it moves, you see which places' people gain or lose access.
+- Linking a task to a conversation never changes who can see either one. Only people who can read the conversation see the link.
+- A task link in a message shows the task's title and status, and opens it. Creating a task posts nothing.
- If someone else saves a task while you're editing it, your text is kept and you choose what to save.
diff --git a/src/bundled/tasks/StatusIcon.tsx b/src/bundled/tasks/StatusIcon.tsx
index 3319dbcf6e..9ece83053b 100644
--- a/src/bundled/tasks/StatusIcon.tsx
+++ b/src/bundled/tasks/StatusIcon.tsx
@@ -10,13 +10,13 @@ import type { TaskStatus } from "./model";
export function StatusIcon({ status }: { status: TaskStatus }) {
const props = { size: 16, "aria-hidden": true } as const;
switch (status) {
- case "open":
+ case "todo":
return ;
case "in_progress":
return ;
case "done":
return ;
- case "wont_do":
+ case "cancelled":
return ;
}
}
diff --git a/src/bundled/tasks/TaskLink.tsx b/src/bundled/tasks/TaskLink.tsx
new file mode 100644
index 0000000000..82f491e548
--- /dev/null
+++ b/src/bundled/tasks/TaskLink.tsx
@@ -0,0 +1,101 @@
+// A task's link in a message: the task's live status and title in place of
+// the link, and a hover card with its details. Someone who can't see the task
+// sees only that it isn't available, never its title.
+import { useContext, useEffect, useMemo, useSyncExternalStore } from "react";
+import {
+ LinkInteractiveContext,
+ LinkLabelContext,
+ LinkPreviewContext,
+} from "../../features/conversation/LinkLabelContext";
+import type { RelayData } from "../../features/relay/service";
+import type { RelaySession } from "../../features/relay/session";
+import { Button } from "../../shared/design-system/ui/Button";
+import { LinkLabel } from "../links/InlineLink";
+import { statusLabels, type Task } from "./model";
+import { projectOf } from "./places";
+import { usePlaces, useTasks } from "./react";
+import { taskLinkId } from "./route";
+import { StatusIcon } from "./StatusIcon";
+import styles from "./Tasks.module.css";
+
+export function TaskLink({ url, relay }: { url: string; relay: RelayData }) {
+ const live = useContext(LinkInteractiveContext);
+ const connection = useSyncExternalStore(relay.subscribe, relay.snapshot);
+ const session =
+ live && connection.status === "ready" ? connection.session : undefined;
+ const state = useTasks(session);
+ const id = taskLinkId(url);
+ const task = state.tasks.find((item) => item.id === id);
+ const unavailable = !!session && state.status !== "loading" && !task;
+ const offer = useContext(LinkPreviewContext);
+ const preview = useMemo(
+ () =>
+ session && (task || unavailable)
+ ? {
+ label: task ? `Task: ${task.title}` : "Unavailable task",
+ render: (open: (target: string) => boolean) =>
+ task ? (
+ open(url)}
+ />
+ ) : (
+
+ This task isn’t available. You may not have access, or it may
+ have been deleted.
+
+ ),
+ }
+ : undefined,
+ [session, task, unavailable, url],
+ );
+ useEffect(() => {
+ if (!offer || !preview) return;
+ offer(preview);
+ return () => offer(undefined);
+ }, [offer, preview]);
+ // An authored label stays; a pasted link takes the task's title.
+ const authored = useContext(LinkLabelContext) !== undefined;
+ return (
+
+
+
+ ),
+ })}
+ />
+ );
+}
+
+function TaskPreview({
+ session,
+ task,
+ onOpen,
+}: {
+ session: RelaySession;
+ task: Task;
+ onOpen(): void;
+}) {
+ const places = usePlaces(session, [task.home]);
+ const project = projectOf(task, places);
+ const where = project.name ?? places.get(task.home)?.name;
+ return (
+
+
{task.title}
+
+ {statusLabels[task.status]}
+ {where ? ` · ${where}` : ""}
+
+
+
+ Open task
+
+
+
+ );
+}
diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx
index 119b78da16..a8d637267f 100644
--- a/src/bundled/tasks/TaskView.test.tsx
+++ b/src/bundled/tasks/TaskView.test.tsx
@@ -2,6 +2,7 @@
import "@testing-library/jest-dom/vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
+import type { ChannelSummary } from "../../features/relay/contracts";
import { PublishRejected } from "../../features/relay/outbox";
import type { RelaySession } from "../../features/relay/session";
import { TASK_TYPE, type Task, taskOf } from "./model";
@@ -10,17 +11,18 @@ import { TaskView } from "./TaskView";
afterEach(cleanup);
const viewer = "a".repeat(64);
-const tasksChannel = { id: "tasks", open: async () => "tasks" };
-const chat = "11111111-1111-4111-8111-111111111111";
-const revision = (id: string, title: string, content: object = {}) => ({
- id,
+const id = "11111111-1111-4111-8111-111111111111";
+const home = "22222222-2222-4222-8222-222222222222";
+const revision = (revisionId: string, title: string) => ({
+ id: revisionId,
pubkey: "b".repeat(64),
sig: "",
created_at: 5,
kind: 45010,
- content: JSON.stringify({ version: 1, author: viewer, ...content }),
+ content: JSON.stringify({ version: 2, author: viewer }),
tags: [
- ["d", "task-1"],
+ ["d", id],
+ ["h", home],
["type", TASK_TYPE],
["title", title],
],
@@ -28,13 +30,37 @@ const revision = (id: string, title: string, content: object = {}) => ({
const mine = taskOf(revision("d".repeat(64), "Fix the header")) as Task;
const theirs = revision("c".repeat(64), "Their title");
-function setup(publish: () => Promise) {
+function setup(
+ publish: () => Promise,
+ role: ChannelSummary["viewerRole"] = "member",
+) {
const signed: { tags: string[][] }[] = [];
+ const channels: ChannelSummary[] = [
+ { id: home, name: "design", channelType: "stream", viewerRole: role },
+ ];
+ const profiles = new Map();
+ const list = { status: "ready", channels };
const session = {
viewer,
- profiles: { snapshot: () => new Map() },
- channels: { list: () => ({ channels: [] }) },
- snapshotRead: vi.fn(async () => [theirs]),
+ media: () => undefined,
+ profiles: {
+ snapshot: () => profiles,
+ subscribe: () => () => {},
+ ensure: async () => {},
+ },
+ channels: {
+ ensureList: () => () => {},
+ subscribeList: () => () => {},
+ list: () => list,
+ },
+ snapshotRead: vi.fn(async (filters: { kinds?: number[] }[]) =>
+ filters[0]?.kinds?.includes(45010) &&
+ !(filters[0] as Record)["#type"]
+ ?.toString()
+ .includes("link")
+ ? [theirs]
+ : [],
+ ),
configArtifactWriter: {
sign: vi.fn(async (template: { tags: string[][] }) => {
signed.push(template);
@@ -56,9 +82,7 @@ it("keeps the person's text on a conflict, then saves over the newer version", a
render(
"shared"}
openConversation={() => {}}
onSaved={onSaved}
/>,
@@ -79,103 +103,40 @@ it("keeps the person's text on a conflict, then saves over the newer version", a
expect(signed[1]?.tags).toContainEqual(["title", "My title"]);
});
-it("shows their version when asked", async () => {
- const { session } = setup(async () => {
- throw new PublishRejected("rejected", "conflict: stale prev");
- });
+it("shows a guest the task with no edit controls", () => {
+ const { session } = setup(async () => "", "guest");
render(
"shared"}
openConversation={() => {}}
onSaved={() => {}}
/>,
);
- fireEvent.click(screen.getByRole("button", { name: "Edit" }));
- fireEvent.click(screen.getByRole("button", { name: "Save" }));
- fireEvent.click(
- await screen.findByRole("button", { name: "Show their version" }),
- );
- expect(screen.getByLabelText("Title")).toHaveValue("Their title");
- expect(screen.queryByRole("alert")).toBeNull();
+ expect(screen.getByText("Read-only access")).toBeInTheDocument();
+ for (const name of ["Edit", "Move…"])
+ expect(screen.queryByRole("button", { name })).toBeNull();
+ expect(screen.queryByLabelText("Status")).toBeNull();
});
-it("links the current chat only once it may be linked", async () => {
+it("creates a new task in the place it started, posting nothing", async () => {
const { session, signed } = setup(async () => "");
- const readyToLink = vi
- .fn<(id: string) => Promise<"shared" | "cancelled" | "unavailable">>()
- .mockResolvedValueOnce("cancelled")
- .mockResolvedValueOnce("shared");
const onSaved = vi.fn();
render(
{}}
- onSaved={onSaved}
- />,
- );
- const link = screen.getByRole("button", { name: "Link this chat" });
- fireEvent.click(link);
- await vi.waitFor(() => expect(link).toBeEnabled());
- expect(readyToLink).toHaveBeenCalledTimes(1);
- expect(signed).toHaveLength(0);
- fireEvent.click(link);
- await vi.waitFor(() => expect(onSaved).toHaveBeenCalled());
- expect(onSaved.mock.calls[0]?.[0].links).toEqual([chat]);
-});
-
-it("asks to share a new task's chat only at Create, and saves nothing if declined", async () => {
- const { session, signed } = setup(async () => "");
- const readyToLink = vi.fn(async () => "cancelled" as const);
- render(
- {}}
- onSaved={() => {}}
- />,
- );
- fireEvent.change(screen.getByLabelText("Title"), {
- target: { value: "From this chat" },
- });
- expect(readyToLink).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole("button", { name: "Create task" }));
- expect(await screen.findByRole("alert")).toHaveTextContent(
- "This chat wasn’t shared, so the task wasn’t saved.",
- );
- expect(readyToLink).toHaveBeenCalledWith(chat, expect.any(String));
- expect(signed).toHaveLength(0);
-});
-
-it("makes the tasks channel only when the community's first task is saved", async () => {
- const { session, signed } = setup(async () => "");
- const open = vi.fn(async () => "made");
- const onSaved = vi.fn();
- render(
- "shared"}
+ home={home}
openConversation={() => {}}
onSaved={onSaved}
/>,
);
fireEvent.change(screen.getByLabelText("Title"), {
- target: { value: "Just a title" },
+ target: { value: "From this chat" },
});
- expect(open).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Create task" }));
await vi.waitFor(() => expect(onSaved).toHaveBeenCalled());
- expect(open).toHaveBeenCalledOnce();
- expect(signed[0]?.tags).toContainEqual(["h", "made"]);
+ expect(signed).toHaveLength(1);
+ expect(signed[0]?.tags).toContainEqual(["h", home]);
+ expect(signed[0]?.tags).toContainEqual(["op", "create"]);
});
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index 1050fef1d1..f5fcc65b27 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -1,24 +1,23 @@
-import { type ReactNode, useEffect, useId, useRef, useState } from "react";
-import type { RelaySession } from "../../features/relay/session";
+import {
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
import { useChannelReference } from "../../features/conversation/channel-reference";
+import { useIdentityNames } from "../../features/identity-names/react";
import { DOCUMENT_PROFILE } from "../../features/markdown/document-profile";
import {
MarkdownDocument,
sharedComponents,
} from "../../features/markdown/MarkdownDocument";
import { AttachmentImage } from "../../features/messages/AttachmentImage";
-import { useIdentityNames } from "../../features/identity-names/react";
-import { formatPublicKey } from "../../shared/identity/public-key";
-import { relativeTimestamp } from "../../shared/relative-timestamp";
-import { Button } from "../../shared/design-system/ui/Button";
-import { Field } from "../../shared/design-system/ui/Field";
-import { InlineHeader } from "../../shared/design-system/ui/Header";
-import { IconButton } from "../../shared/design-system/ui/IconButton";
-import { Input } from "../../shared/design-system/ui/Input";
-import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
-import { Select } from "../../shared/design-system/ui/Select";
-import { Textarea } from "../../shared/design-system/ui/Textarea";
-import { useToastNotification } from "../../shared/design-system/ui/Toast";
+import type { RelaySession } from "../../features/relay/session";
+import { avatarMedia } from "../../shared/avatar-source";
import {
ChatCircleIcon,
HashIcon,
@@ -27,7 +26,23 @@ import {
LockIcon,
XIcon,
} from "../../shared/design-system/icons/index";
+import { AlertDialog } from "../../shared/design-system/ui/AlertDialog";
+import { AvatarStack } from "../../shared/design-system/ui/AvatarStack";
+import { Button } from "../../shared/design-system/ui/Button";
+import { Combobox } from "../../shared/design-system/ui/Combobox";
+import { Field } from "../../shared/design-system/ui/Field";
+import { InlineHeader } from "../../shared/design-system/ui/Header";
+import { IconButton } from "../../shared/design-system/ui/IconButton";
+import { Input } from "../../shared/design-system/ui/Input";
+import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
+import { Select, type SelectGroup } from "../../shared/design-system/ui/Select";
+import { Textarea } from "../../shared/design-system/ui/Textarea";
+import { useToastNotification } from "../../shared/design-system/ui/Toast";
+import { formatPublicKey } from "../../shared/identity/public-key";
+import { relativeTimestamp } from "../../shared/relative-timestamp";
+import { readLinks, setLink, type TaskLink } from "./links";
import {
+ MAX_ASSIGNEES,
statuses,
statusLabels,
type Task,
@@ -35,54 +50,49 @@ import {
type TaskImage,
type TaskStatus,
} from "./model";
+import { accessChange, type Place, projectOf } from "./places";
+import { useCanEdit, usePlaces, useTaskHomes } from "./react";
+import { saveTask, type SaveTarget } from "./store";
import { StatusIcon } from "./StatusIcon";
-import type { TasksChannel } from "./react";
-import { saveTask } from "./store";
-import type { ChatShareOutcome } from "../../features/solo/share-requests";
import styles from "./Tasks.module.css";
const empty: TaskFields = {
title: "",
description: "",
- status: "open",
+ status: "todo",
images: [],
- links: [],
+ assignees: [],
};
+
/** An open edit: the text, the revision it builds on, and the task's id. */
export type TaskDraft = Readonly<{
fields: TaskFields;
base: Task | undefined;
id: string;
+ home: string | undefined;
}>;
-/** A save, or why it stopped before writing: a link the owner didn't share. */
-type ViewSave =
- | Awaited>
- | Readonly<{ status: "declined"; outcome: "cancelled" | "unavailable" }>;
-const declined = "Only this chat’s owner can link it to a task.";
-
const fieldsOf = (task: Task): TaskFields => ({
title: task.title,
description: task.description,
status: task.status,
images: task.images,
- links: task.links,
+ assignees: task.assignees,
});
+const message = (reason: unknown, fallback: string) =>
+ reason instanceof Error ? reason.message : fallback;
+
export type TaskViewProps = {
session: RelaySession;
- channel: TasksChannel;
/** The task's current revision; undefined starts a new task. */
task: Task | undefined;
+ /** Where a new task starts. */
+ home?: string | undefined;
/** The conversation this view sits beside, which "Link this chat" links. */
currentChat?: string | undefined;
- /** Resolves "shared" once `channelId` may be linked; a private Solo chat
- * first asks its owner to make it View only. */
- readyToLink(channelId: string, task: string): Promise;
openConversation(channelId: string): void;
onSaved(task: Task): void;
- /** Conversations a new task starts linked to, already cleared to link. */
- newLinks?: readonly string[] | undefined;
/** Unsaved edits the list keeps while another task is open. */
draft?: TaskDraft | undefined;
onDraftChange?: ((draft: TaskDraft | undefined) => void) | undefined;
@@ -90,68 +100,15 @@ export type TaskViewProps = {
onDiscard?: (() => void) | undefined;
};
-/** One task: read by default, with an explicit edit mode. Every save names the
- * revision it started from, so a concurrent edit is reported, never lost. */
+/** One task: read by default, with an explicit edit mode. Every save names
+ * the revision it started from, so a concurrent edit is reported, never lost. */
export function TaskView(props: TaskViewProps) {
- const { session, channel, task } = props;
- const notify = useToastNotification();
+ const { session, task } = props;
const [editing, setEditing] = useState(!task || !!props.draft);
- const [saving, setSaving] = useState(false);
- // Consent is asked only as a link is saved, so declining or discarding
- // never leaves a chat shared with nothing linked to it.
- const save = async (
- fields: TaskFields,
- base: Task | undefined,
- id?: string,
- ): Promise => {
- setSaving(true);
- try {
- for (const added of fields.links.filter(
- (link) => !base?.links.includes(link),
- )) {
- const outcome = await props.readyToLink(added, fields.title);
- if (outcome !== "shared") return { status: "declined", outcome };
- }
- // The community's first saved task makes its tasks channel.
- const target =
- channel.id ?? (await channel.open(AbortSignal.timeout(30_000)));
- const result = await saveTask(
- session,
- target,
- fields,
- base,
- undefined,
- id,
- );
- if (result.status === "saved") props.onSaved(result.task);
- return result;
- } finally {
- setSaving(false);
- }
- };
- // Immediate changes in read mode: status and links.
- const change = async (next: Partial) => {
- if (!task || saving) return false;
- try {
- const result = await save({ ...fieldsOf(task), ...next }, task);
- if (result.status === "saved") return true;
- if (result.status === "conflict")
- notify("Someone else changed this task. Try again.", "error");
- else if (result.outcome === "unavailable") notify(declined, "error");
- } catch (reason) {
- notify(
- reason instanceof Error ? reason.message : "Couldn’t save the task.",
- "error",
- );
- }
- return false;
- };
if (editing || !task)
return (
{
props.onDraftChange?.(undefined);
setEditing(false);
@@ -159,54 +116,112 @@ export function TaskView(props: TaskViewProps) {
}}
/>
);
- const link = (channelId: string) =>
- change({ links: [...task.links, channelId] });
- const unlink = async (channelId: string) => {
- const solo =
- session.channels.list().channels.find((item) => item.id === channelId)
- ?.channelType === "solo";
- const unlinked = await change({
- links: task.links.filter((item) => item !== channelId),
- });
- // Unlinking never changes access back.
- if (unlinked && solo)
- notify(
- "Unlinked. The chat stays View only. Change that in the chat’s People settings.",
- "success",
+ return (
+ setEditing(true)}
+ />
+ );
+}
+
+function TaskDetails({
+ session,
+ task,
+ currentChat,
+ openConversation,
+ onSaved,
+ edit,
+}: TaskViewProps & { task: Task; edit(): void }) {
+ const notify = useToastNotification();
+ const canEdit = useCanEdit(session, task.home);
+ const [saving, setSaving] = useState(false);
+ const [moving, setMoving] = useState(false);
+ const places = usePlaces(session, [task.home]);
+ const project = projectOf(task, places);
+ const home = places.get(task.home);
+ // Immediate changes: status and assignees, on the revision shown.
+ const change = async (next: Partial) => {
+ if (saving) return;
+ setSaving(true);
+ try {
+ const result = await saveTask(
+ session,
+ { ...fieldsOf(task), ...next },
+ { op: "update", base: task },
);
+ if (result.status === "saved") onSaved(result.task);
+ else {
+ onSaved(result.current);
+ notify("Someone else changed this task. Try again.", "error");
+ }
+ } catch (reason) {
+ notify(message(reason, "Couldn’t save the task."), "error");
+ } finally {
+ setSaving(false);
+ }
+ };
+ const setStatus = (status: TaskStatus) => {
+ // Starting a task assigns whoever starts it, when there's room.
+ const viewer = session.viewer;
+ const starts =
+ status === "in_progress" &&
+ viewer &&
+ !task.assignees.includes(viewer) &&
+ task.assignees.length < MAX_ASSIGNEES;
+ void change({
+ status,
+ ...(starts ? { assignees: [...task.assignees, viewer] } : {}),
+ });
};
- const linkedHere =
- props.currentChat !== undefined && task.links.includes(props.currentChat);
return (
-
-
{task.title}
+
+
{task.title}
+
+ {project.id && project.id !== task.home
+ ? `${project.name ?? "Private project"}${home ? ` · ${placeLabel(home)}` : ""}`
+ : home
+ ? placeLabel(home)
+ : ""}
+
-
-
}
- disabled={saving}
- groups={[
- {
- label: "Status",
- options: statuses.map((status) => ({
- value: status,
- label: statusLabels[status],
- leading:
,
- })),
- },
- ]}
- onValueChange={(value) =>
- void change({ status: value as TaskStatus })
- }
- />
-
setEditing(true)} disabled={saving}>
- Edit
-
+
+ {canEdit ? (
+ <>
+
}
+ disabled={saving}
+ groups={statusGroups}
+ onValueChange={(value) => setStatus(value as TaskStatus)}
+ />
+
void change({ assignees })}
+ />
+
+ Edit
+
+ setMoving(true)}>
+ Move…
+
+ >
+ ) : (
+ <>
+
+ {statusLabels[task.status]}
+
+
+ >
+ )}
{task.description.trim() ? (
) : (
-
No description.
+
No description.
)}
{task.images.length > 0 && (
)}
-
-
- {task.links.length ? (
-
- {task.links.map((channelId) => (
-
- props.openConversation(channelId)}
- />
- }
- disabled={saving}
- onClick={() => void unlink(channelId)}
- />
-
- ))}
-
- ) : (
-
- No conversations are linked yet.
-
+
+
+
+ {canEdit ? null : (
+ Read-only access
)}
- {props.currentChat && !linkedHere ? (
-
- void link(props.currentChat as string)}
- >
-
- Link this chat
-
-
- ) : null}
+ {moving ? (
+ setMoving(false)}
+ onMoved={(moved) => {
+ setMoving(false);
+ onSaved(moved);
+ }}
+ />
+ ) : null}
);
}
-function TaskByline({ session, task }: { session: RelaySession; task: Task }) {
+const statusGroups: readonly SelectGroup[] = [
+ {
+ label: "Status",
+ options: statuses.map((status) => ({
+ value: status,
+ label: statusLabels[status],
+ leading: ,
+ })),
+ },
+];
+
+/** Profiles for `pubkeys`, read in the background and kept current. */
+function usePeople(session: RelaySession, pubkeys: readonly string[]) {
+ const key = pubkeys.join(",");
+ useEffect(() => {
+ if (key)
+ void session.profiles
+ .ensure(key.split(","), "background")
+ .catch(() => {});
+ }, [session, key]);
+ const snapshot = useSyncExternalStore(
+ session.profiles.subscribe,
+ session.profiles.snapshot,
+ session.profiles.snapshot,
+ );
const name = useIdentityNames(session.names);
+ return useCallback(
+ (pubkey: string) => {
+ const profile = snapshot.get(pubkey);
+ return {
+ id: pubkey,
+ name:
+ pubkey === session.viewer
+ ? "You"
+ : name(
+ pubkey,
+ profile?.name ?? formatPublicKey(pubkey) ?? "Someone",
+ ),
+ src: avatarMedia(profile?.picture, session.media),
+ isAgent: !!profile?.isAgent,
+ };
+ },
+ [snapshot, name, session],
+ );
+}
+
+function Assignees({
+ session,
+ assignees,
+}: {
+ session: RelaySession;
+ assignees: readonly string[];
+}) {
+ const person = usePeople(session, assignees);
+ const people = assignees.map(person);
+ if (!people.length)
+ return Nobody assigned ;
+ return (
+
+ ({ ...item, shape: "circle" }))}
+ />{" "}
+ {people.map((item) => item.name).join(", ")}
+
+ );
+}
+
+type Person = ReturnType>;
+
+/** Up to four people, chosen from the people of the task's home. Agents
+ * are never offered: a person always answers for the work. */
+function AssigneePicker({
+ session,
+ home,
+ assignees,
+ disabled,
+ onChange,
+}: {
+ session: RelaySession;
+ home: string;
+ assignees: readonly string[];
+ disabled: boolean;
+ onChange(assignees: readonly string[]): void;
+}) {
+ const homes = useTaskHomes(session);
+ const members = homes.find((item) => item.id === home)?.members;
+ const pubkeys = useMemo(
+ () => [...new Set([...assignees, ...(members ?? [])])],
+ [assignees, members],
+ );
+ const person = usePeople(session, pubkeys);
+ const [search, setSearch] = useState("");
+ // Stable between renders: the combobox syncs its selection to these.
+ const people = useMemo(
+ () =>
+ pubkeys
+ .map(person)
+ .filter((item) => !item.isAgent || assignees.includes(item.id)),
+ [pubkeys, person, assignees],
+ );
+ const chosen = useMemo(
+ () => people.filter((item) => assignees.includes(item.id)),
+ [people, assignees],
+ );
+ const full = chosen.length >= MAX_ASSIGNEES;
+ return (
+
+ multiple
+ items={people}
+ value={chosen}
+ itemToStringLabel={(item) => item.name}
+ itemToStringValue={(item) => item.id}
+ isItemEqualToValue={(a, b) => a.id === b.id}
+ inputValue={search}
+ onInputValueChange={setSearch}
+ onOpenChange={(open) => open && setSearch("")}
+ disabled={disabled}
+ onValueChange={(next) => {
+ if (next.length <= MAX_ASSIGNEES) onChange(next.map((item) => item.id));
+ }}
+ >
+
+ {chosen.length ? (
+ ({ ...item, shape: "circle" }))}
+ />
+ ) : (
+ "Nobody assigned"
+ )}
+
+
+
+ {(item: Person) => (
+
+ {item.name}
+
+ )}
+
+
+
+ );
+}
+
+function TaskByline({ session, task }: { session: RelaySession; task: Task }) {
+ const person = usePeople(session, [task.author, task.editor]);
const label = (pubkey: string) =>
- pubkey === session.viewer
- ? "you"
- : name(
- pubkey,
- session.profiles.snapshot().get(pubkey)?.name ??
- formatPublicKey(pubkey) ??
- "someone",
- );
+ pubkey === session.viewer ? "you" : person(pubkey).name;
return (
-
+
Created by {label(task.author)} · Updated{" "}
{relativeTimestamp(task.updatedAt * 1000)} by {label(task.editor)}
@@ -327,8 +475,95 @@ function TaskImages({
);
}
-/** A linked conversation as the viewer may see it: its name when readable,
- * "Private channel" with no name when not. */
+/** Conversations linked to the task that the viewer can read. A link lives
+ * with its conversation, so nobody learns of a link they can't read. */
+function LinkedConversations({
+ session,
+ task,
+ currentChat,
+ openConversation,
+}: {
+ session: RelaySession;
+ task: Task;
+ currentChat: string | undefined;
+ openConversation(channelId: string): void;
+}) {
+ const notify = useToastNotification();
+ const [links, setLinks] = useState();
+ const [busy, setBusy] = useState(false);
+ const [attempt, setAttempt] = useState(0);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a change is a new read.
+ useEffect(() => {
+ const controller = new AbortController();
+ readLinks(session, { task: task.id }, controller.signal).then(
+ (read) => !controller.signal.aborted && setLinks(read),
+ () => !controller.signal.aborted && setLinks([]),
+ );
+ return () => controller.abort();
+ }, [session, task.id, attempt]);
+ const toggle = async (conversation: string, linked: boolean) => {
+ setBusy(true);
+ try {
+ await setLink(
+ session,
+ task.id,
+ conversation,
+ linked,
+ AbortSignal.timeout(20_000),
+ );
+ setAttempt((count) => count + 1);
+ } catch (reason) {
+ notify(message(reason, "Couldn’t change the link."), "error");
+ } finally {
+ setBusy(false);
+ }
+ };
+ const linkedHere =
+ !!currentChat && !!links?.some((link) => link.conversation === currentChat);
+ return (
+
+
+ {links?.length ? (
+
+ {links.map((link) => (
+
+ openConversation(link.conversation)}
+ />
+ }
+ disabled={busy}
+ onClick={() => void toggle(link.conversation, false)}
+ />
+
+ ))}
+
+ ) : (
+
+ {links ? "No conversations you can see are linked." : "Loading…"}
+
+ )}
+ {currentChat && links && !linkedHere ? (
+
+ void toggle(currentChat, true)}
+ >
+
+ Link this chat
+
+
+ ) : null}
+
+ );
+}
+
function LinkedConversation({
session,
channelId,
@@ -341,96 +576,203 @@ function LinkedConversation({
const reference = useChannelReference(session.channels, channelId);
let icon: ReactNode = ;
let label = "Loading…";
- let trailing: string | undefined;
if (reference.state === "found") {
const solo = reference.channelType === "solo";
- icon = solo ? (
-
- ) : (
-
- );
- label = reference.name || (solo ? "Solo chat" : "Channel");
- trailing = solo ? "Solo chat" : "Channel";
+ if (solo) icon = ;
+ label = reference.name || (solo ? "Chat" : "Channel");
} else if (reference.state === "withheld") {
icon = ;
label = "Private channel";
- trailing = "No access";
}
- const readable = reference.state === "found" && reference.readable !== false;
return (
);
}
+/** Where a task can go: the places the viewer can post in, by name. */
+function homeGroups(
+ homes: readonly { id: string; name: string; channelType?: string }[],
+ except?: string,
+): readonly SelectGroup[] {
+ const options = (kind: "chat" | "channel") =>
+ homes
+ .filter((item) => item.id !== except)
+ .filter((item) => (item.channelType === "solo") === (kind === "chat"))
+ .map((item) => ({ value: item.id, label: item.name || "Untitled" }))
+ .sort((a, b) => a.label.localeCompare(b.label));
+ return [
+ { label: "Channels", options: options("channel") },
+ { label: "Chats", separator: true, options: options("chat") },
+ ].filter((group) => group.options.length);
+}
+
+const placeLabel = (place: Place) =>
+ place.kind === "chat" ? place.name : `#${place.name}`;
+const placeList = (list: readonly Place[]) => list.map(placeLabel).join(", ");
+
+/** Moving one task: choose where, then confirm whose access changes, by
+ * place. The task's comments go with it. */
+function MoveTask({
+ session,
+ task,
+ onClose,
+ onMoved,
+}: {
+ session: RelaySession;
+ task: Task;
+ onClose(): void;
+ onMoved(task: Task): void;
+}) {
+ const homes = useTaskHomes(session);
+ const groups = homeGroups(homes, task.home);
+ const [to, setTo] = useState();
+ const [error, setError] = useState("");
+ const [pending, setPending] = useState(false);
+ const places = usePlaces(session, to ? [task.home, to] : [task.home]);
+ const change = to ? accessChange(task.home, to, places) : undefined;
+ const move = async () => {
+ if (!to) return;
+ setPending(true);
+ setError("");
+ try {
+ const result = await saveTask(session, fieldsOf(task), {
+ op: "move",
+ base: task,
+ home: to,
+ });
+ if (result.status === "saved") onMoved(result.task);
+ else setError("Someone else changed this task. Close and try again.");
+ } catch (reason) {
+ setError(message(reason, "Couldn’t move the task."));
+ } finally {
+ setPending(false);
+ }
+ };
+ return (
+
+
+ Cancel
+
+ void move()}
+ >
+ Move
+
+ >
+ }
+ >
+ {groups.length ? (
+
+ ) : (
+
+ There’s nowhere else you can post in to move this task.
+
+ )}
+ {change?.gain.length ? (
+
+ Everyone in {placeList(change.gain)} will be able to see this task and
+ its comments.
+
+ ) : null}
+ {change?.lose.length ? (
+
+ People who are only in {placeList(change.lose)} will lose access.
+
+ ) : null}
+ {error ? (
+
+ {error}
+
+ ) : null}
+
+ );
+}
+
function TaskEditor({
session,
task,
- newLinks,
+ home: startHome,
draft: kept,
onDraftChange,
- saving,
- save,
+ onSaved,
onDone,
-}: TaskViewProps & {
- saving: boolean;
- save(
- fields: TaskFields,
- base: Task | undefined,
- id?: string,
- ): Promise;
- onDone(saved: boolean): void;
-}) {
+}: TaskViewProps & { onDone(saved: boolean): void }) {
const inputId = useId();
+ const homes = useTaskHomes(session);
const [draft, setDraft] = useState(
- kept?.fields ??
- (task ? fieldsOf(task) : { ...empty, links: newLinks ?? [] }),
+ kept?.fields ?? (task ? fieldsOf(task) : empty),
);
+ const [home, setHome] = useState(kept?.home ?? startHome);
// The revision this draft builds on; a conflict moves it to theirs.
const [base, setBase] = useState(kept ? kept.base : task);
// One id for a new task across retries, so a create that landed unseen
// is found rather than made twice.
const [taskId] = useState(() => kept?.id ?? task?.id ?? crypto.randomUUID());
useEffect(
- () => onDraftChange?.({ fields: draft, base, id: taskId }),
- [draft, base, taskId, onDraftChange],
+ () => onDraftChange?.({ fields: draft, base, id: taskId, home }),
+ [draft, base, taskId, home, onDraftChange],
);
- const [conflict, setConflict] = useState<{ theirs: Task }>();
+ const [conflict, setConflict] = useState();
const [error, setError] = useState("");
+ const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const files = useRef(null);
+ const groups = useMemo(() => homeGroups(homes), [homes]);
+ // Only a place the viewer can post in can take a new task.
+ const where = homes.some((item) => item.id === home) ? home : undefined;
const update = (next: Partial) =>
setDraft((current) => ({ ...current, ...next }));
const submit = async () => {
+ const target: SaveTarget | undefined = base
+ ? { op: "update", base }
+ : where
+ ? { op: "create", home: where, id: taskId }
+ : undefined;
+ if (!target) {
+ setError("Choose where this task lives.");
+ return;
+ }
setError("");
+ setSaving(true);
try {
- const result = await save(draft, base, taskId);
- if (result.status === "saved") onDone(true);
- else if (result.status === "declined")
- setError(
- result.outcome === "unavailable"
- ? declined
- : "This chat wasn’t shared, so the task wasn’t saved.",
- );
- else {
+ const result = await saveTask(session, draft, target);
+ if (result.status === "saved") {
+ onSaved(result.task);
+ onDone(true);
+ } else {
// Keep the person's text; the next Save is a deliberate overwrite.
- setConflict({ theirs: result.current });
+ setConflict(result.current);
setBase(result.current);
}
} catch (reason) {
- setError(
- reason instanceof Error ? reason.message : "Couldn’t save the task.",
- );
+ setError(message(reason, "Couldn’t save the task."));
+ } finally {
+ setSaving(false);
}
};
const upload = async (list: FileList | null) => {
- // Media access is community-wide; the tasks channel's roster need not
- // include the viewer, and saving the task is the guarded write.
+ // Media access is community-wide; saving the task is the guarded write.
const uploadImage = session.attachments?.uploadForNewChat;
const chosen = [...(list ?? [])].filter((file) =>
file.type.startsWith("image/"),
@@ -481,15 +823,15 @@ function TaskEditor({
}}
>
{conflict ? (
-
-
+
+
Someone else changed this task. Your text is kept. Saving now
replaces their version.
{
- setDraft(fieldsOf(conflict.theirs));
+ setDraft(fieldsOf(conflict));
setConflict(undefined);
}}
>
@@ -505,9 +847,20 @@ function TaskEditor({
onChange={(event) => update({ title: event.target.value })}
/>
+ {task ? null : (
+
+ )}
) : null}
-
+
{task ? "Save" : "Create task"}
diff --git a/src/bundled/tasks/Tasks.module.css b/src/bundled/tasks/Tasks.module.css
index 0d912ea64c..0da072bf7d 100644
--- a/src/bundled/tasks/Tasks.module.css
+++ b/src/bundled/tasks/Tasks.module.css
@@ -1,3 +1,5 @@
+/* Layout only: spacing and arrangement of the plugin's own elements. Every
+ control is a design-system component in its own appearance. */
.page {
container: tasks-page / inline-size;
display: flex;
@@ -15,7 +17,7 @@
padding: var(--space-4);
}
-/* List beside the open task; a narrow pane shows one at a time. */
+/* List beside the open task; a narrow pane shows one at a time, with Back. */
.board {
flex: 1;
min-height: 0;
@@ -23,7 +25,7 @@
grid-template-columns: minmax(0, 1fr);
}
.board[data-detail] {
- grid-template-columns: minmax(16rem, 22rem) minmax(0, 1fr);
+ grid-template-columns: minmax(16rem, 24rem) minmax(0, 1fr);
}
.list,
.detail {
@@ -32,7 +34,7 @@
overflow: auto;
display: flex;
flex-direction: column;
- gap: var(--space-3);
+ gap: var(--space-4);
padding: var(--space-4);
}
.detail {
@@ -56,8 +58,13 @@
}
}
-.toolbar,
-.actionRow {
+.toolbar {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+}
+.actions,
+.controls {
display: flex;
flex-wrap: wrap;
align-items: center;
@@ -86,33 +93,22 @@
}
/* One task, read or edited. */
-.task {
- display: flex;
- flex-direction: column;
- gap: var(--space-5);
- min-width: 0;
-}
-.taskHeading {
+.task,
+.section {
display: flex;
flex-direction: column;
- gap: var(--space-1);
+ gap: var(--space-4);
min-width: 0;
}
-.taskHeading h2 {
- margin: 0;
- overflow-wrap: anywhere;
-}
-.taskActions {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
+.section {
gap: var(--space-2);
}
-.section {
+.heading {
display: flex;
flex-direction: column;
- gap: var(--space-2);
+ gap: var(--space-1);
min-width: 0;
+ overflow-wrap: anywhere;
}
.images {
display: flex;
@@ -127,19 +123,17 @@
max-width: 100%;
}
-/* In the flow of the form, so nothing above it can cover it. */
-.notice {
+/* A task link's status, in line with the link's text. */
+.linkIcon {
+ display: inline-flex;
+ margin-right: var(--space-half);
+ vertical-align: -0.1875em;
+}
+.preview {
display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: var(--space-2) var(--space-3);
- padding: var(--space-3);
- border: 1px solid var(--border-warning);
- border-radius: var(--radius-card);
- background: var(--affordance-warning);
- color: var(--text-warning);
-}
-.notice > p {
- flex: 1 1 12rem;
- margin: 0;
+ flex-direction: column;
+ gap: var(--space-2);
+ min-width: 0;
+ max-width: 20rem;
+ overflow-wrap: anywhere;
}
diff --git a/src/bundled/tasks/TasksGate.tsx b/src/bundled/tasks/TasksGate.tsx
deleted file mode 100644
index 7ba08649bb..0000000000
--- a/src/bundled/tasks/TasksGate.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { ReactNode } from "react";
-import type { RelaySession } from "../../features/relay/session";
-import { Button } from "../../shared/design-system/ui/Button";
-import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion";
-import { type TasksChannel, useTasksChannel } from "./react";
-import styles from "./Tasks.module.css";
-
-/** Looks up the community's tasks channel before showing `children`. The
- * page and the panel share it; the first save makes it. */
-export function TasksGate({
- session,
- children,
-}: {
- session: RelaySession;
- children(channel: TasksChannel): ReactNode;
-}) {
- const channel = useTasksChannel(session);
- if (channel.status === "ready") return children(channel.channel);
- return (
-
-
- {channel.error}
-
- Try again
-
-
- ) : undefined
- }
- >
- {null}
-
-
- );
-}
diff --git a/src/bundled/tasks/TasksPage.tsx b/src/bundled/tasks/TasksPage.tsx
index bda6ce600a..e1c4878289 100644
--- a/src/bundled/tasks/TasksPage.tsx
+++ b/src/bundled/tasks/TasksPage.tsx
@@ -2,58 +2,41 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { Navigation } from "../../features/navigation/controller";
import type { NavigationScope } from "../../features/navigation/targets";
import type { PageProps } from "../../features/pages/service";
-import {
- useChannelRoster,
- useRelayConnection,
-} from "../../features/relay/react";
+import { useRelayConnection } from "../../features/relay/react";
import type { RelayData } from "../../features/relay/service";
import type { RelaySession } from "../../features/relay/session";
-import type { ChatSharing } from "../../features/solo/share-requests";
import {
ArrowLeftIcon,
- CaretDownIcon,
ClipboardCheckIcon,
PlusIcon,
} from "../../shared/design-system/icons/index";
import { Button } from "../../shared/design-system/ui/Button";
import { EmptyState } from "../../shared/design-system/ui/EmptyState";
+import { FullPageSurface } from "../../shared/design-system/ui/FullPageSurface";
+import { InlineHeader } from "../../shared/design-system/ui/Header";
import { LoadingRegion } from "../../shared/design-system/ui/LoadingRegion";
-import {
- MenuGroup,
- MenuGroupLabel,
- MenuPopup,
- MenuRadioGroup,
- MenuRadioItem,
- MenuRoot,
- MenuSeparator,
- MenuTrigger,
-} from "../../shared/design-system/ui/Menu";
import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
-import { Panel } from "../../shared/design-system/ui/Panel";
import {
PanelHeader,
PanelHeaderLabel,
} from "../../shared/design-system/ui/PanelHeader";
-import { readyToLink } from "./linking";
-import { filterTasks, type TaskFilter } from "./model";
-import { type TasksChannel, useTasksWithSaved } from "./react";
+import { SearchField } from "../../shared/design-system/ui/SearchField";
+import { Select, type SelectGroup } from "../../shared/design-system/ui/Select";
+import { byRecent, isMine, isOpenStatus, type Task } from "./model";
+import { type Place, type ProjectGroup, projectOf } from "./places";
+import { usePlaces, useTasksWithSaved } from "./react";
+import { taskRoute } from "./route";
+import { holdsWords } from "./similar";
import { StatusIcon } from "./StatusIcon";
-import { TasksGate } from "./TasksGate";
import { type TaskDraft, TaskView } from "./TaskView";
import styles from "./Tasks.module.css";
type TasksPageProps = Pick
& {
relay: RelayData;
navigator: Navigation;
- sharing: ChatSharing | undefined;
};
-export function TasksPage({
- relay,
- navigation,
- navigator,
- sharing,
-}: TasksPageProps) {
+export function TasksPage({ relay, navigation, navigator }: TasksPageProps) {
const connection = useRelayConnection(relay);
const request = useMemo(
() => navigation?.forSession(relay, connection),
@@ -83,8 +66,12 @@ export function TasksPage({
return;
request.resolve({ ...request.target, scope });
}, [request, connection.status, scope]);
+ const opened =
+ navigation?.target.kind === "page"
+ ? taskRoute(navigation.target.route?.params)
+ : undefined;
return (
-
+
{connection.status === "ready" && scope ? (
-
- {(channel) => (
-
- readyToLink(connection.session, sharing, channelId, { task })
- }
- openConversation={(channelId) =>
- void navigator.open({
- version: 1,
- kind: "conversation",
- scope,
- channelId,
- })
- }
- />
- )}
-
+ opened={opened}
+ openConversation={(channelId) =>
+ void navigator.open({
+ version: 1,
+ kind: "conversation",
+ scope,
+ channelId,
+ })
+ }
+ />
) : (
-
+
{connection.status === "connecting"
? "Connecting to your community…"
: "Connect to a community to see its tasks."}
@@ -137,48 +115,128 @@ export function TasksPage({
)}
-
+
);
}
-const statusFilterLabels = { open: "Open", done: "Done" } as const;
-const allOpen: TaskFilter = { status: "open", mine: false };
+type Filter = Readonly<{
+ words: string;
+ /** A project's id, NONE for tasks in no project, or ALL. */
+ project: string;
+ status: "open" | "closed" | "all";
+ mine: boolean;
+}>;
+const ALL = "all";
+const NONE = "none";
+const everything: Filter = {
+ words: "",
+ project: ALL,
+ status: "open",
+ mine: false,
+};
-/** Tasks I'm in: conversations whose signed roster includes me. */
-function useMyChannels(session: RelaySession) {
- const { channels } = useChannelRoster(session.channels);
- return useMemo(
- () =>
- new Set(
- channels
- .filter((item) => item.viewerRole && item.viewerRole !== "guest")
- .map((item) => item.id),
- ),
- [channels],
+const statusGroups: readonly SelectGroup[] = [
+ {
+ label: "Status",
+ options: [
+ { value: "open", label: "Open" },
+ { value: "closed", label: "Done and cancelled" },
+ { value: "all", label: "Any status" },
+ ],
+ },
+];
+const showGroups: readonly SelectGroup[] = [
+ {
+ label: "Show",
+ options: [
+ { value: "everyone", label: "Everyone’s" },
+ { value: "mine", label: "Mine" },
+ ],
+ },
+];
+
+type Group = ProjectGroup & { tasks: readonly Task[] };
+
+/** Tasks by project, the newest activity first; tasks in no project last. */
+function groupByProject(
+ tasks: readonly Task[],
+ places: ReadonlyMap,
+): readonly Group[] {
+ const groups = new Map();
+ for (const task of [...tasks].sort(byRecent)) {
+ const project = projectOf(task, places);
+ const group = groups.get(project.id) ?? { ...project, tasks: [] };
+ groups.set(project.id, { ...group, tasks: [...group.tasks, task] });
+ }
+ return [...groups.values()].sort(
+ (a, b) =>
+ Number(a.id === undefined) - Number(b.id === undefined) ||
+ (a.name ?? "").localeCompare(b.name ?? ""),
);
}
function TaskBoard({
session,
- channel,
- readyToLink,
+ opened,
openConversation,
}: {
session: RelaySession;
- channel: TasksChannel;
- readyToLink: TaskViewLink;
+ opened: string | undefined;
openConversation(channelId: string): void;
}) {
- const state = useTasksWithSaved(session, channel.id);
- const mine = useMyChannels(session);
- const [filter, setFilter] = useState(allOpen);
- const [selected, setSelected] = useState();
- const shown = filterTasks(state.tasks, filter, session.viewer ?? "", mine);
+ const state = useTasksWithSaved(session);
+ const places = usePlaces(
+ session,
+ state.tasks.map((task) => task.home),
+ );
+ const [filter, setFilter] = useState(everything);
+ const [selected, setSelected] = useState(opened);
+ useEffect(() => {
+ if (opened) setSelected(opened);
+ }, [opened]);
+ const viewer = session.viewer ?? "";
+ const groups = useMemo(
+ () => groupByProject(state.tasks, places),
+ [state.tasks, places],
+ );
+ const shown = groups
+ .filter(
+ (group) =>
+ filter.project === ALL ||
+ (filter.project === NONE ? !group.id : group.id === filter.project),
+ )
+ .map((group) => ({
+ ...group,
+ tasks: group.tasks.filter(
+ (task) =>
+ (filter.status === "all" ||
+ isOpenStatus(task.status) === (filter.status === "open")) &&
+ (!filter.mine || isMine(task, viewer)) &&
+ (!filter.words.trim() ||
+ holdsWords(filter.words, `${task.title} ${task.description}`)),
+ ),
+ }))
+ .filter((group) => group.tasks.length);
+ const projectGroups: readonly SelectGroup[] = [
+ {
+ label: "Project",
+ options: [
+ { value: ALL, label: "All projects" },
+ ...groups.flatMap((group) =>
+ group.id
+ ? [{ value: group.id, label: group.name ?? "Private project" }]
+ : [],
+ ),
+ { value: NONE, label: "Not in a project" },
+ ],
+ },
+ ];
const task =
selected === "new"
? undefined
: state.tasks.find((item) => item.id === selected);
- const detail = selected === "new" || task !== undefined;
+ const missing = !!selected && selected !== "new" && !task;
+ const detail = selected === "new" || !!task || missing;
const back = useCallback(() => setSelected(undefined), []);
// Unsaved edits survive opening another task (DESIGN.md master/detail).
const drafts = useRef(new Map());
@@ -190,71 +248,53 @@ function TaskBoard({
},
[selected],
);
+ const filtered = filter !== everything;
return (
-
-
- {statusFilterLabels[filter.status]}
- {filter.mine ? " · Mine" : ""}
-
-
+ setFilter({ ...filter, words })}
+ />
+
+
setFilter({ ...filter, project })}
+ />
+
+ setFilter({ ...filter, status: status as Filter["status"] })
}
/>
-
-
- Status
-
- setFilter((current) => ({
- ...current,
- status: value === "done" ? "done" : "open",
- }))
- }
- >
-
- Open
-
-
- Done
-
-
-
-
-
- Show
-
- setFilter((current) => ({
- ...current,
- mine: value === "mine",
- }))
- }
- >
-
- Everyone’s
-
-
- Mine
-
-
-
-
-
-
- setSelected("new")}
- >
-
- New task
-
+
+ setFilter({ ...filter, mine: show === "mine" })
+ }
+ />
+
+ setSelected("new")}
+ >
+
+ New task
+
+
{state.status === "loading" ? null : shown.length ? (
-
- {shown.map((item) => (
-
- }
- label={item.title || "Untitled task"}
- trailing={
- item.links.length
- ? `${item.links.length} linked`
- : undefined
- }
- selected={item.id === selected}
- onClick={() => setSelected(item.id)}
- />
-
- ))}
-
+ shown.map((group) => (
+
+
+
+ {group.tasks.map((item) => (
+
+ }
+ label={item.title || "Untitled task"}
+ selected={item.id === selected}
+ onClick={() => setSelected(item.id)}
+ />
+
+ ))}
+
+
+ ))
) : (
}
title={
state.tasks.length
- ? "No tasks match this filter"
+ ? "No tasks match these filters"
: "No tasks yet"
}
description={
state.tasks.length
- ? "Change the filter to see other tasks."
- : "A task holds the context for a piece of work and the conversations about it. You can also ask your agent to make one."
+ ? "Change the filters to see other tasks."
+ : "A task holds the context for a piece of work, so anyone can pick it up. You can also ask your agent to make one."
}
action={
- state.tasks.length ? (
- setFilter(allOpen)}>
+ state.tasks.length && filtered ? (
+ setFilter(everything)}>
Show all open tasks
) : (
@@ -319,25 +369,36 @@ function TaskBoard({
Back
- {
- state.setSaved(next);
- setSelected(next.id);
- }}
- onDiscard={back}
- />
+ {missing ? (
+ state.status === "loading" ? null : (
+ }
+ title="This task isn’t available"
+ description="You may not have access, or it may have been deleted."
+ />
+ )
+ ) : (
+ {
+ state.setSaved(next);
+ setSelected(next.id);
+ }}
+ onDiscard={back}
+ />
+ )}
) : null}
);
}
-
-type TaskViewLink = Parameters[0]["readyToLink"];
diff --git a/src/bundled/tasks/TasksPanel.tsx b/src/bundled/tasks/TasksPanel.tsx
index 8bf1644b98..9d518b2ef3 100644
--- a/src/bundled/tasks/TasksPanel.tsx
+++ b/src/bundled/tasks/TasksPanel.tsx
@@ -1,9 +1,9 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import type { RelaySession } from "../../features/relay/session";
import {
ArrowLeftIcon,
- LinkIcon,
ClipboardCheckIcon,
+ LinkIcon,
PlusIcon,
} from "../../shared/design-system/icons/index";
import { Button } from "../../shared/design-system/ui/Button";
@@ -17,63 +17,63 @@ import {
} from "../../shared/design-system/ui/Menu";
import { NavigationItem } from "../../shared/design-system/ui/NavigationItem";
import { useToastNotification } from "../../shared/design-system/ui/Toast";
-import { isOpenStatus, type Task } from "./model";
-import { type TasksChannel, useTasksWithSaved } from "./react";
-import { saveTask } from "./store";
+import { readLinks, setLink } from "./links";
+import { byRecent, isOpenStatus } from "./model";
+import { useTasksWithSaved } from "./react";
import { StatusIcon } from "./StatusIcon";
import { TaskView, type TaskViewProps } from "./TaskView";
import styles from "./Tasks.module.css";
-/** Open tasks the "Link to a task" menu offers, newest first. */
+/** Open tasks the "Link a task" menu offers, newest first. */
const LINK_CHOICES = 20;
-/** Tasks beside one conversation: those linked to it, and ways to make or
- * link one from here. A task opens in place, with Back. */
+/** Tasks beside one conversation: those living in it and those linked to
+ * it, and ways to make or link one from here. A task opens in place, with
+ * Back. */
export function TasksPanel({
session,
- channel,
chat,
- readyToLink,
openConversation,
}: {
session: RelaySession;
- channel: TasksChannel;
/** The conversation this panel sits beside. */
chat: string;
-} & Pick) {
- const state = useTasksWithSaved(session, channel.id);
+} & Pick) {
+ const state = useTasksWithSaved(session);
const notify = useToastNotification();
- // A new task carries the links it starts with; consent waits for Create.
- const [open, setOpen] = useState();
+ const [open, setOpen] = useState();
+ const [linked, setLinked] = useState>();
const [linking, setLinking] = useState(false);
- const linked = state.tasks
- .filter((task) => task.links.includes(chat))
- .sort((a, b) => b.updatedAt - a.updatedAt);
+ const [attempt, setAttempt] = useState(0);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a change is a new read.
+ useEffect(() => {
+ const controller = new AbortController();
+ readLinks(session, { conversation: chat }, controller.signal).then(
+ (links) =>
+ !controller.signal.aborted &&
+ setLinked(new Set(links.map((link) => link.task))),
+ () => !controller.signal.aborted && setLinked(new Set()),
+ );
+ return () => controller.abort();
+ }, [session, chat, attempt]);
+ const here = state.tasks
+ .filter((task) => task.home === chat || linked?.has(task.id))
+ .sort(byRecent);
const choices = state.tasks
- .filter((task) => isOpenStatus(task.status) && !task.links.includes(chat))
- .sort((a, b) => b.updatedAt - a.updatedAt)
+ .filter(
+ (task) =>
+ isOpenStatus(task.status) &&
+ task.home !== chat &&
+ !linked?.has(task.id),
+ )
+ .sort(byRecent)
.slice(0, LINK_CHOICES);
- const cleared = async (task: Task) => {
- const outcome = await readyToLink(chat, task.title);
- if (outcome === "unavailable")
- notify("Only this chat’s owner can link it to a task.", "error");
- return outcome === "shared";
- };
- const linkTo = async (task: Task) => {
+ const linkTo = async (task: string) => {
if (linking) return;
setLinking(true);
try {
- if (!(await cleared(task))) return;
- // A task to link to means the tasks channel exists.
- if (!channel.id) return;
- const result = await saveTask(
- session,
- channel.id,
- { ...task, links: [...task.links, chat] },
- task,
- );
- if (result.status === "saved") state.setSaved(result.task);
- else notify("Someone else changed this task. Try again.", "error");
+ await setLink(session, task, chat, true, AbortSignal.timeout(20_000));
+ setAttempt((count) => count + 1);
} catch (reason) {
notify(
reason instanceof Error ? reason.message : "Couldn’t link the task.",
@@ -84,14 +84,22 @@ export function TasksPanel({
}
};
const task =
- typeof open === "string"
+ open && open !== "new"
? state.tasks.find((item) => item.id === open)
: undefined;
- if (open && (typeof open === "object" || task))
+ if (open === "new" || task)
return (
-
setOpen(undefined)}>
+ {
+ setOpen(undefined);
+ // Links may have changed in the task.
+ setAttempt((count) => count + 1);
+ }}
+ >
Back
@@ -99,11 +107,9 @@ export function TasksPanel({
{
state.setSaved(next);
@@ -115,28 +121,28 @@ export function TasksPanel({
);
return (
-
+
setOpen({ newLinks: [chat] })}
+ onClick={() => setOpen("new")}
>
- New task from this chat
+ New task
- Link to a task
+ Link a task
}
/>
{choices.map((item) => (
- void linkTo(item)}>
+ void linkTo(item.id)}>
{item.title || "Untitled task"}
))}
@@ -144,7 +150,7 @@ export function TasksPanel({
- {state.status === "loading" ? null : linked.length ? (
-
- {linked.map((item) => (
+ {state.status === "loading" || !linked ? null : here.length ? (
+
+ {here.map((item) => (
}
@@ -169,8 +175,8 @@ export function TasksPanel({
) : (
}
- title="No tasks linked here"
- description="Make a task from this chat, or link it to one that already exists."
+ title="No tasks here"
+ description="Make a task from this conversation, or link one that already exists."
/>
)}
diff --git a/src/bundled/tasks/conversation.ts b/src/bundled/tasks/conversation.ts
new file mode 100644
index 0000000000..e268a268ed
--- /dev/null
+++ b/src/bundled/tasks/conversation.ts
@@ -0,0 +1,36 @@
+// A task's comments live in its own hidden conversation: a channel of type
+// `artifact` whose id is computed from the task alone, so anyone who can read
+// the task finds it with no lookup. The relay makes it on the first comment,
+// under the task's home, with no members and no owner; who reads and posts
+// there always comes from the home, and a move takes it along.
+import type { RelaySession } from "../../features/relay/session";
+import type { Task } from "./model";
+
+const encoder = new TextEncoder();
+
+/** The conversation id for task `d`: UUIDv8 of the first 16 bytes of
+ * SHA-256("nip-ar-conversation\0" + d), over the UTF-8 bytes of `d`. */
+export async function conversationId(d: string) {
+ const hash = new Uint8Array(
+ await crypto.subtle.digest(
+ "SHA-256",
+ encoder.encode(`nip-ar-conversation\0${d}`),
+ ),
+ ).slice(0, 16);
+ hash[6] = ((hash[6] ?? 0) & 0x0f) | 0x80;
+ hash[8] = ((hash[8] ?? 0) & 0x3f) | 0x80;
+ const hex = [...hash].map((b) => b.toString(16).padStart(2, "0")).join("");
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
+/** Posts `text` in `task`'s conversation, making it first if nobody has.
+ * The app can't yet post in a conversation outside the viewer's list, which
+ * this one always is; until it can, this fails and says so. */
+export async function postComment(
+ _session: RelaySession,
+ _task: Task,
+ _text: string,
+ _signal: AbortSignal,
+): Promise
{
+ throw new Error("Comments aren’t available in this version yet.");
+}
diff --git a/src/bundled/tasks/index.tsx b/src/bundled/tasks/index.tsx
index 86b03976e0..15d84053d6 100644
--- a/src/bundled/tasks/index.tsx
+++ b/src/bundled/tasks/index.tsx
@@ -4,17 +4,24 @@ import type {
PanelProps,
} from "../../features/panels/service";
import type { RelaySnapshot } from "../../features/relay/service";
-import type { ChatSharing } from "../../features/solo/share-requests";
import type { PluginModule } from "../../plugins/api";
import { ClipboardCheckIcon } from "../../shared/design-system/icons/index";
import { IconButton } from "../../shared/design-system/ui/IconButton";
-import { readyToLink } from "./linking";
-import { TasksGate } from "./TasksGate";
+import inlineStyles from "../../shared/InlineReference.module.css";
+import { taskLinkId, taskRoute } from "./route";
+import { TaskLink } from "./TaskLink";
import { TasksPage } from "./TasksPage";
import { TasksPanel } from "./TasksPanel";
import { addTaskTools } from "./tools";
-export const inject = ["pages", "panels", "relay", "navigation", "agents"];
+export const inject = [
+ "pages",
+ "panels",
+ "relay",
+ "navigation",
+ "agents",
+ "conversation",
+];
const scopeOf = (state: RelaySnapshot) =>
state.viewer && state.scope
@@ -29,9 +36,6 @@ export const apply: PluginModule["apply"] = (ctx) => {
ctx.effect(() => () => {
active = false;
});
- // Read when used, so a host without it degrades to "can't link Solo chats".
- const sharing = () =>
- ctx.reflect.get("chatSharing") as ChatSharing | undefined;
ctx.pages.register({
id: "tasks",
@@ -39,16 +43,20 @@ export const apply: PluginModule["apply"] = (ctx) => {
layout: "workspace",
primary: true,
placement: "dock",
+ route: { version: 1, validate: (params) => !!taskRoute(params) },
component: (props) => (
-
+
),
});
+ ctx.conversation.registerLink({
+ id: "task",
+ title: "Task links",
+ matches: (url) => taskLinkId(url) !== null,
+ className: inlineStyles.link,
+ component: ({ url }) => ,
+ });
+
function Launcher({
context,
toggle,
@@ -83,31 +91,20 @@ export const apply: PluginModule["apply"] = (ctx) => {
return (
Connect to this conversation to see its tasks.
);
- const session = state.session;
return (
-
- {(channel) => (
-
- readyToLink(session, sharing(), channelId, { task })
- }
- openConversation={(channelId) =>
- void ctx.navigation.open({
- version: 1,
- kind: "conversation",
- scope,
- channelId,
- })
- }
- />
- )}
-
+ session={state.session}
+ chat={channelContext.channelId}
+ openConversation={(channelId) =>
+ void ctx.navigation.open({
+ version: 1,
+ kind: "conversation",
+ scope,
+ channelId,
+ })
+ }
+ />
);
}
ctx.panels.register({
@@ -119,5 +116,5 @@ export const apply: PluginModule["apply"] = (ctx) => {
component: Panel,
});
- addTaskTools(ctx.agents, sharing);
+ addTaskTools(ctx.agents);
};
diff --git a/src/bundled/tasks/linking.test.ts b/src/bundled/tasks/linking.test.ts
deleted file mode 100644
index 4ee81643b4..0000000000
--- a/src/bundled/tasks/linking.test.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { expect, it, vi } from "vitest";
-import type { ChannelSummary } from "../../features/relay/contracts";
-import type { RelaySession } from "../../features/relay/session";
-import { readyToLink } from "./linking";
-
-const session = (channels: Partial[]) =>
- ({ channels: { list: () => ({ channels }) } }) as unknown as RelaySession;
-
-it("asks the owner only before linking a Solo chat that isn't public", async () => {
- const requestShare = vi.fn(async () => "cancelled" as const);
- const sharing = { requestShare };
- const relay = session([
- { id: "solo", channelType: "solo", visibility: "private" },
- { id: "shared", channelType: "solo", visibility: "public" },
- { id: "unknown", channelType: "solo" },
- { id: "channel", channelType: "stream", visibility: "private" },
- ]);
- expect(await readyToLink(relay, sharing, "channel", { task: "T" })).toBe(
- "shared",
- );
- expect(await readyToLink(relay, sharing, "shared", { task: "T" })).toBe(
- "shared",
- );
- expect(await readyToLink(relay, sharing, "elsewhere", { task: "T" })).toBe(
- "shared",
- );
- expect(requestShare).not.toHaveBeenCalled();
- expect(await readyToLink(relay, sharing, "solo", { task: "T" })).toBe(
- "cancelled",
- );
- expect(await readyToLink(relay, sharing, "unknown", { task: "T" })).toBe(
- "cancelled",
- );
- expect(requestShare).toHaveBeenCalledTimes(2);
- expect(await readyToLink(relay, undefined, "solo", { task: "T" })).toBe(
- "unavailable",
- );
-});
diff --git a/src/bundled/tasks/linking.ts b/src/bundled/tasks/linking.ts
deleted file mode 100644
index fdde2fbc35..0000000000
--- a/src/bundled/tasks/linking.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// Linking records a conversation's id on a task; it never adds anyone to the
-// conversation. Only a private Solo chat needs the owner's consent first: its
-// owner makes it View only through the app's "Share this chat?" confirmation.
-import type { RelaySession } from "../../features/relay/session";
-import type {
- ChatShareOutcome,
- ChatSharing,
-} from "../../features/solo/share-requests";
-
-/** Whether `channelId` may be linked to the task titled `task`, asking to
- * share it when needed. `agent` names the agent asking, if one is. */
-export async function readyToLink(
- session: RelaySession,
- sharing: ChatSharing | undefined,
- channelId: string,
- options: Readonly<{
- task: string;
- agent?: string | undefined;
- signal?: AbortSignal | undefined;
- }>,
-): Promise {
- const channel = session.channels
- .list()
- .channels.find((item) => item.id === channelId);
- // Unknown visibility is not public: ask, and let the app's check decide.
- if (channel?.channelType !== "solo" || channel.visibility === "public")
- return "shared";
- return sharing
- ? sharing.requestShare(session, channelId, {
- signal: options.signal,
- reason: options.agent
- ? `Your agent ${options.agent} wants to link it to the task “${options.task}”.`
- : `To link it to the task “${options.task}”.`,
- })
- : "unavailable";
-}
diff --git a/src/bundled/tasks/links.ts b/src/bundled/tasks/links.ts
new file mode 100644
index 0000000000..9c66fff0f0
--- /dev/null
+++ b/src/bundled/tasks/links.ts
@@ -0,0 +1,143 @@
+// A link between a task and a conversation is stored on the conversation's
+// side: one NIP-AR artifact of type `buzz.task-link` whose home is the linked
+// conversation. Only people who can read that conversation read the link or
+// learn it exists, and linking never changes who can read either side.
+import {
+ ARTIFACT_KIND,
+ deliver,
+ uuidv5,
+} from "../../features/agents/agent-config-artifacts";
+import type { EventData, RelayEvent } from "../../features/relay/events";
+import type { RelaySession } from "../../features/relay/session";
+import { isChannelId } from "./model";
+
+export const LINK_TYPE = "buzz.task-link";
+/** Namespace for link ids, so one task and conversation have one link. */
+const LINK_NAMESPACE = "6f1d0c2e-8a57-4b0e-9c43-2f6a1d9b7e15";
+/** The link's title is public to the conversation; the task's is not. */
+const LINK_TITLE = "Task link";
+const READ_LIMIT = 500;
+
+export type TaskLink = Readonly<{
+ /** The link artifact's `d`. */
+ id: string;
+ task: string;
+ conversation: string;
+ revision: string;
+}>;
+
+const tag = (event: EventData, name: string) =>
+ event.tags.find((entry) => entry[0] === name)?.[1];
+
+export function linkOf(event: RelayEvent): TaskLink | undefined {
+ if (event.kind !== ARTIFACT_KIND || tag(event, "type") !== LINK_TYPE)
+ return undefined;
+ const id = tag(event, "d");
+ const task = tag(event, "task");
+ const conversation = tag(event, "h");
+ if (!isChannelId(id) || !isChannelId(task) || !isChannelId(conversation))
+ return undefined;
+ return { id, task, conversation, revision: event.id };
+}
+
+export const linkId = (task: string, conversation: string) =>
+ uuidv5(LINK_NAMESPACE, `${task}\0${conversation}`);
+
+/** Current links the viewer can read: of `task`, or in `conversation`. */
+export async function readLinks(
+ session: RelaySession,
+ of: Readonly<{ task: string } | { conversation: string }>,
+ signal: AbortSignal,
+): Promise {
+ const read = session.snapshotRead;
+ if (!read) throw new Error("Tasks aren’t available in this community.");
+ const events = await read(
+ [
+ {
+ artifact: "current",
+ kinds: [ARTIFACT_KIND],
+ "#type": [LINK_TYPE],
+ ...("task" in of
+ ? { "#task": [of.task] }
+ : { "#h": [of.conversation] }),
+ limit: READ_LIMIT,
+ },
+ ],
+ { signal },
+ );
+ return events.flatMap((event) => linkOf(event) ?? []);
+}
+
+/** The link's head, including a deletion, or undefined when it never was. */
+async function head(
+ session: RelaySession,
+ id: string,
+ conversation: string,
+ signal: AbortSignal,
+) {
+ const read = session.snapshotRead;
+ if (!read) throw new Error("Tasks aren’t available in this community.");
+ const [event] = await read(
+ [
+ {
+ kinds: [ARTIFACT_KIND],
+ "#h": [conversation],
+ "#d": [id],
+ limit: 1,
+ consistency: "strong",
+ },
+ ],
+ { signal },
+ );
+ return event && tag(event, "d") === id ? event : undefined;
+}
+
+/** Links `task` to `conversation`, or with `unlink` removes the link. Only
+ * people who can post in the conversation can. Doing what is already done
+ * succeeds. */
+export async function setLink(
+ session: RelaySession,
+ task: string,
+ conversation: string,
+ linked: boolean,
+ signal: AbortSignal,
+): Promise {
+ const writer = session.configArtifactWriter;
+ if (!writer) throw new Error("This community connection can’t link tasks.");
+ const id = await linkId(task, conversation);
+ const current = await head(session, id, conversation, signal);
+ const deleted = !current || tag(current, "op") === "delete";
+ if (deleted !== linked) return;
+ const op = linked ? (current ? "restore" : "create") : "delete";
+ const event = await writer.sign(
+ {
+ kind: ARTIFACT_KIND,
+ created_at: Math.floor(Date.now() / 1000),
+ content: linked ? JSON.stringify({ version: 1 }) : "",
+ tags: [
+ ["ar", "1"],
+ ["d", id],
+ ["h", conversation],
+ ["type", LINK_TYPE],
+ ["op", op],
+ ...(current ? [["prev", current.id]] : []),
+ ...(linked
+ ? [
+ ["title", LINK_TITLE],
+ ["task", task],
+ ]
+ : []),
+ ],
+ },
+ signal,
+ );
+ const delivery = await deliver(writer, event, signal);
+ if (delivery.status === "accepted") return;
+ throw new Error(
+ delivery.status === "refused" && delivery.refusal === "permission"
+ ? "You can only link conversations you can post in."
+ : delivery.status === "refused" && delivery.refusal === "conflict"
+ ? "Someone else changed this link. Try again."
+ : "Couldn’t save the link. Try again.",
+ );
+}
diff --git a/src/bundled/tasks/model.test.ts b/src/bundled/tasks/model.test.ts
index 17cdfbdf81..add36bdc1d 100644
--- a/src/bundled/tasks/model.test.ts
+++ b/src/bundled/tasks/model.test.ts
@@ -1,7 +1,7 @@
import { expect, it } from "vitest";
import {
checkedFields,
- filterTasks,
+ isMine,
type Task,
TASK_TYPE,
taskContent,
@@ -10,8 +10,9 @@ import {
const author = "a".repeat(64);
const editor = "b".repeat(64);
-const chat = "11111111-1111-4111-8111-111111111111";
-const other = "22222222-2222-4222-8222-222222222222";
+const third = "c".repeat(64);
+const id = "11111111-1111-4111-8111-111111111111";
+const home = "22222222-2222-4222-8222-222222222222";
const revision = (content: unknown, tags: string[][] = []) => ({
id: "e".repeat(64),
@@ -22,8 +23,8 @@ const revision = (content: unknown, tags: string[][] = []) => ({
content: typeof content === "string" ? content : JSON.stringify(content),
tags: [
["ar", "1"],
- ["d", "task-1"],
- ["h", "tasks"],
+ ["d", id],
+ ["h", home],
["type", TASK_TYPE],
["title", "Fix the header"],
["op", "update"],
@@ -31,28 +32,29 @@ const revision = (content: unknown, tags: string[][] = []) => ({
],
});
-it("reads a revision as the task it snapshots", () => {
+it("reads a revision as the task it snapshots, in its home", () => {
const task = taskOf(
revision({
- version: 1,
+ version: 2,
author,
description: "It clips.",
status: "in_progress",
images: [
{ url: "https://example.org/a.png", type: "image/png", dim: "10x20" },
],
- links: [chat, chat, other],
+ assignees: [author, author, third],
}),
);
expect(task).toEqual({
- id: "task-1",
+ id,
+ home,
title: "Fix the header",
description: "It clips.",
status: "in_progress",
images: [
{ url: "https://example.org/a.png", type: "image/png", dim: "10x20" },
],
- links: [chat, other],
+ assignees: [author, third],
author,
revision: "e".repeat(64),
editor,
@@ -70,20 +72,45 @@ it("drops what an untrusted record can't safely show", () => {
{ url: "javascript:alert(1)" },
{ url: "https://example.org/b.png", type: "text/html", dim: "big" },
],
- links: ["general", 7, chat],
+ assignees: [
+ "someone",
+ 7,
+ "d".repeat(64),
+ "1".repeat(64),
+ "2".repeat(64),
+ "3".repeat(64),
+ "4".repeat(64),
+ ],
}),
);
expect(task?.author).toBe(editor);
- expect(task?.status).toBe("open");
+ expect(task?.status).toBe("todo");
expect(task?.images).toEqual([{ url: "https://example.org/b.png" }]);
- expect(task?.links).toEqual([chat]);
+ expect(task?.assignees).toEqual([
+ "d".repeat(64),
+ "1".repeat(64),
+ "2".repeat(64),
+ "3".repeat(64),
+ ]);
expect(taskOf(revision("not json"))).toBeUndefined();
expect(taskOf(revision([]))).toBeUndefined();
+ // A task needs a home; one from the old shared store had none of its own.
expect(
taskOf({
...revision({}),
tags: [
- ["d", "x"],
+ ["d", id],
+ ["h", "tasks"],
+ ["type", TASK_TYPE],
+ ],
+ }),
+ ).toBeUndefined();
+ expect(
+ taskOf({
+ ...revision({}),
+ tags: [
+ ["d", id],
+ ["h", home],
["type", "other"],
],
}),
@@ -94,14 +121,14 @@ it("checks fields before saving, with reasons people can act on", () => {
const fields = {
title: " Fix the header ",
description: "",
- status: "open" as const,
+ status: "todo" as const,
images: [],
- links: [chat, chat],
+ assignees: [author, author],
};
expect(checkedFields(fields)).toEqual({
...fields,
title: "Fix the header",
- links: [chat],
+ assignees: [author],
});
expect(() => checkedFields({ ...fields, title: " " })).toThrow(
"Give the task a title.",
@@ -109,36 +136,28 @@ it("checks fields before saving, with reasons people can act on", () => {
expect(() => checkedFields({ ...fields, title: "x".repeat(201) })).toThrow(
"under 200",
);
- expect(JSON.parse(taskContent(fields, author))).toEqual({
- version: 1,
+ expect(() => checkedFields({ ...fields, assignees: ["someone"] })).toThrow(
+ "Assign people only.",
+ );
+ expect(() =>
+ checkedFields({
+ ...fields,
+ assignees: ["1", "2", "3", "4", "5"].map((n) => n.repeat(64)),
+ }),
+ ).toThrow("up to 4");
+ expect(JSON.parse(taskContent(checkedFields(fields), author))).toEqual({
+ version: 2,
author,
description: "",
- status: "open",
+ status: "todo",
images: [],
- links: [chat, chat],
+ assignees: [author],
});
});
-it("filters by status and by what's mine, newest first", () => {
- const base = taskOf(revision({ author })) as Task;
- const task = (id: string, extra: Partial): Task => ({
- ...base,
- id,
- ...extra,
- });
- const tasks = [
- task("mine", { updatedAt: 1 }),
- task("linked", { author: editor, links: [chat], updatedAt: 3 }),
- task("theirs", { author: editor, updatedAt: 2 }),
- task("done", { status: "wont_do", updatedAt: 4 }),
- ];
- const ids = (filter: Parameters[1]) =>
- filterTasks(tasks, filter, author, new Set([chat])).map((item) => item.id);
- expect(ids({ status: "open", mine: false })).toEqual([
- "linked",
- "theirs",
- "mine",
- ]);
- expect(ids({ status: "open", mine: true })).toEqual(["linked", "mine"]);
- expect(ids({ status: "done", mine: false })).toEqual(["done"]);
+it("counts a task as mine when I made it or I'm assigned", () => {
+ const task = taskOf(revision({ author: editor })) as Task;
+ expect(isMine(task, editor)).toBe(true);
+ expect(isMine(task, author)).toBe(false);
+ expect(isMine({ ...task, assignees: [author] }, author)).toBe(true);
});
diff --git a/src/bundled/tasks/model.ts b/src/bundled/tasks/model.ts
index b18ad6b51d..6b7f7bb73e 100644
--- a/src/bundled/tasks/model.ts
+++ b/src/bundled/tasks/model.ts
@@ -1,23 +1,25 @@
-// A task is one NIP-AR artifact (kind 45010) of type `buzz.task` in the
-// community's tasks channel. Its content is the complete snapshot; the relay
-// keeps the revision history and refuses an edit whose `prev` is stale.
+// A task is one NIP-AR artifact (kind 45010) of type `buzz.task`. Its `h` is
+// its home, a project, channel or chat, and the relay lets read it whoever
+// can read that home and edit it whoever can post there. Its content is the
+// complete snapshot; the relay keeps the revision history and refuses an
+// edit whose `prev` is stale.
import { ARTIFACT_KIND } from "../../features/agents/agent-config-artifacts";
import type { EventData } from "../../features/relay/events";
export const TASK_TYPE = "buzz.task";
-const CONTENT_VERSION = 1;
+const CONTENT_VERSION = 2;
-export const statuses = ["open", "in_progress", "done", "wont_do"] as const;
+export const statuses = ["todo", "in_progress", "done", "cancelled"] as const;
export type TaskStatus = (typeof statuses)[number];
export const statusLabels: Readonly> = {
- open: "Open",
+ todo: "To do",
in_progress: "In progress",
done: "Done",
- wont_do: "Won’t do",
+ cancelled: "Cancelled",
};
-/** Open includes In progress; Done includes Won't do. */
+/** To do and In progress; Done and Cancelled are closed. */
export const isOpenStatus = (status: TaskStatus) =>
- status === "open" || status === "in_progress";
+ status === "todo" || status === "in_progress";
export type TaskImage = Readonly<{
url: string;
@@ -25,19 +27,21 @@ export type TaskImage = Readonly<{
dim?: string | undefined;
}>;
-/** What people edit. Links are channel ids: linkage, never membership. */
+/** What people edit. Assignees are people's pubkeys. */
export type TaskFields = Readonly<{
title: string;
description: string;
status: TaskStatus;
images: readonly TaskImage[];
- links: readonly string[];
+ assignees: readonly string[];
}>;
export type Task = TaskFields &
Readonly<{
- /** The artifact's `d`. */
+ /** The artifact's `d`: stable across edits and moves. */
id: string;
+ /** The artifact's `h`: the project, channel or chat it lives in. */
+ home: string;
/** Who created it, as its creator's client recorded. */
author: string;
/** The current revision: its id is the next edit's `prev`. */
@@ -47,9 +51,9 @@ export type Task = TaskFields &
updatedAt: number;
}>;
+export const MAX_ASSIGNEES = 4;
const MAX_TITLE = 200;
const MAX_IMAGES = 32;
-const MAX_LINKS = 64;
const HEX64 = /^[0-9a-f]{64}$/;
const CHANNEL =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -59,6 +63,12 @@ const tag = (event: EventData, name: string) =>
const text = (value: unknown) => (typeof value === "string" ? value : "");
+export const isChannelId = (value: unknown): value is string =>
+ typeof value === "string" && CHANNEL.test(value);
+
+export const isPubkey = (value: unknown): value is string =>
+ typeof value === "string" && HEX64.test(value);
+
/** Only HTTPS links render; anything else in an untrusted record is dropped. */
export function imageOf(value: unknown): TaskImage | undefined {
if (!value || typeof value !== "object") return undefined;
@@ -78,15 +88,13 @@ export function imageOf(value: unknown): TaskImage | undefined {
};
}
-export const isChannelId = (value: unknown): value is string =>
- typeof value === "string" && CHANNEL.test(value);
-
/** A current revision as a task, or undefined when it is not a readable one. */
export function taskOf(event: EventData & { id: string }): Task | undefined {
if (event.kind !== ARTIFACT_KIND || tag(event, "type") !== TASK_TYPE)
return undefined;
const id = tag(event, "d");
- if (!id) return undefined;
+ const home = tag(event, "h");
+ if (!isChannelId(id) || !isChannelId(home)) return undefined;
let content: Record;
try {
const parsed: unknown = JSON.parse(event.content);
@@ -96,22 +104,24 @@ export function taskOf(event: EventData & { id: string }): Task | undefined {
} catch {
return undefined;
}
- const status = statuses.find((item) => item === content.status) ?? "open";
const author = text(content.author);
return {
id,
+ home,
title: (tag(event, "title") ?? "").slice(0, MAX_TITLE),
description: text(content.description),
- status,
+ status: statuses.find((item) => item === content.status) ?? "todo",
images: (Array.isArray(content.images) ? content.images : [])
.flatMap((item) => imageOf(item) ?? [])
.slice(0, MAX_IMAGES),
- links: [
+ assignees: [
...new Set(
- (Array.isArray(content.links) ? content.links : []).filter(isChannelId),
+ (Array.isArray(content.assignees) ? content.assignees : []).filter(
+ isPubkey,
+ ),
),
- ].slice(0, MAX_LINKS),
- author: HEX64.test(author) ? author : event.pubkey,
+ ].slice(0, MAX_ASSIGNEES),
+ author: isPubkey(author) ? author : event.pubkey,
revision: event.id,
editor: event.pubkey,
updatedAt: event.created_at,
@@ -126,14 +136,16 @@ export function checkedFields(fields: TaskFields): TaskFields {
throw new Error(`Keep the title under ${MAX_TITLE} characters.`);
if (fields.images.length > MAX_IMAGES)
throw new Error(`A task holds up to ${MAX_IMAGES} images.`);
- if (fields.links.length > MAX_LINKS)
- throw new Error(`A task links up to ${MAX_LINKS} conversations.`);
+ const assignees = [...new Set(fields.assignees)];
+ if (!assignees.every(isPubkey)) throw new Error("Assign people only.");
+ if (assignees.length > MAX_ASSIGNEES)
+ throw new Error(`A task has up to ${MAX_ASSIGNEES} assignees.`);
return {
title,
description: fields.description,
status: fields.status,
images: fields.images,
- links: [...new Set(fields.links)],
+ assignees,
};
}
@@ -145,28 +157,14 @@ export const taskContent = (fields: TaskFields, author: string) =>
description: fields.description,
status: fields.status,
images: fields.images,
- links: fields.links,
+ assignees: fields.assignees,
});
-export type TaskFilter = Readonly<{
- status: "open" | "done";
- mine: boolean;
-}>;
+/** Newest activity first, then by id, so equal times keep one order. */
+export const byRecent = (a: Task, b: Task) =>
+ b.updatedAt - a.updatedAt || a.id.localeCompare(b.id);
-/** Mine: tasks I created, or that link a conversation I'm in. */
-export function filterTasks(
- tasks: readonly Task[],
- filter: TaskFilter,
- viewer: string,
- myChannels: ReadonlySet,
-) {
- return tasks
- .filter(
- (task) =>
- isOpenStatus(task.status) === (filter.status === "open") &&
- (!filter.mine ||
- task.author === viewer ||
- task.links.some((link) => myChannels.has(link))),
- )
- .sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id));
-}
+/** Assigned to the viewer, or created by them. Created by their agent counts
+ * through the author the agent's tools record: the owner. */
+export const isMine = (task: Task, viewer: string) =>
+ task.author === viewer || task.assignees.includes(viewer);
diff --git a/src/bundled/tasks/places.test.ts b/src/bundled/tasks/places.test.ts
new file mode 100644
index 0000000000..b18f952c52
--- /dev/null
+++ b/src/bundled/tasks/places.test.ts
@@ -0,0 +1,61 @@
+import { expect, it } from "vitest";
+import type { Task } from "./model";
+import { accessChange, type Place, projectOf } from "./places";
+
+const project = "00000000-0000-4000-8000-000000000001";
+const mobile = "00000000-0000-4000-8000-000000000002";
+const chat = "00000000-0000-4000-8000-000000000003";
+const other = "00000000-0000-4000-8000-000000000004";
+const loose = "00000000-0000-4000-8000-000000000005";
+
+const places = new Map([
+ [project, { id: project, name: "Buzz", kind: "channel" }],
+ [mobile, { id: mobile, name: "mobile", kind: "channel", parent: project }],
+ [chat, { id: chat, name: "Riley’s chat", kind: "chat", parent: project }],
+ [other, { id: other, name: "Payments", kind: "channel" }],
+ [loose, { id: loose, name: "random", kind: "channel" }],
+]);
+const task = (home: string) => ({ home }) as Task;
+
+it("groups a task under the project its home is filed in", () => {
+ expect(projectOf(task(mobile), places)).toEqual({
+ id: project,
+ name: "Buzz",
+ });
+ expect(projectOf(task(project), places)).toEqual({
+ id: project,
+ name: "Buzz",
+ });
+ expect(projectOf(task(loose), places)).toEqual({
+ id: undefined,
+ name: undefined,
+ });
+});
+
+it("names the places whose people gain or lose access on a move", () => {
+ // Within one project, only the filed place's own people change.
+ expect(accessChange(mobile, chat, places)).toEqual({
+ gain: [places.get(chat)],
+ lose: [places.get(mobile)],
+ });
+ // Up to the project: the project's people already saw it.
+ expect(accessChange(mobile, project, places)).toEqual({
+ gain: [],
+ lose: [places.get(mobile)],
+ });
+ expect(accessChange(mobile, other, places)).toEqual({
+ gain: [places.get(other)],
+ lose: [places.get(mobile), places.get(project)],
+ });
+});
+
+it("never names a place the viewer can't read", () => {
+ const hidden = "00000000-0000-4000-8000-000000000009";
+ const filed = new Map(places).set(loose, {
+ id: loose,
+ name: "random",
+ kind: "channel",
+ parent: hidden,
+ });
+ expect(accessChange(mobile, loose, filed).gain).toEqual([filed.get(loose)]);
+});
diff --git a/src/bundled/tasks/places.ts b/src/bundled/tasks/places.ts
new file mode 100644
index 0000000000..8e4d9569a1
--- /dev/null
+++ b/src/bundled/tasks/places.ts
@@ -0,0 +1,118 @@
+// Where tasks live, for presentation only: each home's name and kind, and
+// the project it is filed in. Read from relay-signed channel metadata
+// (kind 39000) by naming each channel, so places the viewer reads through a
+// project resolve too. A place the viewer can't read stays unnamed. None of
+// this decides access; the relay does.
+import { channelIdentity } from "../../features/relay/channel-labels";
+import { metadataName } from "../../features/relay/discovery";
+import { tag, type RelayEvent } from "../../features/relay/events";
+import type { RelaySession } from "../../features/relay/session";
+import { soloLabels } from "../../features/solo/labels";
+import { isChannelId, type Task } from "./model";
+
+export type Place = Readonly<{
+ id: string;
+ name: string;
+ kind: "chat" | "channel";
+ /** The channel it is filed under (NIP-29 `parent`), if any. */
+ parent?: string | undefined;
+}>;
+
+/** A project as the Tasks page groups by it. `name` is undefined for a
+ * project the viewer can't read. */
+export type ProjectGroup = Readonly<{
+ id: string | undefined;
+ name: string | undefined;
+}>;
+
+const METADATA_LIMIT = 500;
+
+function placeOf(event: RelayEvent): Place | undefined {
+ const id = tag(event, "d");
+ if (!isChannelId(id)) return undefined;
+ const parent = tag(event, "parent");
+ return {
+ id,
+ name: metadataName(event) ?? id.slice(0, 8),
+ kind: soloLabels(channelIdentity(event).labels) ? "chat" : "channel",
+ ...(isChannelId(parent) ? { parent } : {}),
+ };
+}
+
+/** The places named by `ids`, and the projects they are filed in. */
+export async function readPlaces(
+ session: RelaySession,
+ ids: Iterable,
+ signal: AbortSignal,
+): Promise> {
+ const read = session.snapshotRead;
+ const author = session.relayAuthor;
+ const places = new Map();
+ if (!read || !author) return places;
+ const fetch = async (wanted: readonly string[]) => {
+ for (let at = 0; at < wanted.length; at += METADATA_LIMIT) {
+ const page = wanted.slice(at, at + METADATA_LIMIT);
+ const events = await read(
+ [{ kinds: [39000], authors: [author], "#d": page, limit: page.length }],
+ { signal },
+ );
+ for (const event of events) {
+ const place = event.pubkey === author ? placeOf(event) : undefined;
+ if (place && page.includes(place.id)) places.set(place.id, place);
+ }
+ }
+ };
+ await fetch([...new Set(ids)]);
+ const parents = [...places.values()].flatMap((place) =>
+ place.parent && !places.has(place.parent) ? [place.parent] : [],
+ );
+ await fetch([...new Set(parents)]);
+ return places;
+}
+
+/** The project `task` is in: its home's parent, or its home when other
+ * places are filed under it. A home neither filed nor holding anything is
+ * in no project. */
+export function projectOf(
+ task: Task,
+ places: ReadonlyMap,
+): ProjectGroup {
+ const home = places.get(task.home);
+ if (home?.parent)
+ return { id: home.parent, name: places.get(home.parent)?.name };
+ const holds = [...places.values()].some(
+ (place) => place.parent === task.home,
+ );
+ return holds
+ ? { id: task.home, name: home?.name }
+ : { id: undefined, name: undefined };
+}
+
+/** `id` and the places it is filed under, nearest first: everyone who can
+ * read one of these reads what lives in `id`. */
+function chainOf(id: string, places: ReadonlyMap) {
+ const chain = [id];
+ for (let at = places.get(id)?.parent; at && !chain.includes(at); ) {
+ chain.push(at);
+ at = places.get(at)?.parent;
+ }
+ return chain;
+}
+
+/** Whose access a move from `from` to `to` changes, by place: the people of
+ * `gain` start seeing the task, and those of `lose` stop, unless they also
+ * belong to a place in `gain`'s chain. Named places only, never people. */
+export function accessChange(
+ from: string,
+ to: string,
+ places: ReadonlyMap,
+): Readonly<{ gain: readonly Place[]; lose: readonly Place[] }> {
+ const before = chainOf(from, places);
+ const after = chainOf(to, places);
+ const named = (ids: readonly string[]) =>
+ ids.flatMap((id) => places.get(id) ?? []);
+ return {
+ gain: named(after.filter((id) => !before.includes(id))),
+ lose: named(before.filter((id) => !after.includes(id))),
+ };
+}
diff --git a/src/bundled/tasks/react.ts b/src/bundled/tasks/react.ts
index 8031e924b3..e6997669aa 100644
--- a/src/bundled/tasks/react.ts
+++ b/src/bundled/tasks/react.ts
@@ -6,44 +6,57 @@ import {
useSyncExternalStore,
} from "react";
import type { RelaySession } from "../../features/relay/session";
+import type { ChannelSummary } from "../../features/relay/contracts";
+import { useChannelRoster } from "../../features/relay/react";
import type { Task } from "./model";
+import { type Place, readPlaces } from "./places";
import { type TasksState, type TasksView, watchTasks } from "./store";
-import { findTasksChannel, openTasksChannel } from "./tasks-channel";
-const loadingState: TasksState = { status: "loading", tasks: [] };
-const still = (state: TasksState): TasksView => ({
- snapshot: () => state,
+const loading: TasksView = {
+ snapshot: () => ({ status: "loading", tasks: [] }) satisfies TasksState,
subscribe: () => () => {},
dispose: () => {},
-});
-const loading = still(loadingState);
-/** A community nobody has saved a task in yet. */
-const none = still({ status: "live", tasks: [] });
+};
-/** Every current task in `channel`, live while mounted. The watch starts in
- * an effect so each mount owns, and disposes, exactly the one it opened. */
-export function useTasks(session: RelaySession, channel: string | undefined) {
+/** One live view per session, shared by the page, panels and task links,
+ * and closed when the last of them unmounts. */
+const shared = new WeakMap();
+
+function acquire(session: RelaySession) {
+ const entry = shared.get(session) ?? { view: watchTasks(session), users: 0 };
+ entry.users += 1;
+ shared.set(session, entry);
+ return {
+ view: entry.view,
+ release() {
+ entry.users -= 1;
+ if (entry.users > 0) return;
+ shared.delete(session);
+ entry.view.dispose();
+ },
+ };
+}
+
+/** Every current task the viewer can read, live while mounted. */
+export function useTasks(session: RelaySession | undefined): TasksState {
const [view, setView] = useState(loading);
useEffect(() => {
- if (!channel) {
- setView(none);
+ if (!session) {
+ setView(loading);
return;
}
- const next = watchTasks(session, channel);
- setView(next);
- return next.dispose;
- }, [session, channel]);
+ const held = acquire(session);
+ setView(held.view);
+ return held.release;
+ }, [session]);
return useSyncExternalStore(view.subscribe, view.snapshot, view.snapshot);
}
/** Tasks from the live view, with this device's saves shown until the
* relay's copy has them: the same revision, or a strictly newer one. A tie
* keeps the save, the newest this device knows of. */
-export function useTasksWithSaved(
- session: RelaySession,
- channel: string | undefined,
-) {
- const state = useTasks(session, channel);
+export function useTasksWithSaved(session: RelaySession) {
+ const state = useTasks(session);
const [saved, setSavedMap] = useState>(new Map());
const setSaved = useCallback(
(task: Task) =>
@@ -67,54 +80,51 @@ export function useTasksWithSaved(
return { ...state, tasks, setSaved };
}
-/** The community's tasks channel as the page and panel hold it: `id` once
- * someone has saved a task, and `open` to make it on the first save. */
-export type TasksChannel = Readonly<{
- id: string | undefined;
- open(signal: AbortSignal): Promise;
-}>;
-
-export type TasksChannelState =
- | Readonly<{ status: "loading" }>
- | Readonly<{ status: "error"; error: string; retry(): void }>
- | Readonly<{ status: "ready"; channel: TasksChannel }>;
-
-/** The community's tasks channel, looked up but never made by looking. */
-export function useTasksChannel(session: RelaySession): TasksChannelState {
- const [attempt, setAttempt] = useState(0);
- const [result, setResult] = useState<
- { channelId: string | undefined } | { error: string } | undefined
- >();
- const retry = useCallback(() => setAttempt((count) => count + 1), []);
- // biome-ignore lint/correctness/useExhaustiveDependencies: a retry is a new attempt.
+/** Names, kinds and projects of `ids`, read once per distinct set. Places
+ * not yet read are absent; a failed read leaves them unnamed. */
+export function usePlaces(
+ session: RelaySession,
+ ids: readonly string[],
+): ReadonlyMap {
+ const key = [...new Set(ids)].sort().join(",");
+ const [places, setPlaces] = useState>(new Map());
useEffect(() => {
+ if (!key) return;
const controller = new AbortController();
- setResult(undefined);
- findTasksChannel(session, controller.signal).then(
- (channelId) => !controller.signal.aborted && setResult({ channelId }),
- (reason: unknown) =>
+ readPlaces(session, key.split(","), controller.signal).then(
+ (read) =>
!controller.signal.aborted &&
- setResult({
- error:
- reason instanceof Error ? reason.message : "Couldn’t open Tasks.",
- }),
+ setPlaces((current) => new Map([...current, ...read])),
+ () => {},
);
return () => controller.abort();
- }, [session, attempt]);
- const channelId =
- result && "channelId" in result ? result.channelId : undefined;
- const channel = useMemo(
- () => ({
- id: channelId,
- async open(signal) {
- const id = await openTasksChannel(session, signal);
- setResult({ channelId: id });
- return id;
- },
- }),
- [session, channelId],
- );
- if (!result) return { status: "loading" };
- if ("error" in result) return { status: "error", error: result.error, retry };
- return { status: "ready", channel };
+ }, [session, key]);
+ return places;
+}
+
+/** Where the viewer can make or move a task: channels and chats in their
+ * list they can post in. DMs hold no tasks. */
+export const isTaskHome = (channel: ChannelSummary) =>
+ !channel.archived &&
+ !channel.readOnly &&
+ !channel.pending &&
+ !channel.huddle &&
+ channel.viewerRole !== "guest" &&
+ channel.viewerRole !== undefined &&
+ (channel.channelType === "stream" ||
+ channel.channelType === "forum" ||
+ channel.channelType === "solo");
+
+export function useTaskHomes(session: RelaySession) {
+ const { channels } = useChannelRoster(session.channels);
+ return useMemo(() => channels.filter(isTaskHome), [channels]);
+}
+
+/** Whether the viewer may edit tasks in `home`, as far as this device
+ * knows: a guest or read-only place is view only. A place the viewer reads
+ * through its project isn't in their list; the relay decides there. */
+export function useCanEdit(session: RelaySession, home: string) {
+ const { channels } = useChannelRoster(session.channels);
+ const channel = channels.find((item) => item.id === home);
+ return !channel || (!channel.readOnly && channel.viewerRole !== "guest");
}
diff --git a/src/bundled/tasks/route.test.ts b/src/bundled/tasks/route.test.ts
new file mode 100644
index 0000000000..28f62c23a0
--- /dev/null
+++ b/src/bundled/tasks/route.test.ts
@@ -0,0 +1,17 @@
+import { expect, it } from "vitest";
+import { taskLink, taskLinkId, taskRoute } from "./route";
+
+const id = "11111111-1111-4111-8111-111111111111";
+
+it("round-trips a task link and refuses anything else", () => {
+ expect(taskLinkId(taskLink(id))).toBe(id);
+ expect(taskLinkId(`buzz://plugin?id=buzz.tasks&route.task=nope`)).toBeNull();
+ expect(taskLinkId(`buzz://plugin?id=buzz.other&route.task=${id}`)).toBeNull();
+ expect(
+ taskLinkId(`buzz://plugin?id=buzz.tasks&route.task=${id}&page=x`),
+ ).toBeNull();
+ expect(taskLinkId(`https://example.org/?route.task=${id}`)).toBeNull();
+ expect(taskRoute({ task: id })).toBe(id);
+ expect(taskRoute({ task: id, more: "x" })).toBeUndefined();
+ expect(taskRoute([id])).toBeUndefined();
+});
diff --git a/src/bundled/tasks/route.ts b/src/bundled/tasks/route.ts
new file mode 100644
index 0000000000..2ffbbf88ce
--- /dev/null
+++ b/src/bundled/tasks/route.ts
@@ -0,0 +1,39 @@
+// A task's link: `buzz://plugin?id=buzz.tasks&route.task=`. It opens the
+// Tasks page with the task, in whichever community the link is opened, and
+// grants nothing: the reader sees the task only if they already can.
+import type { JsonValue } from "../../features/navigation/targets";
+import { isChannelId } from "./model";
+
+export const PLUGIN_ID = "buzz.tasks";
+
+export const taskLink = (id: string) =>
+ `buzz://plugin?id=${PLUGIN_ID}&route.task=${id}`;
+
+/** The task route's params, as the Tasks page accepts them. */
+export function taskRoute(params: JsonValue | undefined) {
+ if (!params || typeof params !== "object" || Array.isArray(params))
+ return undefined;
+ const { task, ...rest } = params as Readonly>;
+ return isChannelId(task) && !Object.keys(rest).length ? task : undefined;
+}
+
+/** The task a link names, or null when it isn't a task link. */
+export function taskLinkId(href: string) {
+ try {
+ const url = new URL(href);
+ if (url.protocol !== "buzz:" || url.hostname !== "plugin") return null;
+ if (url.pathname !== "" && url.pathname !== "/") return null;
+ const keys = [...url.searchParams.keys()];
+ if (
+ url.searchParams.get("id") !== PLUGIN_ID ||
+ keys.length !== 2 ||
+ !keys.includes("route.task")
+ )
+ return null;
+ return (
+ taskRoute({ task: url.searchParams.get("route.task") ?? "" }) ?? null
+ );
+ } catch {
+ return null;
+ }
+}
diff --git a/src/bundled/tasks/similar.ts b/src/bundled/tasks/similar.ts
new file mode 100644
index 0000000000..d0175488a3
--- /dev/null
+++ b/src/bundled/tasks/similar.ts
@@ -0,0 +1,47 @@
+// Plain word comparison for tasks: enough to catch an agent describing the
+// same thing twice, never a judgment a person should make.
+const SMALL = new Set([
+ "a",
+ "an",
+ "and",
+ "the",
+ "to",
+ "of",
+ "in",
+ "on",
+ "for",
+ "with",
+ "is",
+ "it",
+ "this",
+ "that",
+ "be",
+ "by",
+ "at",
+ "or",
+ "from",
+ "as",
+]);
+
+const words = (text: string) =>
+ new Set(
+ text
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}]+/u)
+ .filter((word) => word && !SMALL.has(word)),
+ );
+
+/** How alike two titles are, from 0 to 1: shared words over all words. */
+export function sameness(a: string, b: string) {
+ const left = words(a);
+ const right = words(b);
+ if (!left.size || !right.size) return 0;
+ const shared = [...left].filter((word) => right.has(word)).length;
+ return shared / (left.size + right.size - shared);
+}
+
+/** Whether `text` holds every word of `query`. */
+export function holdsWords(query: string, text: string) {
+ const have = words(text);
+ return [...words(query)].every((word) => have.has(word));
+}
diff --git a/src/bundled/tasks/store.test.ts b/src/bundled/tasks/store.test.ts
index d57a202e34..e7b3261a81 100644
--- a/src/bundled/tasks/store.test.ts
+++ b/src/bundled/tasks/store.test.ts
@@ -2,27 +2,30 @@ 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 { saveTask } from "./store";
+import { readTask, saveTask } from "./store";
const viewer = "a".repeat(64);
+const id = "11111111-1111-4111-8111-111111111111";
+const home = "22222222-2222-4222-8222-222222222222";
+const away = "33333333-3333-4333-8333-333333333333";
const fields: TaskFields = {
title: "Fix the header",
description: "It clips.",
- status: "open",
+ status: "todo",
images: [],
- links: [],
+ assignees: [],
};
-const head = (id: string, content: object) => ({
- id,
+const head = (revision: string, content: object = {}, at = home) => ({
+ id: revision,
pubkey: "b".repeat(64),
sig: "",
created_at: 5,
kind: 45010,
- content: JSON.stringify({ version: 1, author: viewer, ...content }),
+ content: JSON.stringify({ version: 2, author: viewer, ...content }),
tags: [
["ar", "1"],
- ["d", "task-1"],
- ["h", "tasks"],
+ ["d", id],
+ ["h", at],
["type", TASK_TYPE],
["title", "Fix the header"],
["op", "update"],
@@ -36,29 +39,47 @@ function session(publish: () => Promise, heads: object[] = []) {
pubkey: viewer,
sig: "",
}));
+ const read = vi.fn(async () => heads);
return {
sign,
+ read,
session: {
viewer,
- snapshotRead: vi.fn(async () => heads),
+ snapshotRead: read,
configArtifactWriter: { sign, publish: vi.fn(publish) },
} as unknown as RelaySession,
};
}
+const tagsOf = (sign: ReturnType["sign"], call: number) =>
+ (sign.mock.calls[call]?.[0] as unknown as { tags: string[][] } | undefined)
+ ?.tags ?? [];
-it("creates a task, then edits only the revision it opened", async () => {
+it("creates a task in its home, then edits only the revision it opened", async () => {
const { session: relay, sign } = session(async () => "");
- const created = await saveTask(relay, "tasks", fields, undefined);
+ const created = await saveTask(relay, fields, { op: "create", home, id });
expect(created.status).toBe("saved");
- const tags = sign.mock.calls[0]?.[0] as unknown as { tags: string[][] };
- expect(tags.tags).toContainEqual(["op", "create"]);
- expect(tags.tags.some(([name]) => name === "prev")).toBe(false);
+ expect(tagsOf(sign, 0)).toContainEqual(["op", "create"]);
+ expect(tagsOf(sign, 0)).toContainEqual(["h", home]);
+ expect(tagsOf(sign, 0).some(([name]) => name === "prev")).toBe(false);
if (created.status !== "saved") return;
- await saveTask(relay, "tasks", { ...fields, status: "done" }, created.task);
- const update = sign.mock.calls[1]?.[0] as unknown as { tags: string[][] };
- expect(update.tags).toContainEqual(["op", "update"]);
- expect(update.tags).toContainEqual(["prev", created.task.revision]);
- expect(update.tags).toContainEqual(["d", created.task.id]);
+ await saveTask(
+ relay,
+ { ...fields, status: "done" },
+ { op: "update", base: created.task },
+ );
+ expect(tagsOf(sign, 1)).toContainEqual(["op", "update"]);
+ expect(tagsOf(sign, 1)).toContainEqual(["prev", created.task.revision]);
+ expect(tagsOf(sign, 1)).toContainEqual(["h", home]);
+});
+
+it("moves a task as a revision whose home is the new place", async () => {
+ const { session: relay, sign } = session(async () => "");
+ const base = taskOf(head("d".repeat(64))) as Task;
+ const moved = await saveTask(relay, fields, { op: "move", base, home: away });
+ expect(moved.status === "saved" && moved.task.home).toBe(away);
+ expect(tagsOf(sign, 0)).toContainEqual(["op", "move"]);
+ expect(tagsOf(sign, 0)).toContainEqual(["h", away]);
+ expect(tagsOf(sign, 0)).toContainEqual(["prev", base.revision]);
});
it("reports someone else's save as a conflict with their version", async () => {
@@ -66,55 +87,59 @@ it("reports someone else's save as a conflict with their version", async () => {
const { session: relay } = session(async () => {
throw new PublishRejected("rejected", "conflict: stale prev");
}, [theirs]);
- const base = taskOf(head("d".repeat(64), {})) as Task;
- const result = await saveTask(relay, "tasks", fields, base);
+ const base = taskOf(head("d".repeat(64))) as Task;
+ const result = await saveTask(relay, fields, { op: "update", base });
expect(result).toEqual({ status: "conflict", current: taskOf(theirs) });
});
it("confirms an uncertain save from the head, else says it failed", async () => {
- const base = taskOf(head("d".repeat(64), {})) as Task;
+ const base = taskOf(head("d".repeat(64))) as Task;
const landed = session(async () => {
throw new Error("socket closed");
- }, [head("f".repeat(64), {})]);
- expect((await saveTask(landed.session, "tasks", fields, base)).status).toBe(
- "saved",
- );
+ }, [head("f".repeat(64))]);
+ expect(
+ (await saveTask(landed.session, fields, { op: "update", base })).status,
+ ).toBe("saved");
const lost = session(async () => {
throw new Error("socket closed");
- }, [head("d".repeat(64), {})]);
- await expect(saveTask(lost.session, "tasks", fields, base)).rejects.toThrow(
- "Couldn’t save the task. Try again.",
- );
+ }, [head("d".repeat(64))]);
+ await expect(
+ saveTask(lost.session, fields, { op: "update", base }),
+ ).rejects.toThrow("Couldn’t save the task. Try again.");
+});
+
+it("says why the relay refused, for an edit and for a move", async () => {
+ const base = taskOf(head("d".repeat(64))) as Task;
const refused = session(async () => {
throw new PublishRejected("rejected", "restricted: not a member");
});
await expect(
- saveTask(refused.session, "tasks", fields, base),
- ).rejects.toThrow("You can’t edit tasks in this community.");
+ saveTask(refused.session, fields, { op: "update", base }),
+ ).rejects.toThrow("You can only view tasks here.");
+ await expect(
+ saveTask(refused.session, fields, { op: "move", base, home: away }),
+ ).rejects.toThrow("between places you can post in");
});
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");
- }, [
- {
- ...head("f".repeat(64), {}),
- tags: [
- ["d", "chosen"],
- ["type", TASK_TYPE],
- ["title", "Fix the header"],
- ],
- },
- ]);
- const result = await saveTask(
- relay,
- "tasks",
- fields,
- undefined,
- undefined,
- "chosen",
- );
+ }, [head("f".repeat(64))]);
+ const result = await saveTask(relay, fields, { op: "create", home, id });
expect(result.status).toBe("saved");
- const template = sign.mock.calls[0]?.[0] as unknown as { tags: string[][] };
- expect(template.tags).toContainEqual(["d", "chosen"]);
+ expect(tagsOf(sign, 0)).toContainEqual(["d", id]);
+});
+
+it("finds a moved task when its old home no longer has it", async () => {
+ const read = vi
+ .fn()
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([head("d".repeat(64), {}, away)]);
+ const relay = { snapshotRead: read } as unknown as RelaySession;
+ const task = await readTask(relay, id, AbortSignal.timeout(1000), home);
+ expect(task?.home).toBe(away);
+ expect(read.mock.calls[0]?.[0]).toEqual([
+ expect.objectContaining({ "#h": [home], "#d": [id] }),
+ ]);
+ expect(read.mock.calls[1]?.[0]?.[0]).not.toHaveProperty("#h");
});
diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts
index 5cf3e79018..58d5e282b7 100644
--- a/src/bundled/tasks/store.ts
+++ b/src/bundled/tasks/store.ts
@@ -1,10 +1,10 @@
-// Reading and saving tasks in one tasks channel. Reads follow the relay's
-// NIP-AR sync where it has one; saves are compare-and-set on the head the
-// editor opened, so a concurrent edit is reported, never overwritten.
+// Reading and saving tasks. Each task lives in its home; reads ask the relay
+// for every task the viewer can read, wherever it lives, and the relay alone
+// decides that. Saves are compare-and-set on the revision the editor opened,
+// so a concurrent edit is reported, never overwritten.
import {
ARTIFACT_KIND,
deliver,
- readHead,
} from "../../features/agents/agent-config-artifacts";
import type { RelayEvent } from "../../features/relay/events";
import type { RelaySession } from "../../features/relay/session";
@@ -32,46 +32,41 @@ export type TasksView = Readonly<{
/** The session reader's cap on one finite read. */
const READ_LIMIT = 500;
+const taskFilter = { kinds: [ARTIFACT_KIND], "#type": [TASK_TYPE] };
+
const toTasks = (events: readonly RelayEvent[]) =>
events.flatMap((event) => taskOf(event) ?? []);
-/** Every current task in `channel`, kept current while subscribed. */
-export function watchTasks(session: RelaySession, channel: string): TasksView {
+/** Every current task the viewer can read, kept current while subscribed. */
+export function watchTasks(session: RelaySession): TasksView {
const listeners = new Set<() => void>();
let state: TasksState = { status: "loading", tasks: [] };
const set = (next: TasksState) => {
state = next;
for (const listener of listeners) listener();
};
- const filter = {
+ const sync = session.artifacts.sync({
artifact: "current" as const,
- kinds: [ARTIFACT_KIND],
- "#h": [channel],
- "#type": [TASK_TYPE],
- };
- const sync = session.artifacts.sync(filter);
+ ...taskFilter,
+ });
let fallback: AbortController | undefined;
// A relay without sync gets one finite read; saves on this device still
// show through `saved`.
const readOnce = () => {
- if (fallback || !session.snapshotRead) {
- if (!session.snapshotRead)
- set({
- status: "error",
- tasks: [],
- error: "Tasks aren’t available in this community.",
- });
+ if (fallback) return;
+ if (!session.snapshotRead) {
+ set({
+ status: "error",
+ tasks: [],
+ error: "Tasks aren’t available in this community.",
+ });
return;
}
const controller = new AbortController();
fallback = controller;
- session
- .snapshotRead([{ ...filter, limit: READ_LIMIT }], {
- signal: controller.signal,
- })
- .then((events) => {
- if (!controller.signal.aborted)
- set({ status: "live", tasks: toTasks(events) });
+ readTasks(session, controller.signal)
+ .then((tasks) => {
+ if (!controller.signal.aborted) set({ status: "live", tasks });
})
.catch((reason: unknown) => {
if (!controller.signal.aborted)
@@ -122,28 +117,77 @@ export function watchTasks(session: RelaySession, channel: string): TasksView {
};
}
+/** One finite read of every current task the viewer can read. */
+export async function readTasks(
+ session: RelaySession,
+ signal: AbortSignal,
+): Promise {
+ const read = session.snapshotRead;
+ if (!read) throw new Error("Tasks aren’t available in this community.");
+ return toTasks(
+ await read([{ artifact: "current", ...taskFilter, limit: READ_LIMIT }], {
+ signal,
+ }),
+ );
+}
+
+/** Task `id`'s current revision, or undefined when the viewer can't read it
+ * or it was deleted. `home`, when known, names its home, so a task readable
+ * only by naming its home is found too. */
+export async function readTask(
+ session: RelaySession,
+ id: string,
+ signal: AbortSignal,
+ home?: string,
+): Promise {
+ const read = session.snapshotRead;
+ if (!read) throw new Error("Tasks aren’t available in this community.");
+ const events = await read(
+ [
+ {
+ artifact: "current",
+ ...taskFilter,
+ "#d": [id],
+ ...(home ? { "#h": [home] } : {}),
+ limit: 2,
+ },
+ ],
+ { signal },
+ );
+ const tasks = toTasks(events).filter((task) => task.id === id);
+ // A moved task named by its old home reads as missing; ask without it.
+ if (!tasks.length && home) return readTask(session, id, signal);
+ return tasks.length === 1 ? tasks[0] : undefined;
+}
+
export type SaveResult =
| Readonly<{ status: "saved"; task: Task }>
/** Someone else saved first; `current` is their version, the next base. */
| Readonly<{ status: "conflict"; current: Task }>;
-/** Creates task `id` (no `base`) or saves `fields` over the `base` revision.
- * A new task's caller keeps one `id` across retries, so a create that landed
- * unseen is found, not made twice. */
+/** What a save does: create task `id` in `home`, update `base` where it
+ * lives, or move `base` to `home` with `fields` as its snapshot. */
+export type SaveTarget =
+ | Readonly<{ op: "create"; home: string; id: string }>
+ | Readonly<{ op: "update"; base: Task }>
+ | Readonly<{ op: "move"; base: Task; home: string }>;
+
+/** Saves one revision. A new task's caller keeps one `id` across retries, so
+ * a create that landed unseen is found, not made twice. */
export async function saveTask(
session: RelaySession,
- channel: string,
fields: TaskFields,
- base: Task | undefined,
+ target: SaveTarget,
signal: AbortSignal = AbortSignal.timeout(20_000),
- id: string = base?.id ?? crypto.randomUUID(),
): Promise {
- const read = session.snapshotRead;
const writer = session.configArtifactWriter;
const viewer = session.viewer;
- if (!read || !writer || !viewer)
+ if (!session.snapshotRead || !writer || !viewer)
throw new Error("This community connection can’t save tasks.");
const checked = checkedFields(fields);
+ const base = target.op === "create" ? undefined : target.base;
+ const id = base?.id ?? (target.op === "create" ? target.id : "");
+ const home = target.op === "update" ? target.base.home : target.home;
const event = await writer.sign(
{
kind: ARTIFACT_KIND,
@@ -152,10 +196,10 @@ export async function saveTask(
tags: [
["ar", "1"],
["d", id],
- ["h", channel],
+ ["h", home],
["type", TASK_TYPE],
["title", checked.title],
- ["op", base ? "update" : "create"],
+ ["op", target.op],
...(base ? [["prev", base.revision]] : []),
],
},
@@ -172,10 +216,9 @@ export async function saveTask(
delivery.status === "uncertain"
) {
// The head shows whether this revision landed, or whose did instead.
- const head = await readHead(read, channel, id, signal).catch(
+ const current = await readTask(session, id, signal, home).catch(
() => undefined,
);
- const current = head && taskOf(head);
if (current?.revision === event.id)
return { status: "saved", task: current };
if (delivery.status === "refused" && current)
@@ -185,7 +228,9 @@ export async function saveTask(
}
throw new Error(
delivery.status === "refused" && delivery.refusal === "permission"
- ? "You can’t edit tasks in this community."
+ ? 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."
: "Couldn’t save the task. Try again.",
diff --git a/src/bundled/tasks/tasks-channel.test.ts b/src/bundled/tasks/tasks-channel.test.ts
deleted file mode 100644
index 3407902d46..0000000000
--- a/src/bundled/tasks/tasks-channel.test.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { expect, it, vi } from "vitest";
-import type { ChannelSummary } from "../../features/relay/contracts";
-import type { RelaySession } from "../../features/relay/session";
-import { openTasksChannel, TASKS_LABEL } from "./tasks-channel";
-
-const relay = "r".repeat(64);
-const alice = "a".repeat(64);
-const bob = "b".repeat(64);
-const metadata = (id: string, creator: string, labels = [TASKS_LABEL]) => ({
- id: id.padEnd(64, "0"),
- pubkey: relay,
- sig: "",
- created_at: 1,
- kind: 39000,
- content: "",
- tags: [
- ["d", id],
- ["t", "system"],
- ...labels.map((label) => ["t", label]),
- ["P", creator],
- ],
-});
-const channel = (
- id: string,
- creator: string,
- createdAt: number,
- extra: Partial = {},
-): ChannelSummary => ({
- id,
- name: "Tasks",
- channelType: "system",
- creator,
- createdAt,
- labels: [TASKS_LABEL],
- ...extra,
-});
-
-function fixture(byCreator: Record) {
- const events = Object.entries(byCreator).flatMap(([creator, list]) =>
- list.map((item) => metadata(item.id, creator)),
- );
- const create = vi.fn(async () => {
- byCreator[alice] = [...(byCreator[alice] ?? []), channel("mine", alice, 9)];
- events.push(metadata("mine", alice));
- return "mine";
- });
- const session = {
- relayAuthor: relay,
- snapshotRead: vi.fn(async () => [
- ...events,
- metadata("config", bob, ["buzz.agent"]),
- ]),
- channels: {
- findLabeled: vi.fn(
- async ({ creator }: { creator: string }) => byCreator[creator] ?? [],
- ),
- },
- channelCreation: { create },
- } as unknown as RelaySession;
- return { session, create, events };
-}
-
-it("uses the community's oldest open tasks channel, whoever made it", async () => {
- const { session, create } = fixture({
- [alice]: [channel("later", alice, 5)],
- [bob]: [
- channel("first", bob, 2),
- channel("archived", bob, 1, { archived: true }),
- channel("locked", bob, 1, { private: true }),
- ],
- });
- expect(await openTasksChannel(session, new AbortController().signal)).toBe(
- "first",
- );
- expect(create).not.toHaveBeenCalled();
-});
-
-it("makes the channel on the community's first use", async () => {
- const { session, create } = fixture({});
- expect(await openTasksChannel(session, new AbortController().signal)).toBe(
- "mine",
- );
- expect(create).toHaveBeenCalledWith(
- expect.objectContaining({
- system: true,
- visibility: "open",
- labels: [TASKS_LABEL],
- }),
- );
-});
-
-it("makes one channel when the page, panel and tools open together", async () => {
- const { session, create } = fixture({});
- const signal = new AbortController().signal;
- const opened = await Promise.all([
- openTasksChannel(session, signal),
- openTasksChannel(session, signal),
- openTasksChannel(session, signal),
- ]);
- expect(opened).toEqual(["mine", "mine", "mine"]);
- expect(create).toHaveBeenCalledOnce();
-});
-
-it("lets one caller stop waiting without failing the others", async () => {
- const { session, create } = fixture({});
- const leaving = new AbortController();
- const left = openTasksChannel(session, leaving.signal);
- const staying = openTasksChannel(session, new AbortController().signal);
- leaving.abort();
- await expect(left).rejects.toThrow();
- expect(await staying).toBe("mine");
- expect(create).toHaveBeenCalledOnce();
-});
-
-it("converges on the older channel when two first saves race", async () => {
- const byCreator: Record = {};
- const { session, events } = fixture(byCreator);
- // Bob's channel lands, older, while Alice is creating hers.
- const create = session.channelCreation.create as ReturnType;
- create.mockImplementationOnce(async () => {
- byCreator[bob] = [channel("bobs", bob, 3)];
- byCreator[alice] = [channel("mine", alice, 9)];
- events.push(metadata("bobs", bob), metadata("mine", alice));
- return "mine";
- });
- expect(await openTasksChannel(session, new AbortController().signal)).toBe(
- "bobs",
- );
-});
diff --git a/src/bundled/tasks/tasks-channel.ts b/src/bundled/tasks/tasks-channel.ts
deleted file mode 100644
index 2d07f077eb..0000000000
--- a/src/bundled/tasks/tasks-channel.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-// The community's tasks live in one open NIP-CL system channel: hidden from
-// channel lists, readable and writable by everyone in the community. The
-// first person to save a task creates it, and its creator owns it; looking
-// never does. Concurrent first saves can each create one; everyone uses the
-// oldest (NIP-CL "Choosing one channel"), and each creator looks again after
-// creating, so they converge before any task is saved. What remains: a
-// connection keeps the channel it found, so a channel archived later, or more
-// than MAX_CREATORS racing creators, is only resolved again on reconnect.
-import {
- channelIdentity,
- compareChannelAge,
-} from "../../features/relay/channel-labels";
-import type { ChannelSummary } from "../../features/relay/contracts";
-import type { RelaySession } from "../../features/relay/session";
-
-export const TASKS_LABEL = "buzz.tasks";
-const TASKS_CHANNEL_NAME = "Tasks";
-/** One page of open system channels; a community has few. */
-const SYSTEM_CHANNELS_READ = 500;
-/** Different creators only happen when first uses race. */
-const MAX_CREATORS = 8;
-
-const isTasksChannel = (channel: ChannelSummary) =>
- channel.channelType === "system" &&
- !channel.private &&
- !channel.archived &&
- !!channel.labels?.includes(TASKS_LABEL);
-
-// Once found, a community's tasks channel stays put for that connection, so
-// each panel and tool call doesn't look it up again.
-const found = new WeakMap();
-// One creation per connection at a time: the page, the panel and agent tools
-// opening together share it.
-const opening = new WeakMap>();
-/** How long one shared creation may take, whoever is waiting for it. */
-const OPEN_TIMEOUT = 30_000;
-
-/** The community's tasks channel, or undefined when nobody has made one.
- * Throws when it can't tell. */
-export async function findTasksChannel(
- session: RelaySession,
- signal: AbortSignal,
-): Promise {
- const known = found.get(session);
- if (known) return known;
- const findLabeled = session.channels.findLabeled;
- const read = session.snapshotRead;
- const author = session.relayAuthor;
- if (!findLabeled || !read || !author)
- throw new Error("Tasks aren’t available in this community.");
- // A label alone never returns system channels, and its creator isn't
- // known yet: ask for system channels, then keep the labeled ones' creators.
- const events = await read(
- [
- {
- kinds: [39000],
- authors: [author],
- "#t": ["system"],
- limit: SYSTEM_CHANNELS_READ,
- consistency: "strong",
- },
- ],
- { signal },
- );
- const creators = [
- ...new Set(
- events.flatMap((event) => {
- const identity = channelIdentity(event);
- return event.pubkey === author &&
- identity.type === "system" &&
- identity.labels.includes(TASKS_LABEL) &&
- identity.creator
- ? [identity.creator]
- : [];
- }),
- ),
- ].slice(0, MAX_CREATORS);
- // findLabeled verifies each channel's relay-signed creator and labels.
- const oldest = (
- await Promise.all(
- creators.map((creator) =>
- findLabeled(
- { creator, label: TASKS_LABEL },
- { consistency: "strong", signal },
- ),
- ),
- )
- )
- .flat()
- .filter(isTasksChannel)
- .sort(compareChannelAge)[0];
- if (oldest) found.set(session, oldest.id);
- return oldest?.id;
-}
-
-/** The tasks channel, created when this is the community's first save. */
-export function openTasksChannel(
- session: RelaySession,
- signal: AbortSignal,
-): Promise {
- signal.throwIfAborted();
- let shared = opening.get(session);
- if (!shared) {
- shared = create(session, AbortSignal.timeout(OPEN_TIMEOUT));
- opening.set(session, shared);
- const clear = () => {
- if (opening.get(session) === shared) opening.delete(session);
- };
- shared.then(clear, clear);
- }
- return untilAborted(shared, signal);
-}
-
-async function create(session: RelaySession, signal: AbortSignal) {
- const existing = await findTasksChannel(session, signal);
- if (existing) return existing;
- await session.channelCreation.create({
- name: TASKS_CHANNEL_NAME,
- visibility: "open",
- labels: [TASKS_LABEL],
- system: true,
- });
- signal.throwIfAborted();
- // Find again rather than trust the create: a concurrent first use may own
- // the older channel.
- const created = await findTasksChannel(session, signal);
- if (!created) throw new Error("Tasks isn’t ready yet. Try again.");
- return created;
-}
-
-/** `work`, unless `signal` aborts first; the work itself goes on for others. */
-function untilAborted(work: Promise, signal: AbortSignal): Promise {
- return new Promise((resolve, reject) => {
- const stop = () => reject(signal.reason);
- signal.addEventListener("abort", stop, { once: true });
- work
- .then(resolve, reject)
- .finally(() => signal.removeEventListener("abort", stop));
- });
-}
diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts
index db729cdfb5..076acf3721 100644
--- a/src/bundled/tasks/tools.test.ts
+++ b/src/bundled/tasks/tools.test.ts
@@ -4,51 +4,50 @@ import type { RelaySession } from "../../features/relay/session";
import { TASK_TYPE } from "./model";
import { addTaskTools } from "./tools";
-const channel = vi.hoisted(() => ({ id: "tasks" as string | undefined }));
-vi.mock("./tasks-channel", () => ({
- findTasksChannel: async () => channel.id,
- openTasksChannel: async () => (channel.id = "tasks"),
-}));
-
const viewer = "a".repeat(64);
-const solo = "11111111-1111-4111-8111-111111111111";
-const head = (id: string, content: object) => ({
- id,
+const agent = "9".repeat(64);
+const person = "b".repeat(64);
+const id = "11111111-1111-4111-8111-111111111111";
+const chat = "22222222-2222-4222-8222-222222222222";
+const home = "33333333-3333-4333-8333-333333333333";
+
+const head = (
+ revision: string,
+ content: object,
+ extra: { d?: string; title?: string } = {},
+) => ({
+ id: revision,
pubkey: viewer,
sig: "",
created_at: 5,
kind: 45010,
- content: JSON.stringify({ version: 1, author: viewer, ...content }),
+ content: JSON.stringify({ version: 2, author: viewer, ...content }),
tags: [
- ["d", "task-1"],
+ ["d", extra.d ?? id],
+ ["h", home],
["type", TASK_TYPE],
- ["title", "Fix the header"],
+ ["title", extra.title ?? "Fix the header"],
],
});
-function setup(
- publish: () => Promise,
- heads: () => object[],
- share: "shared" | "cancelled" = "shared",
-) {
- const signed: { content: string; tags: string[][] }[] = [];
+type Signed = { kind: number; content: string; tags: string[][] };
+
+function setup(publish: () => Promise, heads: () => object[]) {
+ const signed: Signed[] = [];
const session = {
viewer,
- channels: {
- list: () => ({
- channels: [
- {
- id: solo,
- name: "Header",
- channelType: "solo",
- visibility: "private",
- },
- ],
- }),
+ profiles: {
+ snapshot: () =>
+ new Map([
+ [agent, { name: "Fizz", isAgent: true }],
+ [person, { name: "Riley" }],
+ ]),
},
- snapshotRead: vi.fn(async () => heads()),
+ snapshotRead: vi.fn(async (filters: { kinds?: number[] }[]) =>
+ filters[0]?.kinds?.includes(45010) ? heads() : [],
+ ),
configArtifactWriter: {
- sign: vi.fn(async (template: { content: string; tags: string[][] }) => {
+ sign: vi.fn(async (template: Signed) => {
signed.push(template);
return {
...template,
@@ -64,132 +63,179 @@ function setup(
string,
(args: Record) => Promise
>();
- const requestShare = vi.fn(async () => share);
- addTaskTools(
- {
- relay: () =>
- ({ snapshot: () => ({ status: "ready", session }) }) as never,
- snapshot: () =>
- ({ agents: [{ key: "agent", name: "Fizz" }], running: [] }) as never,
- addTool: (tool) => {
- tools.set(tool.name, (args) =>
- tool.call(
- { key: "agent", signal: new AbortController().signal } as never,
- { channel: solo },
- args,
- ),
- );
- },
+ addTaskTools({
+ relay: () => ({ snapshot: () => ({ status: "ready", session }) }) as never,
+ addTool: (tool) => {
+ tools.set(tool.name, (args) =>
+ tool.call(
+ { key: "agent", signal: new AbortController().signal } as never,
+ { channel: chat },
+ args,
+ ),
+ );
},
- () => ({ requestShare }),
- );
- return { tools, signed, requestShare };
+ });
+ const call = (name: string, args: Record) => {
+ const tool = tools.get(name);
+ if (!tool) throw new Error(`no ${name}`);
+ return tool(args);
+ };
+ return { call, signed };
}
+const artifacts = (signed: Signed[]) =>
+ signed.filter((event) => event.kind === 45010);
+const typeOf = (event: Signed | undefined) =>
+ event?.tags.find((tag) => tag[0] === "type")?.[1];
-it("creates nothing when the owner declines to share the chat", async () => {
- const { tools, signed, requestShare } = setup(
- async () => "",
- () => [],
- "cancelled",
- );
- await expect(
- tools.get("tasks_create")?.({ title: "Fix the header" }),
- ).rejects.toThrow("chose not to share");
- expect(requestShare).toHaveBeenCalledOnce();
- expect(signed).toHaveLength(0);
+it("offers exactly find, create, update and comment", () => {
+ const names: string[] = [];
+ addTaskTools({
+ relay: () => undefined as never,
+ addTool: (tool) => void names.push(tool.name),
+ });
+ expect(names).toEqual([
+ "tasks_find",
+ "tasks_create",
+ "tasks_update",
+ "tasks_comment",
+ ]);
});
-it("creates a task linked to this chat once shared", async () => {
- const { tools, signed } = setup(
+it("creates in the named place and links this chat, posting nothing", async () => {
+ const { call, signed } = setup(
async () => "",
() => [],
);
- const reply = await tools.get("tasks_create")?.({
+ const reply = await call("tasks_create", {
title: "Fix the header",
+ place: home,
images: ["https://example.org/a.png"],
});
expect(reply).toContain("Created task");
- expect(JSON.parse(signed[0]?.content ?? "")).toMatchObject({
- links: [solo],
+ const [task, link] = artifacts(signed);
+ expect(task?.tags).toContainEqual(["h", home]);
+ expect(JSON.parse(task?.content ?? "")).toMatchObject({
images: [{ url: "https://example.org/a.png" }],
+ assignees: [],
});
+ // The link lives with the chat, so only its readers learn of it.
+ expect(typeOf(link)).toBe("buzz.task-link");
+ expect(link?.tags).toContainEqual(["h", chat]);
+ expect(signed.every((event) => event.kind === 45010)).toBe(true);
});
-it("reapplies an update over someone else's newer save", async () => {
- let current = head("d".repeat(64), {
- description: "Theirs.",
- status: "open",
+it("returns a clear match instead of creating a duplicate", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64), { status: "todo" })],
+ );
+ const reply = await call("tasks_create", {
+ title: "Fix the header",
+ place: home,
+ });
+ expect(reply).toContain(`Not created: open task ${id}`);
+ expect(signed).toHaveLength(0);
+});
+
+it("leaves a possible match for the person, then creates when told", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64), { status: "todo" })],
+ );
+ const args = { title: "Fix the header spacing on mobile", place: home };
+ expect(await call("tasks_create", args)).toContain("Not created yet");
+ expect(signed).toHaveLength(0);
+ await call("tasks_create", { ...args, new_anyway: true, link: false });
+ expect(artifacts(signed)).toHaveLength(1);
+});
+
+it("finds what's mine and what nobody has taken", async () => {
+ const other = "44444444-4444-4444-8444-444444444444";
+ const { call } = setup(
+ async () => "",
+ () => [
+ head("d".repeat(64), { assignees: [viewer] }),
+ head("c".repeat(64), {}, { d: other, title: "Nobody's" }),
+ ],
+ );
+ const mine = await call("tasks_find", { assignee: "me" });
+ expect(mine).toContain(id);
+ expect(mine).not.toContain(other);
+ const nobody = await call("tasks_find", { assignee: "nobody" });
+ expect(nobody).toContain(other);
+ expect(nobody).not.toContain(id);
+});
+
+it("needs evidence to close a task, and assigns whoever starts it", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64), { status: "todo" })],
+ );
+ await expect(call("tasks_update", { id, status: "done" })).rejects.toThrow(
+ "needs evidence",
+ );
+ expect(signed).toHaveLength(0);
+ await call("tasks_update", { id, status: "in_progress" });
+ expect(JSON.parse(signed[0]?.content ?? "")).toMatchObject({
+ status: "in_progress",
+ assignees: [viewer],
+ });
+});
+
+it("assigns people only, never agents", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64), {})],
+ );
+ await expect(
+ call("tasks_update", { id, assignees: [person, agent] }),
+ ).rejects.toThrow("never agents");
+ await call("tasks_update", { id, assignees: [person] });
+ expect(JSON.parse(signed[0]?.content ?? "")).toMatchObject({
+ assignees: [person],
});
+});
+
+it("moves a task when given a new place", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64), {})],
+ );
+ await call("tasks_update", { id, place: chat });
+ expect(signed[0]?.tags).toContainEqual(["op", "move"]);
+ expect(signed[0]?.tags).toContainEqual(["h", chat]);
+});
+
+it("reapplies an update over someone else's newer save", async () => {
+ let current = head("d".repeat(64), { description: "Theirs." });
let calls = 0;
- const { tools, signed } = setup(
+ const { call, signed } = setup(
async () => {
if (calls++ === 0) {
- current = head("c".repeat(64), {
- description: "Newer.",
- status: "open",
- });
+ current = head("c".repeat(64), { description: "Newer." });
throw new PublishRejected("rejected", "conflict: stale prev");
}
return "";
},
() => [current],
);
- await tools.get("tasks_update")?.({ id: "task-1", status: "done" });
+ await call("tasks_update", { id, status: "in_progress" });
expect(signed[1]?.tags).toContainEqual(["prev", "c".repeat(64)]);
expect(JSON.parse(signed[1]?.content ?? "")).toMatchObject({
description: "Newer.",
- status: "done",
+ status: "in_progress",
});
});
-it("names the agent and the task when it asks to share another chat", async () => {
- const other = "22222222-2222-4222-8222-222222222222";
- const { tools, requestShare } = setup(
- async () => "",
- () => [head("d".repeat(64), { status: "open" })],
- );
- await tools.get("tasks_link")?.({ id: "task-1", channel: solo });
- expect(requestShare).toHaveBeenCalledWith(
- expect.anything(),
- solo,
- expect.objectContaining({
- reason: "Your agent Fizz wants to link it to the task “Fix the header”.",
- }),
- );
- // A conversation that isn't the owner's Solo chat links without asking.
- requestShare.mockClear();
- await tools.get("tasks_link")?.({ id: "task-1", channel: other });
- expect(requestShare).not.toHaveBeenCalled();
-});
-
-it("reads without making the tasks channel", async () => {
- channel.id = undefined;
- try {
- const { tools, signed } = setup(
- async () => "",
- () => [],
- );
- expect(await tools.get("tasks_read")?.({})).toBe(
- "No tasks yet in this community.",
- );
- expect(channel.id).toBeUndefined();
- await tools.get("tasks_create")?.({ title: "First", link: false });
- expect(channel.id).toBe("tasks");
- expect(signed).toHaveLength(1);
- } finally {
- channel.id = "tasks";
- }
-});
-
it("tells the agent which id to check after an unclear create", async () => {
- const { tools, signed } = setup(
+ const { call, signed } = setup(
async () => {
throw new Error("network");
},
() => [],
);
- const failed = tools.get("tasks_create")?.({ title: "Fix", link: false });
+ const failed = call("tasks_create", { title: "Fix", link: false });
await expect(failed).rejects.toThrow(/saved as task [0-9a-f-]{36}/);
- const id = signed[0]?.tags.find((tag) => tag[0] === "d")?.[1];
- await expect(failed).rejects.toThrow(id);
+ const made = signed[0]?.tags.find((tag) => tag[0] === "d")?.[1];
+ await expect(failed).rejects.toThrow(made);
});
diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts
index 4882fda88f..75e94915ac 100644
--- a/src/bundled/tasks/tools.ts
+++ b/src/bundled/tasks/tools.ts
@@ -1,40 +1,42 @@
-// Agent tools. Each runs in the owner's app and writes as the owner, the way
-// the owner's own edits do. Linking a private Solo chat still waits for the
-// owner to confirm the app's "Share this chat?" dialog; an agent can't skip it.
-import {
- ARTIFACT_KIND,
- readHead,
-} from "../../features/agents/agent-config-artifacts";
+// Agent tools: find, create, update and comment. Each runs in the owner's
+// app and writes as the owner, the way the owner's own edits do, so the
+// relay applies the owner's access. Two rules keep agents' tidying
+// trustworthy: create looks for an open task about the same thing first, and
+// Done or Cancelled needs evidence, left as a comment.
import type { Agents as AgentsService } from "../../features/agents/service";
import type { RelaySession } from "../../features/relay/session";
-import type { ChatSharing } from "../../features/solo/share-requests";
-import { readyToLink } from "./linking";
+import { postComment } from "./conversation";
+import { setLink } from "./links";
import {
+ byRecent,
checkedFields,
imageOf,
isChannelId,
isOpenStatus,
+ isPubkey,
+ MAX_ASSIGNEES,
statuses,
statusLabels,
- TASK_TYPE,
type Task,
type TaskFields,
type TaskStatus,
- taskOf,
} from "./model";
-import { saveTask } from "./store";
-import { findTasksChannel, openTasksChannel } from "./tasks-channel";
+import { type Place, projectOf, readPlaces } from "./places";
+import { readTask, readTasks, saveTask } from "./store";
+import { holdsWords, sameness } from "./similar";
-type Agents = Pick;
+type Agents = Pick;
type Client = { key: string; signal?: AbortSignal | undefined };
type Args = Record;
/** How many times an agent's change is reapplied over someone else's edit. */
const ATTEMPTS = 3;
const LIST_LIMIT = 50;
-/** How long one step of relay work may take. Waiting on the owner's
- * confirmation has no deadline but the agent's own. */
+/** How long one tool call's relay work may take. */
const STEP_TIMEOUT = 60_000;
+/** At or above: the same task. Between this and CLEAR: a person decides. */
+const CLEAR_MATCH = 0.8;
+const POSSIBLE_MATCH = 0.5;
const deadline = (client: Client) =>
client.signal
@@ -51,6 +53,13 @@ const textArg = (args: Args, name: string) => {
return value;
};
+const channelArg = (args: Args, name: string) => {
+ const value = textArg(args, name);
+ if (value !== undefined && !isChannelId(value))
+ throw new Error(`${name} must be a channel id`);
+ return value;
+};
+
function imagesArg(args: Args) {
if (args.images === undefined) return undefined;
if (!Array.isArray(args.images))
@@ -62,35 +71,64 @@ function imagesArg(args: Args) {
});
}
-function describe(task: Task, session: RelaySession) {
- const channels = session.channels.list().channels;
- const links = task.links.map((id) => {
- const channel = channels.find((item) => item.id === id);
- return channel
- ? `- ${channel.name} (${channel.channelType ?? "channel"}, ${id})`
- : `- A conversation you can't read (${id})`;
- });
+/** Assignees by pubkey, people only: an agent never answers for a task. */
+function assigneesArg(args: Args, session: RelaySession) {
+ if (args.assignees === undefined) return undefined;
+ const list = args.assignees;
+ if (!Array.isArray(list) || !list.every(isPubkey))
+ throw new Error("assignees must be a list of people's hex pubkeys");
+ if (list.length > MAX_ASSIGNEES)
+ throw new Error(`A task has up to ${MAX_ASSIGNEES} assignees`);
+ const profiles = session.profiles.snapshot();
+ if (list.some((pubkey) => profiles.get(pubkey)?.isAgent))
+ throw new Error("Only people can be assigned, never agents");
+ return list;
+}
+
+const nameOf = (session: RelaySession, pubkey: string) =>
+ session.profiles.snapshot().get(pubkey)?.name ?? pubkey;
+
+/** Where it lives and who can see it, in words an agent can pass on. */
+function whereabouts(task: Task, places: ReadonlyMap) {
+ const home = places.get(task.home);
+ const project = projectOf(task, places);
+ const place = home ? `${home.name} (${home.kind}, ${home.id})` : task.home;
+ const inProject =
+ project.id && project.id !== task.home
+ ? ` in the ${project.name ?? "private"} project`
+ : "";
+ return `Lives in ${place}${inProject}. Anyone who can open ${home?.name ?? "that place"} can see it.`;
+}
+
+function describe(
+ task: Task,
+ session: RelaySession,
+ places: ReadonlyMap,
+) {
return [
`# ${task.title}`,
`id: ${task.id}`,
`status: ${statusLabels[task.status]}`,
- `author: ${task.author}`,
- `updated: ${new Date(task.updatedAt * 1000).toISOString()} by ${task.editor}`,
+ `assignees: ${task.assignees.map((pubkey) => nameOf(session, pubkey)).join(", ") || "nobody"}`,
+ `created by: ${nameOf(session, task.author)}`,
+ `updated: ${new Date(task.updatedAt * 1000).toISOString()} by ${nameOf(session, task.editor)}`,
+ whereabouts(task, places),
"",
task.description || "(No description.)",
...(task.images.length
? ["", "## Images", ...task.images.map((image) => `- ${image.url}`)]
: []),
- "",
- "## Linked conversations",
- ...(links.length ? links : ["(None.)"]),
].join("\n");
}
-export function addTaskTools(
- agents: Agents,
- sharing: () => ChatSharing | undefined,
-) {
+const summary = (task: Task, session: RelaySession) =>
+ `- ${task.id}: ${task.title} (${statusLabels[task.status]}; ${
+ task.assignees.length
+ ? task.assignees.map((pubkey) => nameOf(session, pubkey)).join(", ")
+ : "nobody has it"
+ })`;
+
+export function addTaskTools(agents: Agents) {
/** The owner's session for this agent's community. */
function sessionOf(client: Client) {
const relay = agents.relay(client.key)?.snapshot();
@@ -99,77 +137,135 @@ export function addTaskTools(
return relay.session;
}
- /** The community's tasks channel; reading never makes it. */
- async function lookup(client: Client) {
- const session = sessionOf(client);
- const signal = deadline(client);
- const channel = await findTasksChannel(session, signal);
- return { session, channel, signal };
- }
-
- /** The agent's name, so the owner's confirmation says who asks. */
- function agentName(client: Client) {
- const { agents: here, running } = agents.snapshot();
- return [...here, ...running].find((agent) => agent.key === client.key)
- ?.name;
- }
-
async function current(
session: RelaySession,
- channel: string,
id: string,
signal: AbortSignal,
) {
- const read = session.snapshotRead;
- if (!read) throw new Error("This community can't read tasks");
- const head = await readHead(read, channel, id, signal);
- const task = head && taskOf(head);
- if (!task) throw new Error(`No task ${id} here`);
+ const task = await readTask(session, id, signal);
+ if (!task) throw new Error(`No task ${id} that you can read`);
return task;
}
/** Applies `edit` to the newest revision, again over anyone else's save. */
async function change(
session: RelaySession,
- channel: string,
id: string,
edit: (task: Task) => TaskFields,
signal: AbortSignal,
+ home?: string,
) {
- let task = await current(session, channel, id, signal);
+ let task = await current(session, id, signal);
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
signal.throwIfAborted();
- const result = await saveTask(session, channel, edit(task), task, signal);
+ const target =
+ home && home !== task.home
+ ? { op: "move" as const, base: task, home }
+ : { op: "update" as const, base: task };
+ const result = await saveTask(session, edit(task), target, signal);
if (result.status === "saved") return result.task;
- task = result.current ?? (await current(session, channel, id, signal));
+ task = result.current;
}
throw new Error("Others keep changing this task. Try again.");
}
- async function cleared(
- client: Client,
- session: RelaySession,
- chat: string,
- task: string,
- ) {
- const outcome = await readyToLink(session, sharing(), chat, {
- task,
- agent: agentName(client),
- signal: client.signal,
- });
- client.signal?.throwIfAborted();
- if (outcome === "cancelled")
- throw new Error(
- "Your owner chose not to share this chat, so it wasn't linked.",
- );
- if (outcome === "unavailable")
- throw new Error("Only this chat's owner can link it to a task.");
- }
+ agents.addTool({
+ name: "tasks_find",
+ description:
+ 'Finds tasks you can see, newest activity first. Use it to answer "what should I work on?": first assignee "me" (the person you work for), then open tasks nobody has taken. Searching a project covers everything filed in it. With id, reads one task in full.',
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: { type: "string", description: "Read this one task" },
+ words: {
+ type: "string",
+ description: "Words in the title or description",
+ },
+ place: {
+ type: "string",
+ description:
+ "A project, channel or chat id: its tasks, and for a project everything filed in it",
+ },
+ status: {
+ type: "string",
+ enum: ["open", "closed", "all"],
+ description:
+ "Open (To do, In progress; the default), closed (Done, Cancelled), or all",
+ },
+ assignee: {
+ type: "string",
+ description: '"me", "nobody", or a person\'s hex pubkey',
+ },
+ },
+ additionalProperties: false,
+ },
+ async call(client, _context, args) {
+ const session = sessionOf(client);
+ const signal = deadline(client);
+ const id = textArg(args, "id");
+ if (id) {
+ const task = await current(session, id, signal);
+ return describe(
+ task,
+ session,
+ await readPlaces(session, [task.home], signal),
+ );
+ }
+ const words = (textArg(args, "words") ?? "").trim();
+ const place = channelArg(args, "place");
+ const which =
+ args.status === "closed" || args.status === "all"
+ ? args.status
+ : "open";
+ const assignee = textArg(args, "assignee");
+ if (
+ assignee &&
+ assignee !== "me" &&
+ assignee !== "nobody" &&
+ !isPubkey(assignee)
+ )
+ throw new Error('assignee must be "me", "nobody" or a hex pubkey');
+ const who = assignee === "me" ? session.viewer : assignee;
+ const all = await readTasks(session, signal);
+ const places = place
+ ? await readPlaces(
+ session,
+ all.map((task) => task.home),
+ signal,
+ )
+ : undefined;
+ const tasks = all
+ .filter(
+ (task) =>
+ (which === "all" ||
+ isOpenStatus(task.status) === (which === "open")) &&
+ (!who ||
+ (who === "nobody"
+ ? task.assignees.length === 0
+ : task.assignees.includes(who))) &&
+ (!place ||
+ task.home === place ||
+ (places && projectOf(task, places).id === place)) &&
+ (!words || holdsWords(words, `${task.title} ${task.description}`)),
+ )
+ .sort(byRecent);
+ if (!tasks.length) return "No tasks match.";
+ return tasks
+ .slice(0, LIST_LIMIT)
+ .map((task) => summary(task, session))
+ .concat(
+ tasks.length > LIST_LIMIT
+ ? [`…and ${tasks.length - LIST_LIMIT} more`]
+ : [],
+ )
+ .join("\n");
+ },
+ });
agents.addTool({
name: "tasks_create",
description:
- "Creates a task in this community's Tasks: a title, a Markdown description of what was noticed and why, and image links. Only the title is required. Everyone in the community can read a task, so never put in it what a private conversation shouldn't share. Links this conversation unless link is false. Linking a private Solo chat makes it View only for the community, so your owner sees a confirmation first; nothing is created if they decline.",
+ "Creates a task from what you're working on, without asking first: a short title, a Markdown description that makes sense to someone who can't read this conversation, and image links. It lives in place (default: this conversation), and everyone who can open that place can see it. It first looks for an open task about the same thing there: a clear match is returned instead, so comment on it with tasks_comment; a possible match is returned for the person to decide, and only then create with new_anyway. If you can't post in place, nothing is created: say so, never put it somewhere else. Reply with the task's id, where it lives and who can see it.",
inputSchema: {
type: "object",
properties: {
@@ -183,209 +279,197 @@ export function addTaskTools(
items: { type: "string" },
description: "https media links of images, as messages attach them",
},
+ place: {
+ type: "string",
+ description:
+ "Project, channel or chat id to put it in (default: this conversation)",
+ },
link: {
type: "boolean",
- description: "Link this conversation (default true)",
+ description:
+ "Link this conversation to it (default true). Only people who can read this conversation see the link.",
+ },
+ new_anyway: {
+ type: "boolean",
+ description:
+ "Create even though a possible match exists, once the person said so",
},
},
required: ["title"],
additionalProperties: false,
},
async call(client, context, args) {
- const chat = args.link === false ? undefined : context.channel;
- // Checked before the owner is asked, so a bad call never shares a chat.
+ const session = sessionOf(client);
+ const signal = deadline(client);
+ const home = channelArg(args, "place") ?? context.channel;
+ if (!isChannelId(home))
+ throw new Error("Say which project, channel or chat it goes in");
const fields = checkedFields({
title: textArg(args, "title") ?? "",
description: textArg(args, "description") ?? "",
- status: "open",
+ status: "todo",
images: imagesArg(args) ?? [],
- links: chat ? [chat] : [],
+ assignees: [],
});
- const session = sessionOf(client);
- if (chat) await cleared(client, session, chat, fields.title);
- const signal = deadline(client);
- const channel = await openTasksChannel(session, signal);
+ const open = (await readTasks(session, signal)).filter(
+ (task) => task.home === home && isOpenStatus(task.status),
+ );
+ const scored = open
+ .map((task) => ({ task, score: sameness(fields.title, task.title) }))
+ .sort((a, b) => b.score - a.score);
+ const best = scored[0];
+ if (best && best.score >= CLEAR_MATCH)
+ return `Not created: open task ${best.task.id} is about the same thing. Comment on it with tasks_comment instead.\n\n${summary(best.task, session)}`;
+ const possible = scored.filter((item) => item.score >= POSSIBLE_MATCH);
+ if (possible.length && args.new_anyway !== true)
+ return `Not created yet: these open tasks may be about the same thing. Ask the person whether one of them is it; if not, call tasks_create again with new_anyway.\n\n${possible
+ .slice(0, 5)
+ .map((item) => summary(item.task, session))
+ .join("\n")}`;
// Named before saving, so a retry after an unclear outcome can check.
const id = crypto.randomUUID();
const result = await saveTask(
session,
- channel,
fields,
- undefined,
+ { op: "create", home, id },
signal,
- id,
).catch((reason: unknown) => {
throw new Error(
- `${reason instanceof Error ? reason.message : "Couldn't create the task."} It may still have been saved as task ${id}: read it with tasks_read before creating it again.`,
+ `${reason instanceof Error ? reason.message : "Couldn't create the task."} It may still have been saved as task ${id}: read it with tasks_find before creating it again.`,
);
});
if (result.status !== "saved")
throw new Error("Couldn't create the task");
- return `Created task ${result.task.id}.\n\n${describe(result.task, session)}`;
- },
- });
-
- agents.addTool({
- name: "tasks_read",
- description:
- "Reads one task with its description, images and linked conversations, or without id lists tasks (open by default).",
- inputSchema: {
- type: "object",
- properties: {
- id: { type: "string", description: "The task's id" },
- status: {
- type: "string",
- enum: ["open", "done", "all"],
- description: "Without id: which tasks to list",
- },
- linked_here: {
- type: "boolean",
- description: "Without id: only tasks linked to this conversation",
- },
- },
- additionalProperties: false,
- },
- async call(client, context, args) {
- const { session, channel, signal } = await lookup(client);
- const id = textArg(args, "id");
- if (!channel)
- return id ? `No task ${id} here` : "No tasks yet in this community.";
- if (id)
- return describe(await current(session, channel, id, signal), session);
- const read = session.snapshotRead;
- if (!read) throw new Error("This community can't read tasks");
- const which =
- args.status === "done" || args.status === "all" ? args.status : "open";
- const here = args.linked_here === true ? context.channel : undefined;
- const tasks = (
- await read(
- [
- {
- artifact: "current",
- kinds: [ARTIFACT_KIND],
- "#h": [channel],
- "#type": [TASK_TYPE],
- limit: 500,
- },
- ],
- { signal },
- )
- )
- .flatMap((event) => taskOf(event) ?? [])
- .filter(
- (task) =>
- (which === "all" ||
- isOpenStatus(task.status) === (which === "open")) &&
- (!here || task.links.includes(here)),
- )
- .sort((a, b) => b.updatedAt - a.updatedAt);
- if (!tasks.length) return "No tasks match.";
- return tasks
- .slice(0, LIST_LIMIT)
- .map(
- (task) =>
- `- ${task.id}: ${task.title} (${statusLabels[task.status]}, ${task.links.length} linked)`,
- )
- .concat(
- tasks.length > LIST_LIMIT
- ? [`…and ${tasks.length - LIST_LIMIT} more`]
- : [],
- )
- .join("\n");
+ const chat = context.channel;
+ const linked =
+ args.link !== false && isChannelId(chat) && chat !== home
+ ? await setLink(session, id, chat, true, signal).then(
+ () =>
+ "\nLinked this conversation; only people who can read it see that.",
+ () => "\nCouldn't link this conversation.",
+ )
+ : "";
+ const places = await readPlaces(session, [home], signal);
+ return `Created task ${id}.${linked}\n\n${describe(result.task, session, places)}`;
},
});
agents.addTool({
name: "tasks_update",
description:
- "Changes a task's title, description, status or images. Omitted fields stay as they are; images replaces the whole list.",
+ "Changes a task: title, description, images, assignees, status, or place (moving it changes who can see it and its comments). Omitted fields stay. Set In progress when work starts; that assigns the person you work for. Set Done or Cancelled only with evidence, such as a merged pull request or someone saying it's finished, and give it as evidence: it's left as a comment. Otherwise comment on progress instead.",
inputSchema: {
type: "object",
properties: {
id: { type: "string" },
title: { type: "string" },
description: { type: "string", description: "Markdown" },
- status: { type: "string", enum: [...statuses] },
images: {
type: "array",
items: { type: "string" },
- description: "https media links",
+ description: "https media links; replaces the whole list",
+ },
+ assignees: {
+ type: "array",
+ items: { type: "string" },
+ description: "People's hex pubkeys, up to four; replaces the list",
+ },
+ status: { type: "string", enum: [...statuses] },
+ evidence: {
+ type: "string",
+ description: "Required for done or cancelled: one line saying why",
+ },
+ place: {
+ type: "string",
+ description: "Move it to this project, channel or chat id",
},
},
required: ["id"],
additionalProperties: false,
},
async call(client, _context, args) {
+ const session = sessionOf(client);
const id = textArg(args, "id") ?? "";
const title = textArg(args, "title");
const description = textArg(args, "description");
+ const images = imagesArg(args);
+ const assignees = assigneesArg(args, session);
+ const place = channelArg(args, "place");
const status =
args.status === undefined ? undefined : statusOf(args.status);
if (args.status !== undefined && !status)
throw new Error(`status must be one of ${statuses.join(", ")}`);
- const images = imagesArg(args);
- const { session, channel, signal } = await lookup(client);
- if (!channel) throw new Error(`No task ${id} here`);
+ const evidence = textArg(args, "evidence")?.trim();
+ const closing = status === "done" || status === "cancelled";
+ if (closing && !evidence)
+ throw new Error(
+ "Done or Cancelled needs evidence: say in one line why, such as the merged pull request or who said it's finished",
+ );
+ const signal = deadline(client);
+ const viewer = session.viewer;
const task = await change(
session,
- channel,
id,
- (base) => ({
- ...base,
- ...(title !== undefined && { title }),
- ...(description !== undefined && { description }),
- ...(status && { status }),
- ...(images && { images }),
- }),
+ (base) => {
+ const people = assignees ?? base.assignees;
+ // Starting work assigns the person the agent works for.
+ const starting =
+ status === "in_progress" &&
+ base.status !== "in_progress" &&
+ !!viewer &&
+ !people.includes(viewer) &&
+ people.length < MAX_ASSIGNEES;
+ return {
+ ...base,
+ ...(title !== undefined && { title }),
+ ...(description !== undefined && { description }),
+ ...(images && { images }),
+ ...(status && { status }),
+ assignees: starting && viewer ? [...people, viewer] : people,
+ };
+ },
signal,
+ place,
);
- return `Updated.\n\n${describe(task, session)}`;
+ const noted =
+ closing && evidence
+ ? await postComment(
+ session,
+ task,
+ `${statusLabels[task.status]}: ${evidence}`,
+ signal,
+ ).then(
+ () => "",
+ () =>
+ "\nThe evidence comment didn't post; add it with tasks_comment.",
+ )
+ : "";
+ const places = await readPlaces(session, [task.home], signal);
+ return `Updated.${noted}\n\n${describe(task, session, places)}`;
},
});
agents.addTool({
- name: "tasks_link",
+ name: "tasks_comment",
description:
- "Links a conversation to a task, or unlinks it. Defaults to this conversation. Linking never adds anyone to it. Linking a private Solo chat makes it View only for the community, so your owner sees a confirmation first. Unlinking never changes access back.",
+ "Comments on a task, such as progress, a summary of a thread about it, or the answer to a question in it. Everyone who can see the task reads it.",
inputSchema: {
type: "object",
properties: {
id: { type: "string", description: "The task's id" },
- channel: {
- type: "string",
- description: "The conversation's channel id (default: this one)",
- },
- unlink: { type: "boolean", description: "Unlink instead" },
+ text: { type: "string", description: "Markdown" },
},
- required: ["id"],
+ required: ["id", "text"],
additionalProperties: false,
},
- async call(client, context, args) {
- const id = textArg(args, "id") ?? "";
- const chat = textArg(args, "channel") ?? context.channel;
- if (!isChannelId(chat)) throw new Error("channel must be a channel id");
- const unlink = args.unlink === true;
- const found = await lookup(client);
- const { session, channel } = found;
- if (!channel) throw new Error(`No task ${id} here`);
- if (!unlink) {
- // The task must exist before the owner is asked to share for it.
- const task = await current(session, channel, id, found.signal);
- await cleared(client, session, chat, task.title);
- }
- const task = await change(
- session,
- channel,
- id,
- (base) => ({
- ...base,
- links: unlink
- ? base.links.filter((link) => link !== chat)
- : [...base.links, chat],
- }),
- deadline(client),
- );
- return `${unlink ? "Unlinked. Its access is unchanged." : "Linked."}\n\n${describe(task, session)}`;
+ async call(client, _context, args) {
+ const session = sessionOf(client);
+ const signal = deadline(client);
+ const text = (textArg(args, "text") ?? "").trim();
+ if (!text) throw new Error("text must not be empty");
+ const task = await current(session, textArg(args, "id") ?? "", signal);
+ await postComment(session, task, text, signal);
+ return `Commented on ${task.id}.`;
},
});
}
diff --git a/src/features/solo/ShareRequestDialog.test.tsx b/src/features/solo/ShareRequestDialog.test.tsx
deleted file mode 100644
index 8f39e6c234..0000000000
--- a/src/features/solo/ShareRequestDialog.test.tsx
+++ /dev/null
@@ -1,248 +0,0 @@
-// @vitest-environment jsdom
-import { Context } from "@deepseek-ai/cordis";
-import { act, cleanup, render, screen } from "@testing-library/react";
-import userEvent from "@testing-library/user-event";
-import { StrictMode } from "react";
-import { afterEach, expect, it, vi } from "vitest";
-import type { RelaySession } from "../relay/session";
-import type {
- ChannelDetails,
- ChannelDetailsDraft,
-} from "../relay/channel-details-protocol";
-import { ShareRequestDialog } from "./ShareRequestDialog";
-import {
- type ChatSharing,
- createChatSharingService,
- createShareRequests,
-} from "./share-requests";
-
-afterEach(cleanup);
-
-const id = "11111111-1111-4111-8111-111111111111";
-const viewer = "a".repeat(64);
-const asker = { requester: "Tasks" };
-
-function fixture(
- visibility: "public" | "private" = "private",
- creator = viewer,
-) {
- let base: ChannelDetails = {
- channelId: id,
- version: "version",
- name: "Chat",
- description: "",
- visibility,
- joinRole: "member",
- canEdit: true,
- labels: ["buzz.solo"],
- };
- let fail = false;
- const save = vi.fn(
- async (_base: ChannelDetails, draft: ChannelDetailsDraft) => {
- if (fail) throw new Error("Relay refused the change.");
- base = { ...base, ...draft, version: "saved" };
- },
- );
- const session = {
- viewer,
- channels: {
- list: () => ({
- channels: [{ id, channelType: "solo", creator, members: [creator] }],
- }),
- },
- channelDetails: {
- load: vi.fn(async () => base),
- save,
- check: vi.fn(async () => {}),
- snapshot: () => undefined,
- },
- } as unknown as RelaySession;
- return {
- session,
- save,
- failNext(value: boolean) {
- fail = value;
- },
- };
-}
-
-it("shows the app's confirmation and makes the chat View only only when confirmed", async () => {
- const f = fixture();
- const requests = createShareRequests();
- render( );
- const outcome = requests.request(f.session, id, asker);
- expect(await screen.findByText("Share “Chat”?")).toBeTruthy();
- expect(
- screen.getByText(
- /full history, Canvas, workspace folders, and agent instructions/,
- ),
- ).toBeTruthy();
- expect(f.save).not.toHaveBeenCalled();
- await userEvent.click(screen.getByRole("button", { name: "Share" }));
- expect(await outcome).toBe("shared");
- expect(f.save).toHaveBeenCalledExactlyOnceWith(
- expect.objectContaining({ visibility: "private" }),
- expect.objectContaining({ visibility: "public", joinRole: "guest" }),
- expect.any(AbortSignal),
- expect.any(Function),
- );
- expect(screen.queryByText("Share “Chat”?")).toBeNull();
-});
-
-it("changes nothing when the viewer cancels", async () => {
- const f = fixture();
- const requests = createShareRequests();
- render( );
- const outcome = requests.request(f.session, id, asker);
- await userEvent.click(await screen.findByRole("button", { name: "Cancel" }));
- expect(await outcome).toBe("cancelled");
- expect(f.save).not.toHaveBeenCalled();
-});
-
-it("keeps the dialog open with the error so the viewer can retry", async () => {
- const f = fixture();
- f.failNext(true);
- const requests = createShareRequests();
- render( );
- const outcome = requests.request(f.session, id, asker);
- await userEvent.click(await screen.findByRole("button", { name: "Share" }));
- expect((await screen.findByRole("alert")).textContent).toBe(
- "Relay refused the change.",
- );
- f.failNext(false);
- await userEvent.click(screen.getByRole("button", { name: "Retry" }));
- expect(await outcome).toBe("shared");
-});
-
-it("resolves without a dialog when the chat is already open", async () => {
- const f = fixture("public");
- const requests = createShareRequests();
- render( );
- expect(await requests.request(f.session, id, asker)).toBe("shared");
- expect(requests.snapshot()).toEqual([]);
- expect(screen.queryByText("Share “Chat”?")).toBeNull();
-});
-
-it("refuses without a dialog for a chat the viewer does not own", async () => {
- const f = fixture("private", "b".repeat(64));
- const requests = createShareRequests();
- expect(await requests.request(f.session, id, asker)).toBe("unavailable");
- expect(requests.snapshot()).toEqual([]);
- expect(f.save).not.toHaveBeenCalled();
-});
-
-it("asks once for repeated requests about the same chat", async () => {
- const f = fixture();
- const requests = createShareRequests();
- render( );
- const first = requests.request(f.session, id, asker);
- await screen.findByText("Share “Chat”?");
- const second = requests.request(f.session, id, asker);
- expect(requests.snapshot()).toHaveLength(1);
- await userEvent.click(screen.getByRole("button", { name: "Share" }));
- expect(await first).toBe("shared");
- expect(await second).toBe("shared");
- expect(f.save).toHaveBeenCalledOnce();
-});
-
-it("withdraws a plugin's request when the plugin stops", async () => {
- const f = fixture();
- const root = new Context();
- const requests = createShareRequests();
- createChatSharingService(root, requests, (plugin) =>
- plugin === "example.tasks" ? "Tasks" : plugin,
- );
- let sharing: ChatSharing | undefined;
- const fiber = root
- .extend({ pluginOwner: { id: "example.tasks", revision: "one" } })
- .plugin((ctx) => {
- sharing = ctx.reflect.get("chatSharing");
- });
- await fiber.await();
- render( );
- if (!sharing) throw new Error("chatSharing is unavailable");
- const outcome = sharing.requestShare(f.session, id);
- await screen.findByText("Share “Chat”?");
- await act(async () => {
- await fiber.dispose();
- });
- expect(await outcome).toBe("cancelled");
- expect(screen.queryByText("Share “Chat”?")).toBeNull();
- expect(f.save).not.toHaveBeenCalled();
-});
-
-it("withdraws a request when its caller's signal aborts", async () => {
- const f = fixture();
- const requests = createShareRequests();
- render( );
- const controller = new AbortController();
- const outcome = requests.request(
- f.session,
- id,
- asker,
- undefined,
- controller.signal,
- );
- await screen.findByText("Share “Chat”?");
- act(() => controller.abort());
- expect(await outcome).toBe("cancelled");
- expect(screen.queryByText("Share “Chat”?")).toBeNull();
- expect(f.save).not.toHaveBeenCalled();
-});
-
-it("still shares after a StrictMode remount", async () => {
- const f = fixture();
- const requests = createShareRequests();
- render(
-
-
- ,
- );
- const outcome = requests.request(f.session, id, asker);
- await userEvent.click(await screen.findByRole("button", { name: "Share" }));
- expect(await outcome).toBe("shared");
- expect(f.save).toHaveBeenCalledOnce();
-});
-
-it("names who asks, their reason, and a chat without a name", async () => {
- const f = fixture();
- const requests = createShareRequests();
- render( );
- void requests.request(f.session, id, {
- requester: "Tasks",
- reason: "Your agent Fizz wants to link it to the task “Fix the header”.",
- });
- await screen.findByText("Share “Chat”?");
- expect(
- screen.getByText(/Tasks asked to change “Chat” from Private to View only/),
- ).toBeTruthy();
- expect(
- screen.getByText(
- "Reason given: Your agent Fizz wants to link it to the task “Fix the header”.",
- ),
- ).toBeTruthy();
-});
-
-it("keeps sharing when its caller aborts after the viewer chose Share", async () => {
- const f = fixture();
- let finish!: () => void;
- f.save.mockImplementationOnce(
- () => new Promise((resolve) => (finish = resolve)),
- );
- const requests = createShareRequests();
- render( );
- const controller = new AbortController();
- const outcome = requests.request(
- f.session,
- id,
- asker,
- undefined,
- controller.signal,
- );
- await userEvent.click(await screen.findByRole("button", { name: "Share" }));
- await vi.waitFor(() => expect(f.save).toHaveBeenCalledOnce());
- act(() => controller.abort());
- expect(screen.getByText("Share “Chat”?")).toBeTruthy();
- await act(async () => finish());
- expect(await outcome).toBe("shared");
-});
diff --git a/src/features/solo/ShareRequestDialog.tsx b/src/features/solo/ShareRequestDialog.tsx
deleted file mode 100644
index 2a25db14dd..0000000000
--- a/src/features/solo/ShareRequestDialog.tsx
+++ /dev/null
@@ -1,106 +0,0 @@
-import { useEffect, useRef, useState, useSyncExternalStore } from "react";
-import type { ChannelDetailsDraft } from "../relay/channel-details-protocol";
-import { AlertDialog } from "../../shared/design-system/ui/AlertDialog";
-import { Button } from "../../shared/design-system/ui/Button";
-import { soloShareDisclosure } from "./labels";
-import { shareSoloChatAccess } from "./share";
-import type { ShareRequest, ShareRequests } from "./share-requests";
-
-/** The viewer confirms a `chatSharing` request with the app's own wording. */
-export function ShareRequestDialog({ requests }: { requests: ShareRequests }) {
- const pending = useSyncExternalStore(requests.subscribe, requests.snapshot);
- const request = pending[0];
- if (!request) return null;
- return (
-
- );
-}
-
-function ShareRequestConfirmation({
- request,
- requests,
-}: {
- request: ShareRequest;
- requests: ShareRequests;
-}) {
- const cancel = useRef(null);
- const [busy, setBusy] = useState(false);
- const [error, setError] = useState("");
- // An uncertain save is checked on retry, never republished.
- const attempts = useRef(new Map());
- // Made in the effect, so a remount (StrictMode) never keeps an aborted one.
- const controller = useRef(undefined);
- useEffect(() => {
- const active = new AbortController();
- controller.current = active;
- return () => active.abort();
- }, []);
- const decline = () => requests.settle(request.id, "cancelled");
- const confirm = async () => {
- const signal = controller.current?.signal;
- if (busy || !signal || signal.aborted) return;
- setBusy(true);
- setError("");
- // The chat may become View only from here, so its caller can't withdraw.
- requests.confirm(request.id);
- try {
- await shareSoloChatAccess(request.session, request.details.channelId, {
- signal,
- confirmed: request.details,
- attempts: attempts.current,
- });
- requests.settle(request.id, "shared");
- } catch (reason) {
- if (signal.aborted) return;
- setError(
- reason instanceof Error ? reason.message : "Couldn’t share this chat.",
- );
- setBusy(false);
- }
- };
- // A chat without a name is told apart by its id.
- const chat = request.details.name
- ? `“${request.details.name}”`
- : `chat ${request.details.channelId.slice(0, 8)}`;
- return (
-
- {request.requester} asked to change {chat} from Private to View only.
- {request.reason ? (
- Reason given: {request.reason}
- ) : null}
- {soloShareDisclosure()}
- >
- }
- pending={busy}
- onClose={decline}
- initialFocus={cancel}
- actions={
- <>
-
- Cancel
-
- void confirm()}
- >
- {error ? "Retry" : "Share"}
-
- >
- }
- >
- {error ? (
-
- {error}
-
- ) : null}
-
- );
-}
diff --git a/src/features/solo/share-requests.ts b/src/features/solo/share-requests.ts
deleted file mode 100644
index 6cc0d07339..0000000000
--- a/src/features/solo/share-requests.ts
+++ /dev/null
@@ -1,211 +0,0 @@
-import { Service, type Context } from "@deepseek-ai/cordis";
-import type { ChannelDetails } from "../relay/channel-details-protocol";
-import type { RelaySession } from "../relay/session";
-import { shareSoloChatAccess } from "./share";
-
-export type ChatShareOutcome = "shared" | "cancelled" | "unavailable";
-
-/** The handle plugins read with `ctx.reflect.get("chatSharing")`. */
-export type ChatSharing = Readonly<{
- /**
- * Ask the viewer to make one of their own Solo chats View only. The app
- * shows its "Share this chat?" confirmation; nothing changes unless the
- * viewer confirms. Resolves `"shared"` once the chat is View only or public
- * (at once, without a dialog, when it already is), `"cancelled"` when the
- * viewer declines or the caller stops, and `"unavailable"` when the viewer
- * cannot share it. Never rejects. Aborting `signal` withdraws the request
- * until the viewer chooses Share; from then on only the viewer ends it.
- * `reason` is one sentence the dialog shows as the caller's own words.
- */
- requestShare(
- session: RelaySession,
- channelId: string,
- options?: ShareRequestOptions,
- ): Promise;
-}>;
-
-export type ShareRequestOptions = Readonly<{
- signal?: AbortSignal | undefined;
- reason?: string | undefined;
-}>;
-
-declare module "@deepseek-ai/cordis" {
- interface Context {
- /** Read with `ctx.reflect.get("chatSharing")` for old-host compatibility. */
- chatSharing?: ChatSharing;
- }
-}
-
-/** A confirmation waiting for the viewer, with the access it was asked about. */
-export type ShareRequest = Readonly<{
- id: string;
- session: RelaySession;
- details: ChannelDetails;
- /** The asking plugin's name, as the app knows it. */
- requester: string;
- /** The caller's own one-sentence reason, if it gave one. */
- reason?: string | undefined;
-}>;
-
-/** Who asks and why, as the dialog shows them. */
-type Asker = Readonly<{ requester: string; reason?: string | undefined }>;
-
-const MAX_REASON = 200;
-const reasonOf = (reason: string | undefined) =>
- reason?.replace(/\s+/g, " ").trim().slice(0, MAX_REASON) || undefined;
-
-type Pending = ShareRequest & {
- readonly done: Promise;
- readonly resolve: (outcome: ChatShareOutcome) => void;
- readonly controller: AbortController;
-};
-
-// Each request holds a dialog open for the viewer, so callers cannot queue
-// without bound.
-const PENDING_MAX = 16;
-
-export type ShareRequests = ReturnType;
-
-/** The app-owned queue behind `chatSharing`: one confirmation at a time. */
-export function createShareRequests() {
- let pending: readonly Pending[] = [];
- let next = 0;
- const listeners = new Set<() => void>();
- const notify = () => {
- for (const listener of listeners) listener();
- };
- // Requests the viewer chose Share on: their caller can no longer withdraw
- // them, since the chat may already be View only.
- const confirming = new Set();
- const settle = (id: string, outcome: ChatShareOutcome) => {
- const item = pending.find((entry) => entry.id === id);
- if (!item) return;
- pending = pending.filter((entry) => entry !== item);
- confirming.delete(id);
- item.controller.abort();
- item.resolve(outcome);
- notify();
- };
-
- async function request(
- session: RelaySession,
- channelId: string,
- asker: Asker,
- lifetime?: (end: () => void) => () => void,
- signal?: AbortSignal,
- ): Promise {
- if (signal?.aborted) return "cancelled";
- const same = pending.find(
- (entry) =>
- entry.session === session && entry.details.channelId === channelId,
- );
- if (same) return same.done;
- const controller = new AbortController();
- const stop = lifetime?.(() => controller.abort());
- const withdraw = () => controller.abort();
- signal?.addEventListener("abort", withdraw, { once: true });
- try {
- // The same check both share dialogs make: only the viewer's own Solo
- // chat, with its current signed access.
- let details: ChannelDetails | undefined;
- try {
- details = await shareSoloChatAccess(session, channelId, {
- signal: controller.signal,
- attempts: new Map(),
- });
- } catch {
- return controller.signal.aborted ? "cancelled" : "unavailable";
- }
- if (!details || details.visibility === "public") return "shared";
- if (pending.length >= PENDING_MAX) return "unavailable";
- const raced = pending.find(
- (entry) =>
- entry.session === session && entry.details.channelId === channelId,
- );
- if (raced) return await raced.done;
- let resolve!: (outcome: ChatShareOutcome) => void;
- const done = new Promise((settled) => {
- resolve = settled;
- });
- const id = `share-${++next}`;
- pending = [
- ...pending,
- {
- id,
- session,
- details,
- requester: asker.requester,
- reason: reasonOf(asker.reason),
- done,
- resolve,
- controller,
- },
- ];
- controller.signal.addEventListener(
- "abort",
- () => {
- if (!confirming.has(id)) settle(id, "cancelled");
- },
- { once: true },
- );
- notify();
- return await done;
- } finally {
- stop?.();
- signal?.removeEventListener("abort", withdraw);
- }
- }
-
- return {
- request,
- /** The confirmations waiting for the viewer, oldest first. */
- snapshot: (): readonly ShareRequest[] => pending,
- subscribe(listener: () => void) {
- listeners.add(listener);
- return () => void listeners.delete(listener);
- },
- settle,
- /** The viewer chose Share: from now on only `settle` ends the request. */
- confirm(id: string) {
- if (pending.some((entry) => entry.id === id)) confirming.add(id);
- },
- };
-}
-
-/** Provide `chatSharing`, tying each request to its caller's lifetime. */
-export function createChatSharingService(
- ctx: Context,
- requests: ShareRequests,
- /** A plugin's display name from its id. */
- pluginName: (id: string) => string,
-): ChatSharing {
- class ChatSharingService extends Service implements ChatSharing {
- constructor() {
- super(ctx, "chatSharing");
- }
-
- // A method, so Cordis supplies the caller's context for its lifetime.
- requestShare(
- session: RelaySession,
- channelId: string,
- options?: ShareRequestOptions,
- ) {
- const caller = this.ctx;
- const owner = caller.pluginOwner?.id;
- return requests.request(
- session,
- channelId,
- {
- requester: owner ? pluginName(owner) : "The app",
- reason: options?.reason,
- },
- (end) => {
- const stop = caller.effect(() => end);
- return () => void stop();
- },
- options?.signal,
- );
- }
- }
- return new ChatSharingService();
-}
From e1ab50e13e91d999364e9b83613c9181658ef338 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sun, 15 Nov 2026 23:52:09 -0800
Subject: [PATCH 10/18] fix(agents): leave task conversations out of the
channel list
The relay already hides artifact conversations from reads that don't
name them; the agents' channel list now leaves them out itself too.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/buzz-mcp/tools.test.ts | 29 +++++++++++++++++++++++++++++
src/buzz-mcp/tools.ts | 2 ++
2 files changed, 31 insertions(+)
diff --git a/src/buzz-mcp/tools.test.ts b/src/buzz-mcp/tools.test.ts
index 105a722e14..f125b33c1e 100644
--- a/src/buzz-mcp/tools.test.ts
+++ b/src/buzz-mcp/tools.test.ts
@@ -1650,6 +1650,35 @@ it("lists channels it can join as well as its own", async () => {
);
});
+it("leaves a task's conversation out of every channel list", async () => {
+ const { client, state } = relay();
+ const comments = "7d9a4e3f-5c6b-8d8e-8f1a-2b3c4d5e6f71";
+ state.push(
+ event({
+ kind: 39000,
+ tags: [
+ ["d", comments],
+ ["name", "Comments"],
+ ["t", "artifact"],
+ ["private"],
+ ["hidden"],
+ ],
+ }),
+ event({
+ kind: 39002,
+ tags: [
+ ["d", comments],
+ ["t", "artifact"],
+ ["p", me, "", "member"],
+ ],
+ }),
+ );
+ for (const args of [{}, { all: true }, { q: "comments", all: true }])
+ await expect(
+ callTool(client, {}, "channel_list", args),
+ ).resolves.not.toContain(comments);
+});
+
it("lists only the channel types asked for", async () => {
const { client, state } = relay();
const forum = "7d9a4e3f-5c6b-4d8e-8f1a-2b3c4d5e6f70";
diff --git a/src/buzz-mcp/tools.ts b/src/buzz-mcp/tools.ts
index 6d3be1135c..1c02ef1af9 100644
--- a/src/buzz-mcp/tools.ts
+++ b/src/buzz-mcp/tools.ts
@@ -941,6 +941,8 @@ const HANDLERS: Readonly> = {
? { kinds: [39000], ...scope }
: { kinds: [39000], "#d": [...ids], ...scope },
(event) => {
+ // A task's conversation belongs to its task, never a list.
+ if (tag(event, "t") === "artifact") return true;
const id = tag(event, "d") ?? "";
const flags = [
tag(event, "t") === "stream" ? "" : tag(event, "t"),
From d5a043b911a3351d2b93faed8dd96c3dcda4b107 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Sun, 15 Nov 2026 23:56:52 -0800
Subject: [PATCH 11/18] feat(tasks): comment on tasks in their own conversation
Each task's comments live in a hidden NIP-AR conversation whose id comes
from the task. The task view holds it open with channels.reach: a
neutral wait, then the comments with a composer or read-only, and a
retry when the relay couldn't be asked. Someone who can post in the
task's home starts the conversation with "Add a comment".
The session opens a conversation through a narrow writer that signs only
the exact kind:9007 opening (buzz-artifact-conversations). The agents'
tasks_comment tool and closing evidence now post there and wait for the
relay to accept.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/TaskComments.test.tsx | 153 ++++++++++++++
src/bundled/tasks/TaskComments.tsx | 197 ++++++++++++++++++
src/bundled/tasks/TaskView.test.tsx | 1 -
src/bundled/tasks/TaskView.tsx | 11 +-
src/bundled/tasks/Tasks.module.css | 16 ++
src/bundled/tasks/TasksPage.tsx | 18 +-
src/bundled/tasks/TasksPanel.tsx | 4 +-
src/bundled/tasks/conversation.test.ts | 85 ++++++++
src/bundled/tasks/conversation.ts | 116 ++++++++---
src/bundled/tasks/index.tsx | 14 +-
.../relay/artifact-conversation.test.ts | 61 ++++++
src/features/relay/artifact-conversation.ts | 66 ++++++
src/features/relay/native.ts | 31 +++
src/features/relay/session.ts | 31 +++
src/features/relay/transport.ts | 3 +
15 files changed, 771 insertions(+), 36 deletions(-)
create mode 100644 src/bundled/tasks/TaskComments.test.tsx
create mode 100644 src/bundled/tasks/TaskComments.tsx
create mode 100644 src/bundled/tasks/conversation.test.ts
create mode 100644 src/features/relay/artifact-conversation.test.ts
create mode 100644 src/features/relay/artifact-conversation.ts
diff --git a/src/bundled/tasks/TaskComments.test.tsx b/src/bundled/tasks/TaskComments.test.tsx
new file mode 100644
index 0000000000..bf91071fad
--- /dev/null
+++ b/src/bundled/tasks/TaskComments.test.tsx
@@ -0,0 +1,153 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+} from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+import type { ConversationHostServices } from "../../features/conversation/ConversationHost";
+import type {
+ ChannelReach,
+ ChannelReachState,
+} from "../../features/relay/channel-reach";
+import type { RelaySession } from "../../features/relay/session";
+import { TASK_TYPE, type Task, taskOf } from "./model";
+import { TaskComments } from "./TaskComments";
+
+afterEach(cleanup);
+
+const home = "22222222-2222-4222-8222-222222222222";
+const conversation = "33333333-3333-8333-8333-333333333333";
+const task = taskOf({
+ id: "d".repeat(64),
+ pubkey: "b".repeat(64),
+ created_at: 5,
+ kind: 45010,
+ content: JSON.stringify({ version: 2, author: "a".repeat(64) }),
+ tags: [
+ ["d", "11111111-1111-4111-8111-111111111111"],
+ ["h", home],
+ ["type", TASK_TYPE],
+ ["title", "Fix the header"],
+ ],
+}) as Task;
+
+/** Handles the test answers for, one per channel. */
+function setup(options: { conversations?: boolean } = {}) {
+ const handles = new Map<
+ string,
+ { set(state: ChannelReachState): void; retry: ReturnType }
+ >();
+ const reach = (id: string): ChannelReach => {
+ let state: ChannelReachState = { status: "loading" };
+ const listeners = new Set<() => void>();
+ const retry = vi.fn();
+ handles.set(id, {
+ set(next) {
+ state = next;
+ for (const listener of listeners) listener();
+ },
+ retry,
+ });
+ return {
+ snapshot: () => state,
+ subscribe(listener) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ retry,
+ release: () => {},
+ };
+ };
+ const openConversation = vi.fn(async () => conversation);
+ const session = {
+ viewer: "a".repeat(64),
+ channels: { reach },
+ artifacts: {
+ conversationId: async () => conversation,
+ ...(options.conversations === false ? {} : { openConversation }),
+ },
+ } as unknown as RelaySession;
+ const view = () =>
+ render(
+ ,
+ );
+ return { handles, openConversation, view };
+}
+
+const answer = async (
+ handles: ReturnType["handles"],
+ id: string,
+ state: ChannelReachState,
+) => {
+ await vi.waitFor(() => expect(handles.has(id)).toBe(true));
+ act(() => handles.get(id)?.set(state));
+};
+
+it("waits, without a composer, until the relay answers", async () => {
+ const { handles, view } = setup();
+ view();
+ expect(screen.getByRole("status")).toHaveTextContent("Loading comments…");
+ await answer(handles, conversation, {
+ status: "unavailable",
+ reason: "unavailable",
+ });
+ // The home decides who may start the conversation; still asking.
+ expect(screen.getByRole("status")).toHaveTextContent("Loading comments…");
+ expect(screen.queryByRole("button")).toBeNull();
+});
+
+it("lets someone who can post in the task's home start its comments", async () => {
+ const { handles, openConversation, view } = setup();
+ view();
+ await answer(handles, conversation, {
+ status: "unavailable",
+ reason: "unavailable",
+ });
+ await answer(handles, home, { status: "open", post: true, joined: true });
+ expect(screen.getByText("No comments yet.")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Add a comment" }));
+ expect(openConversation).toHaveBeenCalledWith(task.id, expect.anything());
+});
+
+it("offers a view-only person no way to start comments", async () => {
+ const { handles, view } = setup();
+ view();
+ await answer(handles, conversation, {
+ status: "unavailable",
+ reason: "unavailable",
+ });
+ await answer(handles, home, { status: "open", post: false, joined: false });
+ expect(screen.getByText("No comments yet.")).toBeInTheDocument();
+ expect(screen.queryByRole("button")).toBeNull();
+});
+
+it("offers to try again when the relay couldn't be asked", async () => {
+ const { handles, view } = setup();
+ view();
+ await answer(handles, conversation, {
+ status: "unavailable",
+ reason: "failed",
+ });
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Couldn’t load comments.",
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(handles.get(conversation)?.retry).toHaveBeenCalled();
+ expect(handles.get(home)?.retry).toHaveBeenCalled();
+});
+
+it("says so where the community has no task comments", () => {
+ setup({ conversations: false }).view();
+ expect(
+ screen.getByText("Comments aren’t available in this community yet."),
+ ).toBeInTheDocument();
+});
diff --git a/src/bundled/tasks/TaskComments.tsx b/src/bundled/tasks/TaskComments.tsx
new file mode 100644
index 0000000000..70fb52302c
--- /dev/null
+++ b/src/bundled/tasks/TaskComments.tsx
@@ -0,0 +1,197 @@
+// A task's comments: its own conversation, held open by name. The relay's
+// answer alone decides what shows: a neutral wait, then the comments with a
+// composer or read-only, never a composer while posting is unknown.
+import { useEffect, useState, useSyncExternalStore } from "react";
+import {
+ ConversationChannel,
+ ConversationComposer,
+ ConversationTimeline,
+} from "../../features/conversation/Conversation";
+import type { ConversationHostServices } from "../../features/conversation/ConversationHost";
+import { MessageManagementStatus } from "../../features/messages/MessageManagement";
+import type {
+ ChannelReach,
+ ChannelReachState,
+} from "../../features/relay/channel-reach";
+import { useChannelWindow } from "../../features/relay/react";
+import type { RelaySession } from "../../features/relay/session";
+import { Button } from "../../shared/design-system/ui/Button";
+import type { Task } from "./model";
+import styles from "./Tasks.module.css";
+
+const loading: ChannelReachState = Object.freeze({ status: "loading" });
+const quiet = () => () => {};
+
+/** Holds channel `id` open for as long as the view shows it. */
+function useReach(session: RelaySession, id: string | undefined) {
+ const [handle, setHandle] = useState();
+ useEffect(() => {
+ const reach = session.channels.reach;
+ if (!id || !reach) return;
+ const held = reach(id);
+ setHandle(held);
+ return () => {
+ held.release();
+ setHandle(undefined);
+ };
+ }, [session, id]);
+ const read = () => handle?.snapshot() ?? loading;
+ const state = useSyncExternalStore(handle?.subscribe ?? quiet, read, read);
+ return { state, retry: () => handle?.retry() };
+}
+
+function useConversationId(session: RelaySession, task: Task) {
+ const [id, setId] = useState();
+ useEffect(() => {
+ let current = true;
+ setId(undefined);
+ void session.artifacts.conversationId(task.id).then((derived) => {
+ if (current) setId(derived);
+ });
+ return () => {
+ current = false;
+ };
+ }, [session, task.id]);
+ return id;
+}
+
+export type TaskCommentsProps = {
+ session: RelaySession;
+ /** The relay connection's scope, which conversation views share. */
+ scope: string;
+ host: ConversationHostServices;
+ task: Task;
+};
+
+export function TaskComments({
+ session,
+ scope,
+ host,
+ task,
+}: TaskCommentsProps) {
+ const id = useConversationId(session, task);
+ const conversation = useReach(session, id);
+ const home = useReach(session, task.home);
+ const [opening, setOpening] = useState(false);
+ const [error, setError] = useState();
+ const open = session.artifacts.openConversation;
+ if (!session.channels.reach || !open)
+ return (
+
+ Comments aren’t available in this community yet.
+
+ );
+ const state = conversation.state;
+ if (state.status === "open" && id)
+ return (
+
+
+
+
+ {state.post ? (
+
+ ) : (
+
Read-only access
+ )}
+
+
+ );
+ const reason = state.status === "unavailable" ? state.reason : undefined;
+ if (!reason || (reason === "unavailable" && home.state.status === "loading"))
+ return (
+
+ Loading comments…
+
+ );
+ if (reason === "failed")
+ return (
+
+
Couldn’t load comments.
+
{
+ conversation.retry();
+ home.retry();
+ }}
+ >
+ Try again
+
+
+ );
+ // Nobody has commented yet. Whoever may post in the task's home starts it.
+ const canStart = home.state.status === "open" && home.state.post;
+ return (
+
+
No comments yet.
+ {canStart ? (
+
{
+ setOpening(true);
+ setError(undefined);
+ open(task.id, AbortSignal.timeout(20_000))
+ .catch((reason: unknown) =>
+ setError(
+ reason instanceof Error
+ ? reason.message
+ : "Couldn’t start comments. Try again.",
+ ),
+ )
+ .finally(() => setOpening(false));
+ }}
+ >
+ Add a comment
+
+ ) : null}
+ {error ? (
+
+ {error}
+
+ ) : null}
+
+ );
+}
+
+function CommentList({ session, id }: { session: RelaySession; id: string }) {
+ const window = useChannelWindow(session.channels, id);
+ if (window.status === "error" && !window.rows.length)
+ return (
+
+
{window.error}
+
session.channels.ensure(id)}
+ >
+ Try again
+
+
+ );
+ if (window.status !== "ready" && !window.rows.length)
+ return (
+
+ Loading comments…
+
+ );
+ return (
+
+
+
+ );
+}
diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx
index a8d637267f..5b2ae46f3c 100644
--- a/src/bundled/tasks/TaskView.test.tsx
+++ b/src/bundled/tasks/TaskView.test.tsx
@@ -113,7 +113,6 @@ it("shows a guest the task with no edit controls", () => {
onSaved={() => {}}
/>,
);
- expect(screen.getByText("Read-only access")).toBeInTheDocument();
for (const name of ["Edit", "Move…"])
expect(screen.queryByRole("button", { name })).toBeNull();
expect(screen.queryByLabelText("Status")).toBeNull();
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index f5fcc65b27..8557332417 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -29,6 +29,7 @@ import {
import { AlertDialog } from "../../shared/design-system/ui/AlertDialog";
import { AvatarStack } from "../../shared/design-system/ui/AvatarStack";
import { Button } from "../../shared/design-system/ui/Button";
+import { TaskComments, type TaskCommentsProps } from "./TaskComments";
import { Combobox } from "../../shared/design-system/ui/Combobox";
import { Field } from "../../shared/design-system/ui/Field";
import { InlineHeader } from "../../shared/design-system/ui/Header";
@@ -89,6 +90,9 @@ export type TaskViewProps = {
task: Task | undefined;
/** Where a new task starts. */
home?: string | undefined;
+ /** Where task comments show: the connection's scope and the plugin's
+ * conversation services. Absent, the view shows no comments. */
+ comments?: Pick | undefined;
/** The conversation this view sits beside, which "Link this chat" links. */
currentChat?: string | undefined;
openConversation(channelId: string): void;
@@ -133,6 +137,7 @@ function TaskDetails({
openConversation,
onSaved,
edit,
+ comments,
}: TaskViewProps & { task: Task; edit(): void }) {
const notify = useToastNotification();
const canEdit = useCanEdit(session, task.home);
@@ -245,9 +250,9 @@ function TaskDetails({
/>
- {canEdit ? null : (
- Read-only access
- )}
+ {comments ? (
+
+ ) : null}
{moving ? (
& {
relay: RelayData;
navigator: Navigation;
+ host: ConversationHostServices;
};
-export function TasksPage({ relay, navigation, navigator }: TasksPageProps) {
+export function TasksPage({
+ relay,
+ navigation,
+ navigator,
+ host,
+}: TasksPageProps) {
const connection = useRelayConnection(relay);
const request = useMemo(
() => navigation?.forSession(relay, connection),
@@ -86,6 +93,9 @@ export function TasksPage({ relay, navigation, navigator }: TasksPageProps) {
key={`${connection.scope}:${connection.generation}`}
session={connection.session}
opened={opened}
+ comments={
+ connection.scope ? { scope: connection.scope, host } : undefined
+ }
openConversation={(channelId) =>
void navigator.open({
version: 1,
@@ -179,11 +189,12 @@ function TaskBoard({
session,
opened,
openConversation,
+ comments,
}: {
session: RelaySession;
opened: string | undefined;
openConversation(channelId: string): void;
-}) {
+} & Pick) {
const state = useTasksWithSaved(session);
const places = usePlaces(
session,
@@ -388,6 +399,7 @@ function TaskBoard({
: undefined
}
openConversation={openConversation}
+ comments={comments}
draft={selected ? drafts.current.get(selected) : undefined}
onDraftChange={onDraftChange}
onSaved={(next) => {
diff --git a/src/bundled/tasks/TasksPanel.tsx b/src/bundled/tasks/TasksPanel.tsx
index 9d518b2ef3..0597668551 100644
--- a/src/bundled/tasks/TasksPanel.tsx
+++ b/src/bundled/tasks/TasksPanel.tsx
@@ -34,11 +34,12 @@ export function TasksPanel({
session,
chat,
openConversation,
+ comments,
}: {
session: RelaySession;
/** The conversation this panel sits beside. */
chat: string;
-} & Pick) {
+} & Pick) {
const state = useTasksWithSaved(session);
const notify = useToastNotification();
const [open, setOpen] = useState();
@@ -111,6 +112,7 @@ export function TasksPanel({
home={chat}
currentChat={chat}
openConversation={openConversation}
+ comments={comments}
onSaved={(next) => {
state.setSaved(next);
setOpen(next.id);
diff --git a/src/bundled/tasks/conversation.test.ts b/src/bundled/tasks/conversation.test.ts
new file mode 100644
index 0000000000..62e18c699a
--- /dev/null
+++ b/src/bundled/tasks/conversation.test.ts
@@ -0,0 +1,85 @@
+import { expect, it, vi } from "vitest";
+import type { ChannelReachState } from "../../features/relay/channel-reach";
+import type { RelaySession } from "../../features/relay/session";
+import { postComment } from "./conversation";
+import type { Task } from "./model";
+
+const conversation = "33333333-3333-8333-8333-333333333333";
+const task = { id: "11111111-1111-4111-8111-111111111111" } as Task;
+
+/** A session whose relay answers `state` and settles each send as `delivery`. */
+function setup(state: ChannelReachState, delivery: "accepted" | "failed") {
+ const listeners = new Set<() => void>();
+ let items: { event: { id: string }; delivery: string }[] = [];
+ const release = vi.fn();
+ const send = vi.fn((_id: string, _text: string) => {
+ items = [{ event: { id: "m1" }, delivery: "sending" }];
+ queueMicrotask(() => {
+ items = [{ event: { id: "m1" }, delivery }];
+ for (const listener of listeners) listener();
+ });
+ return "m1";
+ });
+ const session = {
+ artifacts: { openConversation: vi.fn(async () => conversation) },
+ channels: {
+ reach: () => ({
+ snapshot: () => state,
+ subscribe: () => () => {},
+ retry() {},
+ release,
+ }),
+ },
+ messages: { send },
+ outbox: {
+ snapshot: () => items,
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ },
+ } as unknown as RelaySession;
+ return { session, send, release };
+}
+const signal = () => new AbortController().signal;
+
+it("opens the task's conversation and waits for the relay to accept the comment", async () => {
+ const t = setup({ status: "open", post: true, joined: false }, "accepted");
+ await postComment(t.session, task, "Shipped.", signal());
+ expect(t.session.artifacts.openConversation).toHaveBeenCalledWith(
+ task.id,
+ expect.anything(),
+ );
+ expect(t.send).toHaveBeenCalledWith(conversation, "Shipped.");
+ expect(t.release).toHaveBeenCalled();
+});
+
+it("never sends where the relay says the person can only read", async () => {
+ const t = setup({ status: "open", post: false, joined: false }, "accepted");
+ await expect(postComment(t.session, task, "Hi", signal())).rejects.toThrow(
+ "only read",
+ );
+ expect(t.send).not.toHaveBeenCalled();
+ expect(t.release).toHaveBeenCalled();
+});
+
+it("tells apart couldn't-check from no access", async () => {
+ for (const [reason, message] of [
+ ["failed", "Try again"],
+ ["unavailable", "aren’t available to you"],
+ ] as const) {
+ const t = setup({ status: "unavailable", reason }, "accepted");
+ await expect(postComment(t.session, task, "Hi", signal())).rejects.toThrow(
+ message,
+ );
+ expect(t.send).not.toHaveBeenCalled();
+ }
+});
+
+it("reports a comment the relay refused", async () => {
+ const t = setup({ status: "open", post: true, joined: false }, "failed");
+ await expect(postComment(t.session, task, "Hi", signal())).rejects.toThrow(
+ "didn’t post",
+ );
+ expect(t.release).toHaveBeenCalled();
+});
diff --git a/src/bundled/tasks/conversation.ts b/src/bundled/tasks/conversation.ts
index e268a268ed..709c6cbcdf 100644
--- a/src/bundled/tasks/conversation.ts
+++ b/src/bundled/tasks/conversation.ts
@@ -1,36 +1,98 @@
-// A task's comments live in its own hidden conversation: a channel of type
-// `artifact` whose id is computed from the task alone, so anyone who can read
-// the task finds it with no lookup. The relay makes it on the first comment,
-// under the task's home, with no members and no owner; who reads and posts
-// there always comes from the home, and a move takes it along.
+// A task's comments live in its own hidden conversation (NIP-AR): the relay
+// makes it on the first comment, under the task's home, and who reads and
+// posts there always comes from the home. The app holds it open by name with
+// `channels.reach`, since it is never in the viewer's list.
+import type {
+ ChannelReach,
+ ChannelReachState,
+} from "../../features/relay/channel-reach";
import type { RelaySession } from "../../features/relay/session";
import type { Task } from "./model";
-const encoder = new TextEncoder();
+/** The first answer that is not `loading`. */
+export function settled(
+ handle: ChannelReach,
+ signal: AbortSignal,
+): Promise {
+ return new Promise((resolve, reject) => {
+ const check = () => {
+ const state = handle.snapshot();
+ if (state.status === "loading") return;
+ stop();
+ resolve(state);
+ };
+ const abort = () => {
+ stop();
+ reject(signal.reason);
+ };
+ const unsubscribe = handle.subscribe(check);
+ const stop = () => {
+ unsubscribe();
+ signal.removeEventListener("abort", abort);
+ };
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) abort();
+ else check();
+ });
+}
-/** The conversation id for task `d`: UUIDv8 of the first 16 bytes of
- * SHA-256("nip-ar-conversation\0" + d), over the UTF-8 bytes of `d`. */
-export async function conversationId(d: string) {
- const hash = new Uint8Array(
- await crypto.subtle.digest(
- "SHA-256",
- encoder.encode(`nip-ar-conversation\0${d}`),
- ),
- ).slice(0, 16);
- hash[6] = ((hash[6] ?? 0) & 0x0f) | 0x80;
- hash[8] = ((hash[8] ?? 0) & 0x3f) | 0x80;
- const hex = [...hash].map((b) => b.toString(16).padStart(2, "0")).join("");
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+/** Resolves once the relay accepts message `id`; rejects if it fails. */
+function delivered(session: RelaySession, id: string, signal: AbortSignal) {
+ const outbox = session.outbox;
+ if (!outbox) return Promise.reject(new Error("Couldn’t post the comment."));
+ return new Promise((resolve, reject) => {
+ let seen = false;
+ const check = () => {
+ const item = outbox.snapshot().find((entry) => entry.event.id === id);
+ if (item) seen = true;
+ const delivery = item?.delivery;
+ if (delivery === "sending" || delivery === "unknown") return;
+ if (!item && !seen) return;
+ stop();
+ if (delivery === "failed")
+ reject(new Error("The comment didn’t post. Try again."));
+ else resolve();
+ };
+ const abort = () => {
+ stop();
+ reject(signal.reason);
+ };
+ const unsubscribe = outbox.subscribe(check);
+ const stop = () => {
+ unsubscribe();
+ signal.removeEventListener("abort", abort);
+ };
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) abort();
+ else check();
+ });
}
-/** Posts `text` in `task`'s conversation, making it first if nobody has.
- * The app can't yet post in a conversation outside the viewer's list, which
- * this one always is; until it can, this fails and says so. */
+/** Opens `task`'s conversation if nobody has, then posts `text` there and
+ * waits for the relay to accept it. */
export async function postComment(
- _session: RelaySession,
- _task: Task,
- _text: string,
- _signal: AbortSignal,
+ session: RelaySession,
+ task: Task,
+ text: string,
+ signal: AbortSignal,
): Promise {
- throw new Error("Comments aren’t available in this version yet.");
+ const open = session.artifacts.openConversation;
+ const reach = session.channels.reach;
+ if (!open || !reach)
+ throw new Error("Comments aren’t available in this community yet.");
+ const id = await open(task.id, signal);
+ const handle = reach(id);
+ try {
+ const state = await settled(handle, signal);
+ if (state.status !== "open")
+ throw new Error(
+ state.status === "unavailable" && state.reason === "failed"
+ ? "Couldn’t reach the community to comment. Try again."
+ : "This task’s comments aren’t available to you.",
+ );
+ if (!state.post) throw new Error("You can only read this task’s comments.");
+ await delivered(session, session.messages.send(id, text), signal);
+ } finally {
+ handle.release();
+ }
}
diff --git a/src/bundled/tasks/index.tsx b/src/bundled/tasks/index.tsx
index 15d84053d6..3cc7bfbdfe 100644
--- a/src/bundled/tasks/index.tsx
+++ b/src/bundled/tasks/index.tsx
@@ -33,6 +33,12 @@ const scopeOf = (state: RelaySnapshot) =>
export const apply: PluginModule["apply"] = (ctx) => {
let active = true;
+ // Comments open panels and links the way any conversation does.
+ const host = {
+ panels: ctx.panels,
+ relay: ctx.relay,
+ navigation: ctx.navigation,
+ };
ctx.effect(() => () => {
active = false;
});
@@ -45,7 +51,12 @@ export const apply: PluginModule["apply"] = (ctx) => {
placement: "dock",
route: { version: 1, validate: (params) => !!taskRoute(params) },
component: (props) => (
-
+
),
});
@@ -96,6 +107,7 @@ export const apply: PluginModule["apply"] = (ctx) => {
key={`${state.scope}:${state.generation}:${channelContext.channelId}`}
session={state.session}
chat={channelContext.channelId}
+ comments={{ scope: state.scope, host }}
openConversation={(channelId) =>
void ctx.navigation.open({
version: 1,
diff --git a/src/features/relay/artifact-conversation.test.ts b/src/features/relay/artifact-conversation.test.ts
new file mode 100644
index 0000000000..8de556bff1
--- /dev/null
+++ b/src/features/relay/artifact-conversation.test.ts
@@ -0,0 +1,61 @@
+import { expect, it } from "vitest";
+import {
+ artifactConversationId,
+ artifactConversationsCapability,
+ conversationOpening,
+ isConversationOpening,
+} from "./artifact-conversation";
+
+const d = "8c1f3d2e-4b5a-4c6d-9e7f-0a1b2c3d4e5f";
+
+it("derives the relay's conversation address from the artifact alone", async () => {
+ // The relay's published fixture (NOSTR.md, NIP-AR conversations).
+ expect(await artifactConversationId(d)).toBe(
+ "3f3e3cd7-3b56-81d9-8dd2-8d8b5b1f6d57",
+ );
+});
+
+it("is advertised by the relay's supported extensions", () => {
+ expect(
+ artifactConversationsCapability({
+ supported_extensions: ["buzz-artifact-conversations"],
+ }),
+ ).toBe(true);
+ expect(artifactConversationsCapability({ supported_extensions: [] })).toBe(
+ false,
+ );
+});
+
+it("opens exactly one artifact's conversation, and nothing else passes", async () => {
+ const opening = await conversationOpening(d, 1);
+ expect(opening).toEqual({
+ kind: 9007,
+ created_at: 1,
+ content: "",
+ tags: [
+ ["h", "3f3e3cd7-3b56-81d9-8dd2-8d8b5b1f6d57"],
+ ["artifact", d],
+ ],
+ });
+ expect(await isConversationOpening(opening)).toBe(true);
+ for (const forged of [
+ { ...opening, kind: 9 },
+ { ...opening, content: "hello" },
+ {
+ ...opening,
+ tags: [
+ ["h", "other"],
+ ["artifact", d],
+ ],
+ },
+ { ...opening, tags: [...opening.tags, ["name", "Squatted"]] },
+ {
+ ...opening,
+ tags: [
+ ["h", opening.tags[0]?.[1] ?? ""],
+ ["artifact", ""],
+ ],
+ },
+ ])
+ expect(await isConversationOpening(forged)).toBe(false);
+});
diff --git a/src/features/relay/artifact-conversation.ts b/src/features/relay/artifact-conversation.ts
new file mode 100644
index 0000000000..171e2b537c
--- /dev/null
+++ b/src/features/relay/artifact-conversation.ts
@@ -0,0 +1,66 @@
+// NIP-AR conversations (buzz-artifact-conversations): an artifact's comments
+// live in a hidden channel of type `artifact` whose id comes from the
+// artifact's `d` alone, so anyone who can read the artifact finds it with no
+// lookup. The relay makes it on an opening kind:9007, under the artifact's
+// home and with no members; who reads and posts there comes from the home.
+import type { EventTemplate } from "nostr-tools";
+import type { RelayEvent } from "./events";
+
+export const ARTIFACT_CONVERSATIONS_EXTENSION = "buzz-artifact-conversations";
+
+const encoder = new TextEncoder();
+
+/** Whether the relay advertises artifact conversations in NIP-11. */
+export function artifactConversationsCapability(info: unknown): boolean {
+ const extensions = (info as { supported_extensions?: unknown } | undefined)
+ ?.supported_extensions;
+ return (
+ Array.isArray(extensions) &&
+ extensions.includes(ARTIFACT_CONVERSATIONS_EXTENSION)
+ );
+}
+
+/** The conversation id for artifact `d`: UUIDv8 of the first 16 bytes of
+ * SHA-256("nip-ar-conversation\0" + d), over the UTF-8 bytes of `d`. */
+export async function artifactConversationId(d: string): Promise {
+ const hash = new Uint8Array(
+ await crypto.subtle.digest(
+ "SHA-256",
+ encoder.encode(`nip-ar-conversation\0${d}`),
+ ),
+ ).slice(0, 16);
+ hash[6] = ((hash[6] ?? 0) & 0x0f) | 0x80;
+ hash[8] = ((hash[8] ?? 0) & 0x3f) | 0x80;
+ const hex = [...hash].map((b) => b.toString(16).padStart(2, "0")).join("");
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+}
+
+/** The kind:9007 that opens artifact `d`'s conversation. */
+export async function conversationOpening(
+ d: string,
+ createdAt = Math.floor(Date.now() / 1000),
+): Promise {
+ if (!d) throw new Error("A conversation needs its artifact.");
+ return {
+ kind: 9007,
+ created_at: createdAt,
+ content: "",
+ tags: [
+ ["h", await artifactConversationId(d)],
+ ["artifact", d],
+ ],
+ };
+}
+
+/** Whether `event` is exactly an opening: kind:9007, empty, and only the
+ * derived `h` with its `artifact`. Nothing else may pass this writer. */
+export async function isConversationOpening(
+ event: EventTemplate | RelayEvent,
+): Promise {
+ if (event.kind !== 9007 || event.content !== "" || event.tags.length !== 2)
+ return false;
+ const [h, artifact] = event.tags;
+ if (h?.[0] !== "h" || artifact?.[0] !== "artifact") return false;
+ if (h.length !== 2 || artifact.length !== 2 || !artifact[1]) return false;
+ return h[1] === (await artifactConversationId(artifact[1]));
+}
diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts
index 3234e415af..08646cc4d0 100644
--- a/src/features/relay/native.ts
+++ b/src/features/relay/native.ts
@@ -71,6 +71,10 @@ import {
import type { AgentLibrary } from "../agents/library";
import { observerFrame } from "../agents/observer";
import { ARTIFACT_KIND } from "../agents/agent-config-artifacts";
+import {
+ artifactConversationsCapability,
+ isConversationOpening,
+} from "./artifact-conversation";
import {
acceptPublish,
acceptReadStatePublish,
@@ -651,6 +655,33 @@ export async function connectNativeTransport(
},
}
: {}),
+ ...(artifactConversationsCapability(info)
+ ? {
+ artifactConversations: {
+ kinds: [9007],
+ isNotSent: (error: unknown) => error instanceof PublishNotSent,
+ async sign(event: EventTemplate, signal: AbortSignal) {
+ if (!(await isConversationOpening(event)))
+ throw new Error("Not a conversation opening");
+ const signed = await writer.sign(event, signal);
+ if (
+ signed.pubkey !== transport.viewer ||
+ !(await isConversationOpening(signed))
+ )
+ throw new Error("Invalid conversation opening");
+ return signed;
+ },
+ async publish(event: RelayEvent, signal: AbortSignal) {
+ if (
+ event.pubkey !== transport.viewer ||
+ !(await isConversationOpening(event))
+ )
+ throw new Error("Not this viewer's conversation opening");
+ return (await writer.publish(event, signal)) ?? "";
+ },
+ },
+ }
+ : {}),
async openDirectMessage(pubkeys, signal) {
signal.throwIfAborted();
const id = await invoke("relay_direct_message", {
diff --git a/src/features/relay/session.ts b/src/features/relay/session.ts
index 889dc9a5e9..0c1eb8c84d 100644
--- a/src/features/relay/session.ts
+++ b/src/features/relay/session.ts
@@ -3,6 +3,10 @@ import {
VIEWER_ACCESS_CHANGED_KIND,
} from "./channel-access";
import { createChannelReach } from "./channel-reach";
+import {
+ artifactConversationId,
+ conversationOpening,
+} from "./artifact-conversation";
import type { LocalAgentSource } from "../agents/local-activity";
// FOUNDATION: One relay session owns reads, local intent, delivery and shared views.
import { createSoloPreferences, soloGroups } from "./solo-preferences";
@@ -3156,6 +3160,33 @@ export function createRelaySession(
* this relay has no sync; use read() with `artifact: "current"` instead.
* Dispose with the plugin's scope. */
artifacts: {
+ /** The channel id of artifact `d`'s conversation (NIP-AR). Read it
+ * through `channels.reach`; it never lists. */
+ conversationId: artifactConversationId,
+ /** Opens artifact `d`'s conversation, for someone who may post in its
+ * home; opening one that exists changes nothing. Resolves with its id
+ * once the relay accepts. Absent where the relay has no conversations. */
+ ...(transport?.artifactConversations
+ ? {
+ async openConversation(d: string, signal: AbortSignal) {
+ const writer = transport.artifactConversations;
+ if (!writer || closed) throw new Error("Relay is unavailable");
+ const event = await writer.sign(
+ await conversationOpening(d),
+ signal,
+ );
+ try {
+ await writer.publish(event, signal);
+ } catch (error) {
+ if (!(error instanceof PublishRejected)) throw error;
+ throw new Error("You can’t start comments on this task.");
+ }
+ const id = await artifactConversationId(d);
+ reach?.recheck([id]);
+ return id;
+ },
+ }
+ : {}),
sync(filter: unknown): ArtifactSyncView {
if (closed || artifactSyncs.size >= ARTIFACT_SYNC_MAX_VIEWS)
throw new Error("Artifact sync capacity unavailable");
diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts
index 6f5484359e..7d0b171a9b 100644
--- a/src/features/relay/transport.ts
+++ b/src/features/relay/transport.ts
@@ -127,6 +127,9 @@ export interface ReadTransport {
readonly memberAdministration?: RelayWriter;
/** NIP-AR kind-45010 config artifacts only; never supplied to the outbox. */
readonly configArtifacts?: RelayWriter;
+ /** Opens NIP-AR artifact conversations (`buzz-artifact-conversations`):
+ * the exact kind:9007 of `isConversationOpening`, nothing else. */
+ readonly artifactConversations?: RelayWriter;
/** Narrow NIP-IA 9035/9036 signer/publisher; never supplied to the message outbox. */
readonly identityArchive?: RelayWriter;
/** Purpose-bound observer decoding on the shared host live stream. */
From e930ca86ead378bba31aa18264bacef0f99aed18 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 09:14:59 -0800
Subject: [PATCH 12/18] fix(tasks): take edit rights from the relay, and keep
agents to their own reads
Edit controls, linking, the read-only notice and the place lists all follow
the relay's answer for the task's place, not channel membership. Status,
assignees, creator and via live in tags the relay can check and filter on.
Only people who can see a task can be assigned, and a move names anyone who
would lose access before it unassigns them.
Agent tools read as the agent and comment as the agent; saves stay signed by
the owner and need the agent to read both ends of a move. Closing a task
posts its evidence first and stays open when that fails. Moves preview and
then confirm. Find filters on the relay and says when results may be
incomplete.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/TaskComments.tsx | 32 +-
src/bundled/tasks/TaskView.test.tsx | 158 +++++++++-
src/bundled/tasks/TaskView.tsx | 283 ++++++++++++++----
src/bundled/tasks/Tasks.module.css | 34 ++-
src/bundled/tasks/TasksPage.tsx | 56 ++--
src/bundled/tasks/conversation.test.ts | 99 ++-----
src/bundled/tasks/conversation.ts | 112 ++-----
src/bundled/tasks/model.test.ts | 98 +++---
src/bundled/tasks/model.ts | 58 ++--
src/bundled/tasks/places.ts | 50 +++-
src/bundled/tasks/react.ts | 83 +++++-
src/bundled/tasks/store.ts | 60 +++-
src/bundled/tasks/tools.test.ts | 337 +++++++++++++++++----
src/bundled/tasks/tools.ts | 393 +++++++++++++++++++------
14 files changed, 1322 insertions(+), 531 deletions(-)
diff --git a/src/bundled/tasks/TaskComments.tsx b/src/bundled/tasks/TaskComments.tsx
index 70fb52302c..45f010a707 100644
--- a/src/bundled/tasks/TaskComments.tsx
+++ b/src/bundled/tasks/TaskComments.tsx
@@ -1,7 +1,7 @@
// A task's comments: its own conversation, held open by name. The relay's
// answer alone decides what shows: a neutral wait, then the comments with a
// composer or read-only, never a composer while posting is unknown.
-import { useEffect, useState, useSyncExternalStore } from "react";
+import { useEffect, useState } from "react";
import {
ConversationChannel,
ConversationComposer,
@@ -9,37 +9,13 @@ import {
} from "../../features/conversation/Conversation";
import type { ConversationHostServices } from "../../features/conversation/ConversationHost";
import { MessageManagementStatus } from "../../features/messages/MessageManagement";
-import type {
- ChannelReach,
- ChannelReachState,
-} from "../../features/relay/channel-reach";
import { useChannelWindow } from "../../features/relay/react";
import type { RelaySession } from "../../features/relay/session";
import { Button } from "../../shared/design-system/ui/Button";
import type { Task } from "./model";
+import { useReach } from "./react";
import styles from "./Tasks.module.css";
-const loading: ChannelReachState = Object.freeze({ status: "loading" });
-const quiet = () => () => {};
-
-/** Holds channel `id` open for as long as the view shows it. */
-function useReach(session: RelaySession, id: string | undefined) {
- const [handle, setHandle] = useState();
- useEffect(() => {
- const reach = session.channels.reach;
- if (!id || !reach) return;
- const held = reach(id);
- setHandle(held);
- return () => {
- held.release();
- setHandle(undefined);
- };
- }, [session, id]);
- const read = () => handle?.snapshot() ?? loading;
- const state = useSyncExternalStore(handle?.subscribe ?? quiet, read, read);
- return { state, retry: () => handle?.retry() };
-}
-
function useConversationId(session: RelaySession, task: Task) {
const [id, setId] = useState();
useEffect(() => {
@@ -128,9 +104,13 @@ export function TaskComments({
);
// Nobody has commented yet. Whoever may post in the task's home starts it.
const canStart = home.state.status === "open" && home.state.post;
+ const readOnly = home.state.status === "open" && !home.state.post;
return (
No comments yet.
+ {readOnly ? (
+
Read-only access
+ ) : null}
{canStart ? (
({
sig: "",
created_at: 5,
kind: 45010,
- content: JSON.stringify({ version: 2, author: viewer }),
+ content: JSON.stringify({ version: 3 }),
tags: [
["d", id],
["h", home],
["type", TASK_TYPE],
["title", title],
+ ["creator", viewer],
],
});
const mine = taskOf(revision("d".repeat(64), "Fix the header")) as Task;
const theirs = revision("c".repeat(64), "Their title");
+const project = "33333333-3333-4333-8333-333333333333";
+const launch = "44444444-4444-4444-8444-444444444444";
+const leo = "c".repeat(64);
+
+type Answer = ChannelReachState;
+const asking: Answer = { status: "loading" };
+const opened = (post: boolean): Answer => ({
+ status: "open",
+ post,
+ joined: false,
+});
+
+/** A session whose relay answers each place by name from `answers`, and
+ * whose channel list holds only `home`. */
function setup(
publish: () => Promise,
- role: ChannelSummary["viewerRole"] = "member",
+ answers: Record = { [home]: opened(true) },
) {
const signed: { tags: string[][] }[] = [];
const channels: ChannelSummary[] = [
- { id: home, name: "design", channelType: "stream", viewerRole: role },
+ { id: home, name: "design", channelType: "stream", viewerRole: "member" },
+ { id: launch, name: "launch", channelType: "stream", readOnly: true },
];
- const profiles = new Map();
+ const profiles = new Map([[leo, { name: "Leo" }]]);
const list = { status: "ready", channels };
+ const metadata = (d: string, name: string, extra: string[][] = []) => ({
+ id: d.slice(0, 8).padEnd(64, "0"),
+ pubkey: "e".repeat(64),
+ sig: "",
+ created_at: 1,
+ kind: 39000,
+ content: "",
+ tags: [["d", d], ["name", name], ["private"], ...extra],
+ });
const session = {
viewer,
+ relayAuthor: "e".repeat(64),
media: () => undefined,
profiles: {
snapshot: () => profiles,
@@ -52,15 +79,44 @@ function setup(
ensureList: () => () => {},
subscribeList: () => () => {},
list: () => list,
+ reach: (channel: string) => ({
+ snapshot: () => answers[channel] ?? asking,
+ subscribe: () => () => {},
+ retry() {},
+ release() {},
+ }),
},
- snapshotRead: vi.fn(async (filters: { kinds?: number[] }[]) =>
- filters[0]?.kinds?.includes(45010) &&
- !(filters[0] as Record)["#type"]
- ?.toString()
- .includes("link")
+ artifacts: { conversationId: async () => "f".repeat(8) },
+ snapshotRead: vi.fn(async (filters: Record[]) => {
+ const filter = filters[0] ?? {};
+ const kinds = filter.kinds as number[] | undefined;
+ if (kinds?.includes(39000))
+ return [
+ metadata(home, "design", [["parent", project]]),
+ metadata(project, "Payments"),
+ metadata(launch, "launch"),
+ ].filter((event) =>
+ (filter["#d"] as string[]).includes(event.tags[0]?.[1] ?? ""),
+ );
+ if (kinds?.includes(39002))
+ return [
+ {
+ ...metadata(home, ""),
+ kind: 39002,
+ tags: [
+ ["d", home],
+ ["p", viewer],
+ ["p", leo],
+ ],
+ },
+ ].filter((event) =>
+ (filter["#d"] as string[]).includes(event.tags[0]?.[1] ?? ""),
+ );
+ return kinds?.includes(45010) &&
+ !String(filter["#type"] ?? "").includes("link")
? [theirs]
- : [],
- ),
+ : [];
+ }),
configArtifactWriter: {
sign: vi.fn(async (template: { tags: string[][] }) => {
signed.push(template);
@@ -103,22 +159,70 @@ it("keeps the person's text on a conflict, then saves over the newer version", a
expect(signed[1]?.tags).toContainEqual(["title", "My title"]);
});
-it("shows a guest the task with no edit controls", () => {
- const { session } = setup(async () => "", "guest");
+it("shows someone view-only there no edit controls, whatever their list says", () => {
+ // Dana is a member of the task's home in her list, but the relay says she
+ // can only read it.
+ const { session } = setup(async () => "", { [home]: opened(false) });
render(
{}}
onSaved={() => {}}
/>,
);
- for (const name of ["Edit", "Move…"])
+ for (const name of ["Edit", "Move…", "More", "Link this chat", "Unlink"])
expect(screen.queryByRole("button", { name })).toBeNull();
expect(screen.queryByLabelText("Status")).toBeNull();
+ expect(screen.getByText("Read-only access")).toBeInTheDocument();
+});
+
+it("shows neither edit controls nor read-only while the relay is asked", () => {
+ const { session } = setup(async () => "", {});
+ render(
+ {}}
+ onSaved={() => {}}
+ />,
+ );
+ expect(screen.queryByRole("button", { name: "Edit" })).toBeNull();
+ expect(screen.queryByText("Read-only access")).toBeNull();
+});
+
+it("lets someone with access edit where they haven't joined", () => {
+ // Wes reads #launch through its project and may post there; it isn't in
+ // his list as joined.
+ const task = { ...mine, home: launch };
+ const { session } = setup(async () => "", { [launch]: opened(true) });
+ render(
+ {}}
+ onSaved={() => {}}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "Edit" })).toBeInTheDocument();
+ expect(screen.getByLabelText("Status")).toBeInTheDocument();
+});
+
+it("names projects and channels by one rule", async () => {
+ const { session } = setup(async () => "");
+ render(
+ {}}
+ onSaved={() => {}}
+ />,
+ );
+ expect(await screen.findByText("Payments · #design")).toBeInTheDocument();
});
-it("creates a new task in the place it started, posting nothing", async () => {
+it("creates a new task where the relay says the viewer can post, posting nothing", async () => {
const { session, signed } = setup(async () => "");
const onSaved = vi.fn();
render(
@@ -139,3 +243,27 @@ it("creates a new task in the place it started, posting nothing", async () => {
expect(signed[0]?.tags).toContainEqual(["h", home]);
expect(signed[0]?.tags).toContainEqual(["op", "create"]);
});
+
+it("won't create a task where the relay says the viewer can't post", async () => {
+ const { session, signed } = setup(async () => "", {
+ [launch]: opened(false),
+ });
+ render(
+ {}}
+ onSaved={() => {}}
+ />,
+ );
+ fireEvent.change(screen.getByLabelText("Title"), {
+ target: { value: "Nope" },
+ });
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "You can’t post in #launch",
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Create task" }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(signed).toHaveLength(0);
+});
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index 8557332417..8215eab8c7 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -31,6 +31,12 @@ import { AvatarStack } from "../../shared/design-system/ui/AvatarStack";
import { Button } from "../../shared/design-system/ui/Button";
import { TaskComments, type TaskCommentsProps } from "./TaskComments";
import { Combobox } from "../../shared/design-system/ui/Combobox";
+import {
+ MenuItem,
+ MenuPopup,
+ MenuRoot,
+ MenuTrigger,
+} from "../../shared/design-system/ui/Menu";
import { Field } from "../../shared/design-system/ui/Field";
import { InlineHeader } from "../../shared/design-system/ui/Header";
import { IconButton } from "../../shared/design-system/ui/IconButton";
@@ -51,8 +57,14 @@ import {
type TaskImage,
type TaskStatus,
} from "./model";
-import { accessChange, type Place, projectOf } from "./places";
-import { useCanEdit, usePlaces, useTaskHomes } from "./react";
+import {
+ accessChange,
+ type Place,
+ placeLabel,
+ projectOf,
+ readReaders,
+} from "./places";
+import { usePlaceAccess, usePlaces, useTaskPlaces } from "./react";
import { saveTask, type SaveTarget } from "./store";
import { StatusIcon } from "./StatusIcon";
import styles from "./Tasks.module.css";
@@ -140,7 +152,9 @@ function TaskDetails({
comments,
}: TaskViewProps & { task: Task; edit(): void }) {
const notify = useToastNotification();
- const canEdit = useCanEdit(session, task.home);
+ // The relay's answer for the task's home decides every edit control.
+ const { access } = usePlaceAccess(session, task.home);
+ const canEdit = access === "edit";
const [saving, setSaving] = useState(false);
const [moving, setMoving] = useState(false);
const places = usePlaces(session, [task.home]);
@@ -187,9 +201,9 @@ function TaskDetails({
{project.id && project.id !== task.home
- ? `${project.name ?? "Private project"}${home ? ` · ${placeLabel(home)}` : ""}`
+ ? `${project.name ?? "Private project"}${home ? ` · ${placeLabel(home, places)}` : ""}`
: home
- ? placeLabel(home)
+ ? placeLabel(home, places)
: ""}
@@ -212,19 +226,39 @@ function TaskDetails({
disabled={saving}
onChange={(assignees) => void change({ assignees })}
/>
-
- Edit
-
- setMoving(true)}>
- Move…
-
+
+
+ Edit
+
+ setMoving(true)}>
+ Move…
+
+
+
+
+
+ More
+
+ }
+ />
+
+ Edit
+ setMoving(true)}>Move…
+
+
+
>
) : (
<>
-
+
{statusLabels[task.status]}
+ {access === "view" ? (
+ Read-only access
+ ) : null}
>
)}
@@ -246,6 +280,7 @@ function TaskDetails({
session={session}
task={task}
currentChat={currentChat}
+ canEdit={canEdit}
openConversation={openConversation}
/>
@@ -340,7 +375,7 @@ function Assignees({
type Person = ReturnType>;
-/** Up to four people, chosen from the people of the task's home. Agents
+/** Up to four people, chosen from the people who can see the task. Agents
* are never offered: a person always answers for the work. */
function AssigneePicker({
session,
@@ -355,11 +390,12 @@ function AssigneePicker({
disabled: boolean;
onChange(assignees: readonly string[]): void;
}) {
- const homes = useTaskHomes(session);
- const members = homes.find((item) => item.id === home)?.members;
+ // Its members and those of the places it is filed under. An open place
+ // has more readers than these; the relay checks every assignee either way.
+ const readers = useReadersOf(session, home);
const pubkeys = useMemo(
- () => [...new Set([...assignees, ...(members ?? [])])],
- [assignees, members],
+ () => [...new Set([...assignees, ...(readers?.people ?? [])])],
+ [assignees, readers],
);
const person = usePeople(session, pubkeys);
const [search, setSearch] = useState("");
@@ -426,13 +462,19 @@ function AssigneePicker({
}
function TaskByline({ session, task }: { session: RelaySession; task: Task }) {
- const person = usePeople(session, [task.author, task.editor]);
+ const person = usePeople(
+ session,
+ [task.creator, task.via, task.editor].flatMap((key) => key ?? []),
+ );
const label = (pubkey: string) =>
pubkey === session.viewer ? "you" : person(pubkey).name;
+ const created = task.creator
+ ? `Created by ${label(task.creator)}${task.via ? ` via ${label(task.via)}` : ""} · `
+ : "";
return (
- Created by {label(task.author)} · Updated{" "}
- {relativeTimestamp(task.updatedAt * 1000)} by {label(task.editor)}
+ {created}Updated {relativeTimestamp(task.updatedAt * 1000)} by{" "}
+ {label(task.editor)}
);
}
@@ -486,11 +528,14 @@ function LinkedConversations({
session,
task,
currentChat,
+ canEdit,
openConversation,
}: {
session: RelaySession;
task: Task;
currentChat: string | undefined;
+ /** Linking and unlinking edit the task, as the relay allows. */
+ canEdit: boolean;
openConversation(channelId: string): void;
}) {
const notify = useToastNotification();
@@ -537,14 +582,16 @@ function LinkedConversations({
channelId={link.conversation}
open={() => openConversation(link.conversation)}
/>
- }
- disabled={busy}
- onClick={() => void toggle(link.conversation, false)}
- />
+ {canEdit ? (
+ }
+ disabled={busy}
+ onClick={() => void toggle(link.conversation, false)}
+ />
+ ) : null}
))}
@@ -553,7 +600,7 @@ function LinkedConversations({
{links ? "No conversations you can see are linked." : "Loading…"}
)}
- {currentChat && links && !linkedHere ? (
+ {canEdit && currentChat && links && !linkedHere ? (
,
except?: string,
): readonly SelectGroup[] {
const options = (kind: "chat" | "channel") =>
homes
.filter((item) => item.id !== except)
.filter((item) => (item.channelType === "solo") === (kind === "chat"))
- .map((item) => ({ value: item.id, label: item.name || "Untitled" }))
- .sort((a, b) => a.label.localeCompare(b.label));
+ .map((item) => ({
+ value: item.id,
+ label: placeLabel(
+ { id: item.id, name: item.name || "Untitled", kind },
+ places,
+ ),
+ }));
return [
{ label: "Channels", options: options("channel") },
{ label: "Chats", separator: true, options: options("chat") },
].filter((group) => group.options.length);
}
-const placeLabel = (place: Place) =>
- place.kind === "chat" ? place.name : `#${place.name}`;
-const placeList = (list: readonly Place[]) => list.map(placeLabel).join(", ");
+/** The places a picker offers, named and with their projects known. */
+function useHomeChoices(session: RelaySession, except?: string) {
+ const homes = useTaskPlaces(session);
+ const places = usePlaces(
+ session,
+ homes.map((item) => item.id),
+ );
+ const groups = useMemo(
+ () => homeGroups(homes, places, except),
+ [homes, places, except],
+ );
+ return { groups, places };
+}
+
+/** Why the viewer can't put a task in `place` yet, from the relay's answer;
+ * undefined once they can. */
+function placeProblem(access: string, label: string): string | undefined {
+ switch (access) {
+ case "edit":
+ return undefined;
+ case "loading":
+ return "";
+ case "failed":
+ return `Couldn’t check whether you can post in ${label}. Try again.`;
+ default:
+ return `You can’t post in ${label}, so a task can’t live there.`;
+ }
+}
/** Moving one task: choose where, then confirm whose access changes, by
- * place. The task's comments go with it. */
+ * place. An assignee who can't see the new place is named, the one time a
+ * person is, and moving unassigns them. The task's comments go with it. */
function MoveTask({
session,
task,
@@ -633,23 +713,37 @@ function MoveTask({
onClose(): void;
onMoved(task: Task): void;
}) {
- const homes = useTaskHomes(session);
- const groups = homeGroups(homes, task.home);
+ const choices = useHomeChoices(session, task.home);
const [to, setTo] = useState();
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
+ const target = usePlaceAccess(session, to);
const places = usePlaces(session, to ? [task.home, to] : [task.home]);
- const change = to ? accessChange(task.home, to, places) : undefined;
+ const named = new Map([...choices.places, ...places]);
+ const change = to ? accessChange(task.home, to, named) : undefined;
+ const destination = to && named.get(to);
+ const label = destination ? placeLabel(destination, named) : "that place";
+ const readers = useReadersOf(session, to);
+ const person = usePeople(session, task.assignees);
+ const dropped =
+ readers && !readers.anyone
+ ? task.assignees.filter((pubkey) => !readers.people.has(pubkey))
+ : [];
+ const problem = to ? placeProblem(target.access, label) : "";
+ const ready = !!to && problem === undefined && !!readers;
const move = async () => {
- if (!to) return;
+ if (!to || !ready) return;
setPending(true);
setError("");
try {
- const result = await saveTask(session, fieldsOf(task), {
- op: "move",
- base: task,
- home: to,
- });
+ const result = await saveTask(
+ session,
+ {
+ ...fieldsOf(task),
+ assignees: task.assignees.filter((key) => !dropped.includes(key)),
+ },
+ { op: "move", base: task, home: to },
+ );
if (result.status === "saved") onMoved(result.task);
else setError("Someone else changed this task. Close and try again.");
} catch (reason) {
@@ -672,7 +766,7 @@ function MoveTask({
void move()}
>
Move
@@ -680,29 +774,46 @@ function MoveTask({
>
}
>
- {groups.length ? (
+ {choices.groups.length ? (
) : (
- There’s nowhere else you can post in to move this task.
+ There’s nowhere else you can move this task.
)}
- {change?.gain.length ? (
+ {problem ? (
+
+
{problem}
+ {target.access === "failed" ? (
+
+ Try again
+
+ ) : null}
+
+ ) : null}
+ {problem === undefined && change?.gain.length ? (
- Everyone in {placeList(change.gain)} will be able to see this task and
- its comments.
+ Everyone in {placeList(change.gain, named)} will be able to see this
+ task and its comments.
) : null}
- {change?.lose.length ? (
+ {problem === undefined && change?.lose.length ? (
- People who are only in {placeList(change.lose)} will lose access.
+ People who are only in {placeList(change.lose, named)} will lose
+ access.
+
+ ) : null}
+ {problem === undefined && dropped.length ? (
+
+ {listNames(dropped.map((key) => person(key).name))} can’t see{" "}
+ {label} and will be unassigned.
) : null}
{error ? (
@@ -714,6 +825,31 @@ function MoveTask({
);
}
+const placeList = (
+ list: readonly Place[],
+ places: ReadonlyMap,
+) => listNames(list.map((place) => placeLabel(place, places)));
+
+const listNames = (names: readonly string[]) =>
+ new Intl.ListFormat("en", { type: "conjunction" }).format(names);
+
+/** Who can see what lives in `home`; undefined until read, or with no home. */
+function useReadersOf(session: RelaySession, home: string | undefined) {
+ const [readers, setReaders] =
+ useState>>();
+ useEffect(() => {
+ setReaders(undefined);
+ if (!home) return;
+ const controller = new AbortController();
+ readReaders(session, home, controller.signal).then(
+ (read) => !controller.signal.aborted && setReaders(read),
+ () => {},
+ );
+ return () => controller.abort();
+ }, [session, home]);
+ return readers;
+}
+
function TaskEditor({
session,
task,
@@ -724,7 +860,7 @@ function TaskEditor({
onDone,
}: TaskViewProps & { onDone(saved: boolean): void }) {
const inputId = useId();
- const homes = useTaskHomes(session);
+ const choices = useHomeChoices(session);
const [draft, setDraft] = useState(
kept?.fields ?? (task ? fieldsOf(task) : empty),
);
@@ -743,25 +879,34 @@ function TaskEditor({
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const files = useRef(null);
- const groups = useMemo(() => homeGroups(homes), [homes]);
- // Only a place the viewer can post in can take a new task.
- const where = homes.some((item) => item.id === home) ? home : undefined;
+ // Only a place the relay says the viewer can post in takes a new task.
+ const target = usePlaceAccess(session, task ? undefined : home);
+ const startPlaces = usePlaces(session, home ? [home] : []);
+ const chosen = home ? startPlaces.get(home) : undefined;
+ const problem =
+ !task && home
+ ? placeProblem(
+ target.access,
+ chosen ? placeLabel(chosen, startPlaces) : "that place",
+ )
+ : undefined;
+ const where = problem === undefined ? home : undefined;
const update = (next: Partial) =>
setDraft((current) => ({ ...current, ...next }));
const submit = async () => {
- const target: SaveTarget | undefined = base
+ const save: SaveTarget | undefined = base
? { op: "update", base }
: where
? { op: "create", home: where, id: taskId }
: undefined;
- if (!target) {
- setError("Choose where this task lives.");
+ if (!save) {
+ setError(problem || "Choose where this task lives.");
return;
}
setError("");
setSaving(true);
try {
- const result = await saveTask(session, draft, target);
+ const result = await saveTask(session, draft, save);
if (result.status === "saved") {
onSaved(result.task);
onDone(true);
@@ -857,12 +1002,22 @@ function TaskEditor({
label="Where it lives"
variant="field"
description="People who can see this place can see the task."
- value={where ?? ""}
+ value={home ?? ""}
placeholder="Choose a place"
- groups={groups}
+ groups={choices.groups}
onValueChange={setHome}
/>
)}
+ {problem ? (
+
+
{problem}
+ {target.access === "failed" ? (
+
+ Try again
+
+ ) : null}
+
+ ) : null}
{state.status === "loading" ? null : shown.length ? (
- shown.map((group) => (
-
-
-
- {group.tasks.map((item) => (
-
- }
- label={item.title || "Untitled task"}
- selected={item.id === selected}
- onClick={() => setSelected(item.id)}
- />
-
- ))}
-
-
- ))
+
+ {shown.map((group) => (
+
+
+
+ {group.tasks.map((item) => (
+
+ }
+ label={item.title || "Untitled task"}
+ selected={item.id === selected}
+ onClick={() => setSelected(item.id)}
+ />
+
+ ))}
+
+
+ ))}
+
) : (
}
diff --git a/src/bundled/tasks/conversation.test.ts b/src/bundled/tasks/conversation.test.ts
index 62e18c699a..edc36cdfca 100644
--- a/src/bundled/tasks/conversation.test.ts
+++ b/src/bundled/tasks/conversation.test.ts
@@ -1,85 +1,34 @@
import { expect, it, vi } from "vitest";
-import type { ChannelReachState } from "../../features/relay/channel-reach";
-import type { RelaySession } from "../../features/relay/session";
-import { postComment } from "./conversation";
+import { artifactConversationId } from "../../features/relay/artifact-conversation";
+import { postAgentComment } from "./conversation";
import type { Task } from "./model";
-const conversation = "33333333-3333-8333-8333-333333333333";
const task = { id: "11111111-1111-4111-8111-111111111111" } as Task;
-/** A session whose relay answers `state` and settles each send as `delivery`. */
-function setup(state: ChannelReachState, delivery: "accepted" | "failed") {
- const listeners = new Set<() => void>();
- let items: { event: { id: string }; delivery: string }[] = [];
- const release = vi.fn();
- const send = vi.fn((_id: string, _text: string) => {
- items = [{ event: { id: "m1" }, delivery: "sending" }];
- queueMicrotask(() => {
- items = [{ event: { id: "m1" }, delivery }];
- for (const listener of listeners) listener();
- });
- return "m1";
- });
- const session = {
- artifacts: { openConversation: vi.fn(async () => conversation) },
- channels: {
- reach: () => ({
- snapshot: () => state,
- subscribe: () => () => {},
- retry() {},
- release,
- }),
- },
- messages: { send },
- outbox: {
- snapshot: () => items,
- subscribe(listener: () => void) {
- listeners.add(listener);
- return () => listeners.delete(listener);
- },
+it("opens the task's conversation and posts there as the agent", async () => {
+ const publish = vi.fn(async (event: object) => ({ ...event }) as never);
+ await postAgentComment({ publish }, task, "Merged in #12");
+ const conversation = await artifactConversationId(task.id);
+ expect(publish.mock.calls.map(([event]) => event)).toEqual([
+ {
+ kind: 9007,
+ created_at: expect.any(Number),
+ content: "",
+ tags: [
+ ["h", conversation],
+ ["artifact", task.id],
+ ],
},
- } as unknown as RelaySession;
- return { session, send, release };
-}
-const signal = () => new AbortController().signal;
-
-it("opens the task's conversation and waits for the relay to accept the comment", async () => {
- const t = setup({ status: "open", post: true, joined: false }, "accepted");
- await postComment(t.session, task, "Shipped.", signal());
- expect(t.session.artifacts.openConversation).toHaveBeenCalledWith(
- task.id,
- expect.anything(),
- );
- expect(t.send).toHaveBeenCalledWith(conversation, "Shipped.");
- expect(t.release).toHaveBeenCalled();
-});
-
-it("never sends where the relay says the person can only read", async () => {
- const t = setup({ status: "open", post: false, joined: false }, "accepted");
- await expect(postComment(t.session, task, "Hi", signal())).rejects.toThrow(
- "only read",
- );
- expect(t.send).not.toHaveBeenCalled();
- expect(t.release).toHaveBeenCalled();
+ { kind: 9, content: "Merged in #12", tags: [["h", conversation]] },
+ ]);
});
-it("tells apart couldn't-check from no access", async () => {
- for (const [reason, message] of [
- ["failed", "Try again"],
- ["unavailable", "aren’t available to you"],
- ] as const) {
- const t = setup({ status: "unavailable", reason }, "accepted");
- await expect(postComment(t.session, task, "Hi", signal())).rejects.toThrow(
- message,
- );
- expect(t.send).not.toHaveBeenCalled();
- }
-});
-
-it("reports a comment the relay refused", async () => {
- const t = setup({ status: "open", post: true, joined: false }, "failed");
- await expect(postComment(t.session, task, "Hi", signal())).rejects.toThrow(
- "didn’t post",
+it("says plainly when the relay refuses the agent", async () => {
+ const publish = vi.fn(async () => {
+ throw new Error("restricted: not a member");
+ });
+ await expect(postAgentComment({ publish }, task, "Done")).rejects.toThrow(
+ "You can’t comment on this task: restricted: not a member",
);
- expect(t.release).toHaveBeenCalled();
+ expect(publish).toHaveBeenCalledTimes(1);
});
diff --git a/src/bundled/tasks/conversation.ts b/src/bundled/tasks/conversation.ts
index 709c6cbcdf..cc9000d74c 100644
--- a/src/bundled/tasks/conversation.ts
+++ b/src/bundled/tasks/conversation.ts
@@ -1,98 +1,30 @@
-// A task's comments live in its own hidden conversation (NIP-AR): the relay
-// makes it on the first comment, under the task's home, and who reads and
-// posts there always comes from the home. The app holds it open by name with
-// `channels.reach`, since it is never in the viewer's list.
-import type {
- ChannelReach,
- ChannelReachState,
-} from "../../features/relay/channel-reach";
-import type { RelaySession } from "../../features/relay/session";
+// A task's comments live in its own hidden conversation (NIP-AR), under the
+// task's home: who reads and posts there always comes from the home. An
+// agent comments as itself, so the relay checks the agent's access.
+import type { BuzzClient } from "../../buzz-mcp/client";
+import { conversationOpening } from "../../features/relay/artifact-conversation";
import type { Task } from "./model";
-/** The first answer that is not `loading`. */
-export function settled(
- handle: ChannelReach,
- signal: AbortSignal,
-): Promise {
- return new Promise((resolve, reject) => {
- const check = () => {
- const state = handle.snapshot();
- if (state.status === "loading") return;
- stop();
- resolve(state);
- };
- const abort = () => {
- stop();
- reject(signal.reason);
- };
- const unsubscribe = handle.subscribe(check);
- const stop = () => {
- unsubscribe();
- signal.removeEventListener("abort", abort);
- };
- signal.addEventListener("abort", abort, { once: true });
- if (signal.aborted) abort();
- else check();
- });
-}
-
-/** Resolves once the relay accepts message `id`; rejects if it fails. */
-function delivered(session: RelaySession, id: string, signal: AbortSignal) {
- const outbox = session.outbox;
- if (!outbox) return Promise.reject(new Error("Couldn’t post the comment."));
- return new Promise((resolve, reject) => {
- let seen = false;
- const check = () => {
- const item = outbox.snapshot().find((entry) => entry.event.id === id);
- if (item) seen = true;
- const delivery = item?.delivery;
- if (delivery === "sending" || delivery === "unknown") return;
- if (!item && !seen) return;
- stop();
- if (delivery === "failed")
- reject(new Error("The comment didn’t post. Try again."));
- else resolve();
- };
- const abort = () => {
- stop();
- reject(signal.reason);
- };
- const unsubscribe = outbox.subscribe(check);
- const stop = () => {
- unsubscribe();
- signal.removeEventListener("abort", abort);
- };
- signal.addEventListener("abort", abort, { once: true });
- if (signal.aborted) abort();
- else check();
- });
-}
-
-/** Opens `task`'s conversation if nobody has, then posts `text` there and
- * waits for the relay to accept it. */
-export async function postComment(
- session: RelaySession,
+/** Posts `text` on `task` as the agent `client` speaks for, opening the
+ * conversation if nobody has: a comment is the agent's own words, so the
+ * relay checks the agent's access, not its owner's. */
+export async function postAgentComment(
+ client: Pick,
task: Task,
text: string,
- signal: AbortSignal,
): Promise {
- const open = session.artifacts.openConversation;
- const reach = session.channels.reach;
- if (!open || !reach)
- throw new Error("Comments aren’t available in this community yet.");
- const id = await open(task.id, signal);
- const handle = reach(id);
+ const opening = await conversationOpening(task.id);
+ const id = opening.tags[0]?.[1];
+ const refused = (reason: unknown) =>
+ new Error(
+ `You can’t comment on this task: ${
+ reason instanceof Error ? reason.message : "the community refused it"
+ }`,
+ );
try {
- const state = await settled(handle, signal);
- if (state.status !== "open")
- throw new Error(
- state.status === "unavailable" && state.reason === "failed"
- ? "Couldn’t reach the community to comment. Try again."
- : "This task’s comments aren’t available to you.",
- );
- if (!state.post) throw new Error("You can only read this task’s comments.");
- await delivered(session, session.messages.send(id, text), signal);
- } finally {
- handle.release();
+ await client.publish(opening);
+ await client.publish({ kind: 9, content: text, tags: [["h", id ?? ""]] });
+ } catch (reason) {
+ throw refused(reason);
}
}
diff --git a/src/bundled/tasks/model.test.ts b/src/bundled/tasks/model.test.ts
index add36bdc1d..bfeff6e52a 100644
--- a/src/bundled/tasks/model.test.ts
+++ b/src/bundled/tasks/model.test.ts
@@ -6,6 +6,7 @@ import {
TASK_TYPE,
taskContent,
taskOf,
+ taskTags,
} from "./model";
const author = "a".repeat(64);
@@ -34,16 +35,23 @@ const revision = (content: unknown, tags: string[][] = []) => ({
it("reads a revision as the task it snapshots, in its home", () => {
const task = taskOf(
- revision({
- version: 2,
- author,
- description: "It clips.",
- status: "in_progress",
- images: [
- { url: "https://example.org/a.png", type: "image/png", dim: "10x20" },
+ revision(
+ {
+ version: 3,
+ description: "It clips.",
+ images: [
+ { url: "https://example.org/a.png", type: "image/png", dim: "10x20" },
+ ],
+ },
+ [
+ ["status", "in_progress"],
+ ["assignee", author],
+ ["assignee", author],
+ ["assignee", third],
+ ["creator", author],
+ ["via", third],
],
- assignees: [author, author, third],
- }),
+ ),
);
expect(task).toEqual({
id,
@@ -55,35 +63,56 @@ it("reads a revision as the task it snapshots, in its home", () => {
{ url: "https://example.org/a.png", type: "image/png", dim: "10x20" },
],
assignees: [author, third],
- author,
+ creator: author,
+ via: third,
revision: "e".repeat(64),
editor,
updatedAt: 10,
});
});
+it("trusts only tags for what the relay checks, never content", () => {
+ // An app could write a creator, status or assignees into content; none of
+ // it counts.
+ const task = taskOf(
+ revision(
+ {
+ author: third,
+ creator: third,
+ status: "done",
+ assignees: [third],
+ },
+ [],
+ ),
+ );
+ expect(task?.creator).toBeUndefined();
+ expect(task?.status).toBe("todo");
+ expect(task?.assignees).toEqual([]);
+});
+
it("drops what an untrusted record can't safely show", () => {
const task = taskOf(
- revision({
- author: "not a key",
- status: "deleted",
- images: [
- { url: "http://example.org/a.png" },
- { url: "javascript:alert(1)" },
- { url: "https://example.org/b.png", type: "text/html", dim: "big" },
- ],
- assignees: [
- "someone",
- 7,
- "d".repeat(64),
- "1".repeat(64),
- "2".repeat(64),
- "3".repeat(64),
- "4".repeat(64),
+ revision(
+ {
+ images: [
+ { url: "http://example.org/a.png" },
+ { url: "javascript:alert(1)" },
+ { url: "https://example.org/b.png", type: "text/html", dim: "big" },
+ ],
+ },
+ [
+ ["status", "deleted"],
+ ["creator", "not a key"],
+ ["via", "nobody"],
+ ...["someone", "d".repeat(64), "1".repeat(64), "2".repeat(64)].map(
+ (key) => ["assignee", key],
+ ),
+ ...["3", "4"].map((n) => ["assignee", n.repeat(64)]),
],
- }),
+ ),
);
- expect(task?.author).toBe(editor);
+ expect(task?.creator).toBeUndefined();
+ expect(task?.via).toBeUndefined();
expect(task?.status).toBe("todo");
expect(task?.images).toEqual([{ url: "https://example.org/b.png" }]);
expect(task?.assignees).toEqual([
@@ -145,18 +174,19 @@ it("checks fields before saving, with reasons people can act on", () => {
assignees: ["1", "2", "3", "4", "5"].map((n) => n.repeat(64)),
}),
).toThrow("up to 4");
- expect(JSON.parse(taskContent(checkedFields(fields), author))).toEqual({
- version: 2,
- author,
+ expect(JSON.parse(taskContent(checkedFields(fields)))).toEqual({
+ version: 3,
description: "",
- status: "todo",
images: [],
- assignees: [author],
});
+ expect(taskTags(checkedFields(fields))).toEqual([
+ ["status", "todo"],
+ ["assignee", author],
+ ]);
});
it("counts a task as mine when I made it or I'm assigned", () => {
- const task = taskOf(revision({ author: editor })) as Task;
+ const task = taskOf(revision({}, [["creator", editor]])) as Task;
expect(isMine(task, editor)).toBe(true);
expect(isMine(task, author)).toBe(false);
expect(isMine({ ...task, assignees: [author] }, author)).toBe(true);
diff --git a/src/bundled/tasks/model.ts b/src/bundled/tasks/model.ts
index 6b7f7bb73e..20234dfb4b 100644
--- a/src/bundled/tasks/model.ts
+++ b/src/bundled/tasks/model.ts
@@ -1,13 +1,14 @@
// A task is one NIP-AR artifact (kind 45010) of type `buzz.task`. Its `h` is
// its home, a project, channel or chat, and the relay lets read it whoever
-// can read that home and edit it whoever can post there. Its content is the
-// complete snapshot; the relay keeps the revision history and refuses an
-// edit whose `prev` is stale.
+// can read that home and edit it whoever can post there. Each revision is
+// the complete snapshot: what the relay filters on and checks in tags
+// (`status`, one `assignee` per person, `creator`), the rest in content. The
+// relay keeps the revision history and refuses an edit whose `prev` is stale.
import { ARTIFACT_KIND } from "../../features/agents/agent-config-artifacts";
import type { EventData } from "../../features/relay/events";
export const TASK_TYPE = "buzz.task";
-const CONTENT_VERSION = 2;
+const CONTENT_VERSION = 3;
export const statuses = ["todo", "in_progress", "done", "cancelled"] as const;
export type TaskStatus = (typeof statuses)[number];
@@ -42,8 +43,12 @@ export type Task = TaskFields &
id: string;
/** The artifact's `h`: the project, channel or chat it lives in. */
home: string;
- /** Who created it, as its creator's client recorded. */
- author: string;
+ /** Who signed its first revision, as its `creator` tag carries forward
+ * (the relay checks it); undefined when a revision lacks one. */
+ creator: string | undefined;
+ /** The agent that made it for its creator, as that agent's tool noted.
+ * A label only: the creator answers for it. */
+ via: string | undefined;
/** The current revision: its id is the next edit's `prev`. */
revision: string;
/** Who signed the current revision, and when. */
@@ -61,6 +66,9 @@ const CHANNEL =
const tag = (event: EventData, name: string) =>
event.tags.find((entry) => entry[0] === name)?.[1];
+const tags = (event: EventData, name: string) =>
+ event.tags.flatMap((entry) => (entry[0] === name ? [entry[1]] : []));
+
const text = (value: unknown) => (typeof value === "string" ? value : "");
export const isChannelId = (value: unknown): value is string =>
@@ -104,24 +112,23 @@ export function taskOf(event: EventData & { id: string }): Task | undefined {
} catch {
return undefined;
}
- const author = text(content.author);
+ const creator = tag(event, "creator");
+ const via = tag(event, "via");
return {
id,
home,
title: (tag(event, "title") ?? "").slice(0, MAX_TITLE),
description: text(content.description),
- status: statuses.find((item) => item === content.status) ?? "todo",
+ status: statuses.find((item) => item === tag(event, "status")) ?? "todo",
images: (Array.isArray(content.images) ? content.images : [])
.flatMap((item) => imageOf(item) ?? [])
.slice(0, MAX_IMAGES),
- assignees: [
- ...new Set(
- (Array.isArray(content.assignees) ? content.assignees : []).filter(
- isPubkey,
- ),
- ),
- ].slice(0, MAX_ASSIGNEES),
- author: isPubkey(author) ? author : event.pubkey,
+ assignees: [...new Set(tags(event, "assignee").filter(isPubkey))].slice(
+ 0,
+ MAX_ASSIGNEES,
+ ),
+ creator: isPubkey(creator) ? creator : undefined,
+ via: isPubkey(via) ? via : undefined,
revision: event.id,
editor: event.pubkey,
updatedAt: event.created_at,
@@ -149,22 +156,25 @@ export function checkedFields(fields: TaskFields): TaskFields {
};
}
-/** The revision's content: the complete snapshot, author preserved. */
-export const taskContent = (fields: TaskFields, author: string) =>
+/** The revision's content: what no relay rule reads. */
+export const taskContent = (fields: TaskFields) =>
JSON.stringify({
version: CONTENT_VERSION,
- author,
description: fields.description,
- status: fields.status,
images: fields.images,
- assignees: fields.assignees,
});
+/** The revision's tags the relay filters on and checks. */
+export const taskTags = (fields: TaskFields) => [
+ ["status", fields.status],
+ ...fields.assignees.map((pubkey) => ["assignee", pubkey]),
+];
+
/** Newest activity first, then by id, so equal times keep one order. */
export const byRecent = (a: Task, b: Task) =>
b.updatedAt - a.updatedAt || a.id.localeCompare(b.id);
-/** Assigned to the viewer, or created by them. Created by their agent counts
- * through the author the agent's tools record: the owner. */
+/** Assigned to the viewer, or created by them. What their agent creates is
+ * theirs too: the agent's tools sign as its owner. */
export const isMine = (task: Task, viewer: string) =>
- task.author === viewer || task.assignees.includes(viewer);
+ task.creator === viewer || task.assignees.includes(viewer);
diff --git a/src/bundled/tasks/places.ts b/src/bundled/tasks/places.ts
index 8e4d9569a1..476f2d181a 100644
--- a/src/bundled/tasks/places.ts
+++ b/src/bundled/tasks/places.ts
@@ -8,7 +8,8 @@ import { metadataName } from "../../features/relay/discovery";
import { tag, type RelayEvent } from "../../features/relay/events";
import type { RelaySession } from "../../features/relay/session";
import { soloLabels } from "../../features/solo/labels";
-import { isChannelId, type Task } from "./model";
+import { channelVisibility } from "../../features/relay/channel-details-protocol";
+import { isChannelId, isPubkey, type Task } from "./model";
export type Place = Readonly<{
id: string;
@@ -16,6 +17,8 @@ export type Place = Readonly<{
kind: "chat" | "channel";
/** The channel it is filed under (NIP-29 `parent`), if any. */
parent?: string | undefined;
+ /** Open to everyone in the community. */
+ open?: true | undefined;
}>;
/** A project as the Tasks page groups by it. `name` is undefined for a
@@ -36,12 +39,55 @@ function placeOf(event: RelayEvent): Place | undefined {
name: metadataName(event) ?? id.slice(0, 8),
kind: soloLabels(channelIdentity(event).labels) ? "chat" : "channel",
...(isChannelId(parent) ? { parent } : {}),
+ ...(channelVisibility(event) === "public" ? { open: true as const } : {}),
};
}
+/** A place other places are filed under. */
+export const isProject = (id: string, places: ReadonlyMap) =>
+ [...places.values()].some((place) => place.parent === id);
+
+/** One name for a place everywhere: a project as "Buzz", a chat by its
+ * name, any other channel as "#random". */
+export function placeLabel(
+ place: Pick,
+ places: ReadonlyMap,
+) {
+ return place.kind === "chat" || isProject(place.id, places)
+ ? place.name
+ : `#${place.name}`;
+}
+
+/** Who can see what lives in `home`: anyone, when it or a place it is filed
+ * under is open; otherwise the members of those places, from their
+ * relay-signed rosters. The relay refuses an assignee who can't. */
+export async function readReaders(
+ session: Pick,
+ home: string,
+ signal: AbortSignal,
+): Promise }>> {
+ const read = session.snapshotRead;
+ const author = session.relayAuthor;
+ if (!read || !author) return { anyone: false, people: new Set() };
+ const places = await readPlaces(session, [home], signal);
+ const chain = chainOf(home, places);
+ if (chain.some((id) => places.get(id)?.open))
+ return { anyone: true, people: new Set() };
+ const rosters = await read(
+ [{ kinds: [39002], authors: [author], "#d": chain, limit: chain.length }],
+ { signal },
+ );
+ const people = new Set();
+ for (const roster of rosters)
+ if (roster.pubkey === author && chain.includes(tag(roster, "d") ?? ""))
+ for (const [name, value] of roster.tags)
+ if (name === "p" && isPubkey(value)) people.add(value);
+ return { anyone: false, people };
+}
+
/** The places named by `ids`, and the projects they are filed in. */
export async function readPlaces(
- session: RelaySession,
+ session: Pick,
ids: Iterable,
signal: AbortSignal,
): Promise> {
diff --git a/src/bundled/tasks/react.ts b/src/bundled/tasks/react.ts
index e6997669aa..fa3bade9c7 100644
--- a/src/bundled/tasks/react.ts
+++ b/src/bundled/tasks/react.ts
@@ -6,6 +6,10 @@ import {
useSyncExternalStore,
} from "react";
import type { RelaySession } from "../../features/relay/session";
+import type {
+ ChannelReach,
+ ChannelReachState,
+} from "../../features/relay/channel-reach";
import type { ChannelSummary } from "../../features/relay/contracts";
import { useChannelRoster } from "../../features/relay/react";
import type { Task } from "./model";
@@ -102,29 +106,80 @@ export function usePlaces(
return places;
}
-/** Where the viewer can make or move a task: channels and chats in their
- * list they can post in. DMs hold no tasks. */
-export const isTaskHome = (channel: ChannelSummary) =>
+/** Places a task can live in: channels and chats, not DMs, huddles or
+ * archived ones. Whether the viewer may post there is the relay's answer
+ * (`usePlaceAccess`), never this list's. */
+export const isTaskPlace = (channel: ChannelSummary) =>
!channel.archived &&
- !channel.readOnly &&
!channel.pending &&
!channel.huddle &&
- channel.viewerRole !== "guest" &&
- channel.viewerRole !== undefined &&
(channel.channelType === "stream" ||
channel.channelType === "forum" ||
channel.channelType === "solo");
-export function useTaskHomes(session: RelaySession) {
+/** The places the viewer knows of, those this device already knows they can
+ * post in first. */
+export function useTaskPlaces(session: RelaySession) {
const { channels } = useChannelRoster(session.channels);
- return useMemo(() => channels.filter(isTaskHome), [channels]);
+ return useMemo(
+ () =>
+ channels
+ .filter(isTaskPlace)
+ .sort((a, b) => Number(!!a.readOnly) - Number(!!b.readOnly)),
+ [channels],
+ );
+}
+
+/** What the viewer may do with tasks in a place, from the relay's answer:
+ * `edit` where they can post, `view` where they can only read. `loading`
+ * and `failed` show neither edit controls nor a read-only notice yet. */
+export type PlaceAccess = "loading" | "edit" | "view" | "none" | "failed";
+
+const asking: ChannelReachState = Object.freeze({ status: "loading" });
+const quiet = () => () => {};
+
+/** Holds channel `id` open while mounted, and the relay's answer for it. */
+export function useReach(session: RelaySession, id: string | undefined) {
+ const [handle, setHandle] = useState();
+ useEffect(() => {
+ const reach = session.channels.reach;
+ if (!id || !reach) return;
+ const held = reach(id);
+ setHandle(held);
+ return () => {
+ held.release();
+ setHandle(undefined);
+ };
+ }, [session, id]);
+ const read = () => handle?.snapshot() ?? asking;
+ const state = useSyncExternalStore(handle?.subscribe ?? quiet, read, read);
+ return { state, retry: () => handle?.retry() };
}
-/** Whether the viewer may edit tasks in `home`, as far as this device
- * knows: a guest or read-only place is view only. A place the viewer reads
- * through its project isn't in their list; the relay decides there. */
-export function useCanEdit(session: RelaySession, home: string) {
+export const accessOf = (state: ChannelReachState): PlaceAccess =>
+ state.status === "open"
+ ? state.post
+ ? "edit"
+ : "view"
+ : state.status === "unavailable"
+ ? state.reason === "failed"
+ ? "failed"
+ : "none"
+ : "loading";
+
+/** The viewer's access to tasks in `id`. A connection that can't ask the
+ * relay by name falls back to its channel list's posting answer. */
+export function usePlaceAccess(
+ session: RelaySession,
+ id: string | undefined,
+): Readonly<{ access: PlaceAccess; retry(): void }> {
+ const reach = useReach(session, id);
const { channels } = useChannelRoster(session.channels);
- const channel = channels.find((item) => item.id === home);
- return !channel || (!channel.readOnly && channel.viewerRole !== "guest");
+ if (session.channels.reach)
+ return { access: accessOf(reach.state), retry: reach.retry };
+ const listed = channels.find((channel) => channel.id === id);
+ return {
+ access: !listed ? "none" : listed.readOnly ? "view" : "edit",
+ retry: () => {},
+ };
}
diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts
index 58d5e282b7..6e7d4b2594 100644
--- a/src/bundled/tasks/store.ts
+++ b/src/bundled/tasks/store.ts
@@ -13,8 +13,10 @@ import {
TASK_TYPE,
type Task,
type TaskFields,
+ type TaskStatus,
taskContent,
taskOf,
+ taskTags,
} from "./model";
export type TasksState = Readonly<{
@@ -65,7 +67,7 @@ export function watchTasks(session: RelaySession): TasksView {
const controller = new AbortController();
fallback = controller;
readTasks(session, controller.signal)
- .then((tasks) => {
+ .then(({ tasks }) => {
if (!controller.signal.aborted) set({ status: "live", tasks });
})
.catch((reason: unknown) => {
@@ -117,25 +119,54 @@ export function watchTasks(session: RelaySession): TasksView {
};
}
-/** One finite read of every current task the viewer can read. */
+/** What a finite read asks the relay for: each set matches any of its
+ * values, and all of them must match. */
+export type TaskQuery = Readonly<{
+ status?: readonly TaskStatus[] | undefined;
+ /** A person's pubkey, or `null` for tasks nobody has. */
+ assignee?: string | null | undefined;
+ /** A place: its tasks, and for a project everything filed in it. */
+ within?: string | undefined;
+}>;
+
+/** Where task reads come from: a session, or an agent's own reads. */
+export type TaskSource = Pick;
+
+/** One finite read of the current tasks the viewer can read that match
+ * `query`, filtered by the relay. `complete` is false when the read hit its
+ * cap, so more may match. */
export async function readTasks(
- session: RelaySession,
+ session: TaskSource,
signal: AbortSignal,
-): Promise {
+ query: TaskQuery = {},
+): Promise> {
const read = session.snapshotRead;
if (!read) throw new Error("Tasks aren’t available in this community.");
- return toTasks(
- await read([{ artifact: "current", ...taskFilter, limit: READ_LIMIT }], {
- signal,
- }),
+ const events = await read(
+ [
+ {
+ artifact: "current",
+ ...taskFilter,
+ ...(query.status?.length ? { "#status": [...query.status] } : {}),
+ ...(query.assignee
+ ? { "#assignee": [query.assignee] }
+ : query.assignee === null
+ ? { unassigned: true }
+ : {}),
+ ...(query.within ? { within: query.within } : {}),
+ limit: READ_LIMIT,
+ },
+ ],
+ { signal },
);
+ return { tasks: toTasks(events), complete: events.length < READ_LIMIT };
}
/** Task `id`'s current revision, or undefined when the viewer can't read it
* or it was deleted. `home`, when known, names its home, so a task readable
* only by naming its home is found too. */
export async function readTask(
- session: RelaySession,
+ session: TaskSource,
id: string,
signal: AbortSignal,
home?: string,
@@ -168,7 +199,8 @@ export type SaveResult =
/** What a save does: create task `id` in `home`, update `base` where it
* lives, or move `base` to `home` with `fields` as its snapshot. */
export type SaveTarget =
- | Readonly<{ op: "create"; home: string; id: string }>
+ /** `via`: the agent making it for the viewer, shown as a label. */
+ | Readonly<{ op: "create"; home: string; id: string; via?: string }>
| Readonly<{ op: "update"; base: Task }>
| Readonly<{ op: "move"; base: Task; home: string }>;
@@ -188,11 +220,14 @@ export async function saveTask(
const base = target.op === "create" ? undefined : target.base;
const id = base?.id ?? (target.op === "create" ? target.id : "");
const home = target.op === "update" ? target.base.home : target.home;
+ // The signer of the first revision, carried forward as the relay checks.
+ const creator = base ? base.creator : viewer;
+ const via = base ? base.via : target.op === "create" ? target.via : undefined;
const event = await writer.sign(
{
kind: ARTIFACT_KIND,
created_at: Math.floor(Date.now() / 1000),
- content: taskContent(checked, base?.author ?? viewer),
+ content: taskContent(checked),
tags: [
["ar", "1"],
["d", id],
@@ -201,6 +236,9 @@ export async function saveTask(
["title", checked.title],
["op", target.op],
...(base ? [["prev", base.revision]] : []),
+ ...taskTags(checked),
+ ...(creator ? [["creator", creator]] : []),
+ ...(via ? [["via", via]] : []),
],
},
signal,
diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts
index 076acf3721..6995c8952f 100644
--- a/src/bundled/tasks/tools.test.ts
+++ b/src/bundled/tasks/tools.test.ts
@@ -7,44 +7,120 @@ import { addTaskTools } from "./tools";
const viewer = "a".repeat(64);
const agent = "9".repeat(64);
const person = "b".repeat(64);
+const stranger = "8".repeat(64);
+const leo = "7".repeat(64);
+const relay = "e".repeat(64);
const id = "11111111-1111-4111-8111-111111111111";
const chat = "22222222-2222-4222-8222-222222222222";
const home = "33333333-3333-4333-8333-333333333333";
+/** A private channel the owner is in and the agent isn't. */
+const secret = "55555555-5555-4555-8555-555555555555";
+/** A channel Riley isn't in. */
+const lobby = "77777777-7777-4777-8777-777777777777";
+
+type Event = {
+ id: string;
+ pubkey: string;
+ kind: number;
+ content: string;
+ tags: string[][];
+};
+type Filter = Record;
const head = (
revision: string,
- content: object,
- extra: { d?: string; title?: string } = {},
-) => ({
+ tags: string[][] = [],
+ extra: { d?: string; title?: string; home?: string } = {},
+): Event => ({
id: revision,
pubkey: viewer,
- sig: "",
- created_at: 5,
kind: 45010,
- content: JSON.stringify({ version: 2, author: viewer, ...content }),
+ content: JSON.stringify({ version: 3 }),
tags: [
["d", extra.d ?? id],
- ["h", home],
+ ["h", extra.home ?? home],
["type", TASK_TYPE],
["title", extra.title ?? "Fix the header"],
+ ["creator", viewer],
+ ...tags,
],
});
+const place = (d: string, name: string): Event => ({
+ id: d.replace(/-/g, "").padEnd(64, "0"),
+ pubkey: relay,
+ kind: 39000,
+ content: "",
+ tags: [["d", d], ["name", name], ["private"]],
+});
+const roster = (d: string, members: string[]): Event => ({
+ ...place(d, ""),
+ kind: 39002,
+ tags: [["d", d], ...members.map((key) => ["p", key])],
+});
+
+/** Answers `filters` from `events` the way the relay filters them. */
+function answer(events: Event[], filters: Filter[]) {
+ const filter = filters[0] ?? {};
+ return events.filter((event) => {
+ if (!(filter.kinds as number[]).includes(event.kind)) return false;
+ for (const [key, values] of Object.entries(filter))
+ if (
+ key.startsWith("#") &&
+ !event.tags.some(
+ ([name, value]) =>
+ name === key.slice(1) && (values as string[]).includes(value ?? ""),
+ )
+ )
+ return false;
+ if (filter.unassigned && event.tags.some(([name]) => name === "assignee"))
+ return false;
+ if (
+ typeof filter.within === "string" &&
+ !event.tags.some(
+ ([name, value]) => name === "h" && value === filter.within,
+ )
+ )
+ return false;
+ return true;
+ });
+}
+
type Signed = { kind: number; content: string; tags: string[][] };
-function setup(publish: () => Promise, heads: () => object[]) {
+/** The owner can read `heads` and every place; the agent can read every
+ * place but `secret`, and what lives there. */
+function setup(publish: () => Promise, heads: () => Event[]) {
const signed: Signed[] = [];
+ const posted: Signed[] = [];
+ const places = () => [
+ place(home, "design"),
+ place(chat, "random"),
+ place(secret, "payroll"),
+ place(lobby, "lobby"),
+ roster(lobby, [viewer, leo]),
+ roster(home, [viewer, person]),
+ roster(chat, [viewer, person]),
+ roster(secret, [viewer]),
+ ];
+ const visible = (event: Event) =>
+ !event.tags.some(
+ ([name, value]) => (name === "h" || name === "d") && value === secret,
+ );
const session = {
viewer,
+ relayAuthor: relay,
profiles: {
+ ensure: async () => {},
snapshot: () =>
new Map([
[agent, { name: "Fizz", isAgent: true }],
[person, { name: "Riley" }],
+ [leo, { name: "Leo" }],
]),
},
- snapshotRead: vi.fn(async (filters: { kinds?: number[] }[]) =>
- filters[0]?.kinds?.includes(45010) ? heads() : [],
+ snapshotRead: vi.fn(async (filters: Filter[]) =>
+ answer([...heads(), ...places()], filters),
),
configArtifactWriter: {
sign: vi.fn(async (template: Signed) => {
@@ -59,6 +135,20 @@ function setup(publish: () => Promise, heads: () => object[]) {
publish: vi.fn(publish),
},
} as unknown as RelaySession;
+ const client = {
+ key: agent,
+ pubkey: agent,
+ signal: new AbortController().signal,
+ query: vi.fn(async (filters: Filter[]) =>
+ answer([...heads(), ...places()].filter(visible), filters),
+ ),
+ publish: vi.fn(async (event: Signed) => {
+ if (event.tags.some(([name, value]) => name === "h" && !value))
+ throw new Error("no conversation");
+ posted.push(event);
+ return { ...event, id: "1".repeat(64), pubkey: agent };
+ }),
+ };
const tools = new Map<
string,
(args: Record) => Promise
@@ -67,25 +157,23 @@ function setup(publish: () => Promise, heads: () => object[]) {
relay: () => ({ snapshot: () => ({ status: "ready", session }) }) as never,
addTool: (tool) => {
tools.set(tool.name, (args) =>
- tool.call(
- { key: "agent", signal: new AbortController().signal } as never,
- { channel: chat },
- args,
- ),
+ tool.call(client as never, { channel: chat } as never, args),
);
},
});
const call = (name: string, args: Record) => {
const tool = tools.get(name);
if (!tool) throw new Error(`no ${name}`);
- return tool(args);
+ return tool(args) as Promise;
};
- return { call, signed };
+ return { call, signed, posted, client };
}
const artifacts = (signed: Signed[]) =>
signed.filter((event) => event.kind === 45010);
-const typeOf = (event: Signed | undefined) =>
- event?.tags.find((tag) => tag[0] === "type")?.[1];
+const tagOf = (event: Signed | undefined, name: string) =>
+ event?.tags.find((tag) => tag[0] === name)?.[1];
+const assignees = (event: Signed | undefined) =>
+ event?.tags.flatMap(([name, value]) => (name === "assignee" ? [value] : []));
it("offers exactly find, create, update and comment", () => {
const names: string[] = [];
@@ -101,8 +189,8 @@ it("offers exactly find, create, update and comment", () => {
]);
});
-it("creates in the named place and links this chat, posting nothing", async () => {
- const { call, signed } = setup(
+it("creates in the named place as its owner, via the agent, posting nothing", async () => {
+ const { call, signed, posted } = setup(
async () => "",
() => [],
);
@@ -114,20 +202,23 @@ it("creates in the named place and links this chat, posting nothing", async () =
expect(reply).toContain("Created task");
const [task, link] = artifacts(signed);
expect(task?.tags).toContainEqual(["h", home]);
+ expect(task?.tags).toContainEqual(["creator", viewer]);
+ expect(task?.tags).toContainEqual(["via", agent]);
+ expect(task?.tags).toContainEqual(["status", "todo"]);
expect(JSON.parse(task?.content ?? "")).toMatchObject({
images: [{ url: "https://example.org/a.png" }],
- assignees: [],
});
// The link lives with the chat, so only its readers learn of it.
- expect(typeOf(link)).toBe("buzz.task-link");
+ expect(tagOf(link, "type")).toBe("buzz.task-link");
expect(link?.tags).toContainEqual(["h", chat]);
expect(signed.every((event) => event.kind === 45010)).toBe(true);
+ expect(posted).toHaveLength(0);
});
it("returns a clear match instead of creating a duplicate", async () => {
const { call, signed } = setup(
async () => "",
- () => [head("d".repeat(64), { status: "todo" })],
+ () => [head("d".repeat(64), [["status", "todo"]])],
);
const reply = await call("tasks_create", {
title: "Fix the header",
@@ -140,7 +231,7 @@ it("returns a clear match instead of creating a duplicate", async () => {
it("leaves a possible match for the person, then creates when told", async () => {
const { call, signed } = setup(
async () => "",
- () => [head("d".repeat(64), { status: "todo" })],
+ () => [head("d".repeat(64), [["status", "todo"]])],
);
const args = { title: "Fix the header spacing on mobile", place: home };
expect(await call("tasks_create", args)).toContain("Not created yet");
@@ -149,70 +240,216 @@ it("leaves a possible match for the person, then creates when told", async () =>
expect(artifacts(signed)).toHaveLength(1);
});
-it("finds what's mine and what nobody has taken", async () => {
+it("asks the relay for what's mine and what nobody has taken", async () => {
const other = "44444444-4444-4444-8444-444444444444";
- const { call } = setup(
+ const { call, client } = setup(
async () => "",
() => [
- head("d".repeat(64), { assignees: [viewer] }),
- head("c".repeat(64), {}, { d: other, title: "Nobody's" }),
+ head("d".repeat(64), [
+ ["status", "todo"],
+ ["assignee", viewer],
+ ]),
+ head("c".repeat(64), [["status", "in_progress"]], {
+ d: other,
+ title: "Nobody's",
+ }),
],
);
const mine = await call("tasks_find", { assignee: "me" });
expect(mine).toContain(id);
expect(mine).not.toContain(other);
+ expect(client.query).toHaveBeenLastCalledWith([
+ expect.objectContaining({
+ "#assignee": [viewer],
+ "#status": ["todo", "in_progress"],
+ }),
+ ]);
const nobody = await call("tasks_find", { assignee: "nobody" });
expect(nobody).toContain(other);
expect(nobody).not.toContain(id);
+ expect(client.query).toHaveBeenLastCalledWith([
+ expect.objectContaining({ unassigned: true }),
+ ]);
});
-it("needs evidence to close a task, and assigns whoever starts it", async () => {
- const { call, signed } = setup(
+it("says when a read may have missed tasks", async () => {
+ const many = Array.from({ length: 500 }, (_, at) =>
+ head(`${at}`.padStart(64, "0"), [["status", "todo"]], {
+ d: `11111111-1111-4111-8111-${`${at}`.padStart(12, "0")}`,
+ }),
+ );
+ const { call } = setup(
async () => "",
- () => [head("d".repeat(64), { status: "todo" })],
+ () => many,
+ );
+ expect(await call("tasks_find", {})).toContain("may not be all of them");
+});
+
+it("comments the evidence as the agent before the task closes", async () => {
+ const { call, signed, posted } = setup(
+ async () => "",
+ () => [head("d".repeat(64), [["status", "todo"]])],
);
await expect(call("tasks_update", { id, status: "done" })).rejects.toThrow(
"needs evidence",
);
expect(signed).toHaveLength(0);
+ await call("tasks_update", { id, status: "done", evidence: "Merged #12" });
+ expect(posted.map((event) => event.kind)).toEqual([9007, 9]);
+ expect(posted[1]?.content).toBe("Done: Merged #12");
+ expect(tagOf(signed[0], "status")).toBe("done");
+});
+
+it("leaves the task open when the evidence comment fails", async () => {
+ const { call, signed, client } = setup(
+ async () => "",
+ () => [head("d".repeat(64), [["status", "todo"]])],
+ );
+ client.publish.mockRejectedValueOnce(new Error("restricted: read-only"));
+ await expect(
+ call("tasks_update", { id, status: "cancelled", evidence: "Duplicate" }),
+ ).rejects.toThrow("You can’t comment on this task: restricted: read-only");
+ expect(signed).toHaveLength(0);
+});
+
+it("says plainly when the owner may not save, and tries nothing else", async () => {
+ const { call, signed, client } = setup(
+ async () => {
+ throw new PublishRejected("rejected", "restricted: read-only");
+ },
+ () => [head("d".repeat(64), [["status", "todo"]])],
+ );
+ await expect(call("tasks_update", { id, title: "New" })).rejects.toThrow(
+ "You can only view tasks here.",
+ );
+ expect(signed).toHaveLength(1);
+ expect(client.publish).not.toHaveBeenCalled();
+});
+
+it("assigns the person it works for when work starts", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64), [["status", "todo"]])],
+ );
await call("tasks_update", { id, status: "in_progress" });
- expect(JSON.parse(signed[0]?.content ?? "")).toMatchObject({
- status: "in_progress",
- assignees: [viewer],
- });
+ expect(tagOf(signed[0], "status")).toBe("in_progress");
+ expect(assignees(signed[0])).toEqual([viewer]);
});
-it("assigns people only, never agents", async () => {
+it("assigns only known people who can see the task", async () => {
const { call, signed } = setup(
async () => "",
- () => [head("d".repeat(64), {})],
+ () => [head("d".repeat(64))],
);
await expect(
call("tasks_update", { id, assignees: [person, agent] }),
).rejects.toThrow("never agents");
+ await expect(
+ call("tasks_update", { id, assignees: [stranger] }),
+ ).rejects.toThrow("Couldn't find a person");
+ expect(signed).toHaveLength(0);
await call("tasks_update", { id, assignees: [person] });
- expect(JSON.parse(signed[0]?.content ?? "")).toMatchObject({
- assignees: [person],
- });
+ expect(assignees(signed[0])).toEqual([person]);
+});
+
+it("refuses an assignee who can't see the task", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64))],
+ );
+ await expect(
+ call("tasks_update", { id, assignees: [person, leo] }),
+ ).rejects.toThrow("Leo can't see this task");
+ expect(signed).toHaveLength(0);
});
-it("moves a task when given a new place", async () => {
+it("previews a move, by place, and moves only with its confirm", async () => {
const { call, signed } = setup(
async () => "",
- () => [head("d".repeat(64), {})],
+ () => [head("d".repeat(64), [["assignee", person]])],
);
- await call("tasks_update", { id, place: chat });
+ await expect(
+ call("tasks_update", { id, place: chat, title: "Also this" }),
+ ).rejects.toThrow("Move a task on its own");
+ const preview = await call("tasks_update", { id, place: chat });
+ expect(preview).toContain("Not moved yet");
+ expect(preview).toContain("#random");
+ expect(preview).not.toContain("Riley");
+ expect(signed).toHaveLength(0);
+ await expect(
+ call("tasks_update", { id, place: chat, confirm: "made-up" }),
+ ).rejects.toThrow("isn't from a preview");
+ const confirm = /confirm "([^"]+)"/.exec(preview)?.[1];
+ await call("tasks_update", { id, place: chat, confirm });
expect(signed[0]?.tags).toContainEqual(["op", "move"]);
expect(signed[0]?.tags).toContainEqual(["h", chat]);
+ expect(assignees(signed[0])).toEqual([person]);
+ // A confirm is good once.
+ await expect(
+ call("tasks_update", { id, place: chat, confirm }),
+ ).rejects.toThrow();
+});
+
+it("names an assignee a move leaves behind, and unassigns them", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [
+ head("d".repeat(64), [
+ ["assignee", person],
+ ["assignee", viewer],
+ ]),
+ ],
+ );
+ const preview = await call("tasks_update", { id, place: lobby });
+ expect(preview).toContain("Riley can't see #lobby and will be unassigned.");
+ const confirm = /confirm "([^"]+)"/.exec(preview)?.[1];
+ await call("tasks_update", { id, place: lobby, confirm });
+ expect(assignees(signed[0])).toEqual([viewer]);
+});
+
+it("keeps an agent out of a private channel its owner is in", async () => {
+ const hidden = "66666666-6666-4666-8666-666666666666";
+ const { call, signed, posted } = setup(
+ async () => "",
+ () => [
+ head("d".repeat(64), [["status", "todo"]]),
+ head("c".repeat(64), [["status", "todo"]], {
+ d: hidden,
+ home: secret,
+ title: "Payroll export",
+ }),
+ ],
+ );
+ // It can't find tasks there,
+ expect(await call("tasks_find", {})).not.toContain(hidden);
+ await expect(call("tasks_find", { id: hidden })).rejects.toThrow("No task");
+ // edit or comment on them,
+ await expect(
+ call("tasks_update", { id: hidden, title: "Mine now" }),
+ ).rejects.toThrow("No task");
+ await expect(
+ call("tasks_comment", { id: hidden, text: "Seen it" }),
+ ).rejects.toThrow("No task");
+ // or move or create tasks there.
+ await expect(call("tasks_update", { id, place: secret })).rejects.toThrow(
+ "can't see that place",
+ );
+ await expect(
+ call("tasks_create", { title: "Payroll", place: secret }),
+ ).rejects.toThrow("can't see that place");
+ expect(signed).toHaveLength(0);
+ expect(posted).toHaveLength(0);
});
it("reapplies an update over someone else's newer save", async () => {
- let current = head("d".repeat(64), { description: "Theirs." });
+ let current = head("d".repeat(64), [["status", "todo"]]);
let calls = 0;
const { call, signed } = setup(
async () => {
if (calls++ === 0) {
- current = head("c".repeat(64), { description: "Newer." });
+ current = head("c".repeat(64), [["status", "todo"]], {
+ title: "Newer",
+ });
throw new PublishRejected("rejected", "conflict: stale prev");
}
return "";
@@ -221,10 +458,8 @@ it("reapplies an update over someone else's newer save", async () => {
);
await call("tasks_update", { id, status: "in_progress" });
expect(signed[1]?.tags).toContainEqual(["prev", "c".repeat(64)]);
- expect(JSON.parse(signed[1]?.content ?? "")).toMatchObject({
- description: "Newer.",
- status: "in_progress",
- });
+ expect(signed[1]?.tags).toContainEqual(["title", "Newer"]);
+ expect(tagOf(signed[1], "status")).toBe("in_progress");
});
it("tells the agent which id to check after an unclear create", async () => {
@@ -236,6 +471,6 @@ it("tells the agent which id to check after an unclear create", async () => {
);
const failed = call("tasks_create", { title: "Fix", link: false });
await expect(failed).rejects.toThrow(/saved as task [0-9a-f-]{36}/);
- const made = signed[0]?.tags.find((tag) => tag[0] === "d")?.[1];
+ const made = tagOf(signed[0], "d");
await expect(failed).rejects.toThrow(made);
});
diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts
index 75e94915ac..b8cf6b7b83 100644
--- a/src/bundled/tasks/tools.ts
+++ b/src/bundled/tasks/tools.ts
@@ -1,18 +1,22 @@
-// Agent tools: find, create, update and comment. Each runs in the owner's
-// app and writes as the owner, the way the owner's own edits do, so the
-// relay applies the owner's access. Two rules keep agents' tidying
-// trustworthy: create looks for an open task about the same thing first, and
-// Done or Cancelled needs evidence, left as a comment.
+// Agent tools: find, create, update and comment. An agent sees and says
+// things as itself: every read goes through its own connection, so it finds
+// only tasks it could read, and its comments are its own words. Saves are
+// signed by its owner, the task's creator, with the agent named as "via",
+// and only where the agent can read too; the relay applies the owner's
+// access to them. Three rules keep agents' tidying trustworthy: create looks
+// for an open task about the same thing first, Done or Cancelled needs
+// evidence, commented before the task closes, and a move is previewed and
+// done only once the person confirms it.
import type { Agents as AgentsService } from "../../features/agents/service";
+import type { BuzzClient } from "../../buzz-mcp/client";
import type { RelaySession } from "../../features/relay/session";
-import { postComment } from "./conversation";
+import { postAgentComment } from "./conversation";
import { setLink } from "./links";
import {
byRecent,
checkedFields,
imageOf,
isChannelId,
- isOpenStatus,
isPubkey,
MAX_ASSIGNEES,
statuses,
@@ -21,12 +25,22 @@ import {
type TaskFields,
type TaskStatus,
} from "./model";
-import { type Place, projectOf, readPlaces } from "./places";
-import { readTask, readTasks, saveTask } from "./store";
+import {
+ accessChange,
+ type Place,
+ placeLabel,
+ projectOf,
+ readPlaces,
+ readReaders,
+} from "./places";
+import { readTask, readTasks, saveTask, type TaskSource } from "./store";
import { holdsWords, sameness } from "./similar";
type Agents = Pick;
-type Client = { key: string; signal?: AbortSignal | undefined };
+type Client = Pick & {
+ signal?: AbortSignal | undefined;
+ relayAuthor?: string | undefined;
+};
type Args = Record;
/** How many times an agent's change is reapplied over someone else's edit. */
@@ -34,15 +48,32 @@ const ATTEMPTS = 3;
const LIST_LIMIT = 50;
/** How long one tool call's relay work may take. */
const STEP_TIMEOUT = 60_000;
+/** How long a move preview's confirmation stays good. */
+const PREVIEW_TTL = 15 * 60_000;
/** At or above: the same task. Between this and CLEAR: a person decides. */
const CLEAR_MATCH = 0.8;
const POSSIBLE_MATCH = 0.5;
+const OPEN: readonly TaskStatus[] = ["todo", "in_progress"];
+const CLOSED: readonly TaskStatus[] = ["done", "cancelled"];
+const INCOMPLETE =
+ "\n(These may not be all of them: narrow the search to see the rest.)";
const deadline = (client: Client) =>
client.signal
? AbortSignal.any([client.signal, AbortSignal.timeout(STEP_TIMEOUT)])
: AbortSignal.timeout(STEP_TIMEOUT);
+/** The agent's own reads, as task reads take them. */
+function agentReads(client: Client, session: RelaySession): TaskSource {
+ return {
+ relayAuthor: client.relayAuthor ?? session.relayAuthor,
+ snapshotRead: (filters, { signal }) => {
+ signal?.throwIfAborted();
+ return client.query(filters as never) as never;
+ },
+ };
+}
+
const statusOf = (value: unknown): TaskStatus | undefined =>
statuses.find((status) => status === value);
@@ -71,33 +102,66 @@ function imagesArg(args: Args) {
});
}
-/** Assignees by pubkey, people only: an agent never answers for a task. */
-function assigneesArg(args: Args, session: RelaySession) {
+function assigneesArg(args: Args) {
if (args.assignees === undefined) return undefined;
const list = args.assignees;
if (!Array.isArray(list) || !list.every(isPubkey))
throw new Error("assignees must be a list of people's hex pubkeys");
if (list.length > MAX_ASSIGNEES)
throw new Error(`A task has up to ${MAX_ASSIGNEES} assignees`);
+ return [...new Set(list)];
+}
+
+/** Refuses anyone who isn't a known person able to see what lives in
+ * `home`, rather than guessing: an agent never answers for a task. */
+async function checkAssignees(
+ session: RelaySession,
+ reads: TaskSource,
+ home: string,
+ assignees: readonly string[],
+ signal: AbortSignal,
+) {
+ if (!assignees.length) return;
+ await session.profiles.ensure([...assignees], "foreground").catch(() => {});
const profiles = session.profiles.snapshot();
- if (list.some((pubkey) => profiles.get(pubkey)?.isAgent))
- throw new Error("Only people can be assigned, never agents");
- return list;
+ for (const pubkey of assignees) {
+ const profile = profiles.get(pubkey);
+ if (!profile)
+ throw new Error(
+ `Couldn't find a person with pubkey ${pubkey}; nobody was assigned`,
+ );
+ if (profile.isAgent)
+ throw new Error("Only people can be assigned, never agents");
+ }
+ const readers = await readReaders(reads, home, signal);
+ if (readers.anyone) return;
+ const blind = assignees.filter((pubkey) => !readers.people.has(pubkey));
+ if (blind.length)
+ throw new Error(
+ `${blind.map((pubkey) => nameOf(session, pubkey)).join(", ")} can't see this task, so they can't be assigned`,
+ );
}
const nameOf = (session: RelaySession, pubkey: string) =>
session.profiles.snapshot().get(pubkey)?.name ?? pubkey;
+const labelOf = (id: string, places: ReadonlyMap) => {
+ const place = places.get(id);
+ return place ? placeLabel(place, places) : "a private place";
+};
+
/** Where it lives and who can see it, in words an agent can pass on. */
function whereabouts(task: Task, places: ReadonlyMap) {
const home = places.get(task.home);
const project = projectOf(task, places);
- const place = home ? `${home.name} (${home.kind}, ${home.id})` : task.home;
+ const place = home
+ ? `${placeLabel(home, places)} (${home.kind}, ${home.id})`
+ : task.home;
const inProject =
project.id && project.id !== task.home
? ` in the ${project.name ?? "private"} project`
: "";
- return `Lives in ${place}${inProject}. Anyone who can open ${home?.name ?? "that place"} can see it.`;
+ return `Lives in ${place}${inProject}. Anyone who can open ${home ? placeLabel(home, places) : "that place"} can see it.`;
}
function describe(
@@ -105,12 +169,15 @@ function describe(
session: RelaySession,
places: ReadonlyMap,
) {
+ const creator = task.creator
+ ? `${nameOf(session, task.creator)}${task.via ? ` via ${nameOf(session, task.via)}` : ""}`
+ : "unknown";
return [
`# ${task.title}`,
`id: ${task.id}`,
`status: ${statusLabels[task.status]}`,
`assignees: ${task.assignees.map((pubkey) => nameOf(session, pubkey)).join(", ") || "nobody"}`,
- `created by: ${nameOf(session, task.author)}`,
+ `created by: ${creator}`,
`updated: ${new Date(task.updatedAt * 1000).toISOString()} by ${nameOf(session, task.editor)}`,
whereabouts(task, places),
"",
@@ -128,7 +195,18 @@ const summary = (task: Task, session: RelaySession) =>
: "nobody has it"
})`;
+/** A move the person was shown, good once for that revision and place. */
+type Preview = Readonly<{
+ task: string;
+ revision: string;
+ to: string;
+ keep: readonly string[];
+ expires: number;
+}>;
+
export function addTaskTools(agents: Agents) {
+ const previews = new Map();
+
/** The owner's session for this agent's community. */
function sessionOf(client: Client) {
const relay = agents.relay(client.key)?.snapshot();
@@ -137,27 +215,41 @@ export function addTaskTools(agents: Agents) {
return relay.session;
}
- async function current(
- session: RelaySession,
- id: string,
- signal: AbortSignal,
- ) {
- const task = await readTask(session, id, signal);
+ /** The task as the agent can read it; one it can't read isn't there. */
+ async function current(reads: TaskSource, id: string, signal: AbortSignal) {
+ const task = await readTask(reads, id, signal);
if (!task) throw new Error(`No task ${id} that you can read`);
return task;
}
- /** Applies `edit` to the newest revision, again over anyone else's save. */
+ /** Throws unless the agent can read place `id`. */
+ async function readable(reads: TaskSource, id: string, signal: AbortSignal) {
+ const places = await readPlaces(reads, [id], signal);
+ if (!places.has(id))
+ throw new Error(
+ "You can't see that place, so a task can't go there. Nothing changed.",
+ );
+ return places;
+ }
+
+ /** Applies `edit` to the newest revision the agent can read, again over
+ * anyone else's save. The owner signs; the relay may refuse them. */
async function change(
session: RelaySession,
+ reads: TaskSource,
id: string,
edit: (task: Task) => TaskFields,
signal: AbortSignal,
home?: string,
+ revision?: string,
) {
- let task = await current(session, id, signal);
+ let task = await current(reads, id, signal);
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
signal.throwIfAborted();
+ if (revision && task.revision !== revision)
+ throw new Error(
+ "The task changed since the move was previewed. Preview it again.",
+ );
const target =
home && home !== task.home
? { op: "move" as const, base: task, home }
@@ -201,22 +293,19 @@ export function addTaskTools(agents: Agents) {
},
async call(client, _context, args) {
const session = sessionOf(client);
+ const reads = agentReads(client, session);
const signal = deadline(client);
const id = textArg(args, "id");
if (id) {
- const task = await current(session, id, signal);
+ const task = await current(reads, id, signal);
return describe(
task,
session,
- await readPlaces(session, [task.home], signal),
+ await readPlaces(reads, [task.home], signal),
);
}
const words = (textArg(args, "words") ?? "").trim();
const place = channelArg(args, "place");
- const which =
- args.status === "closed" || args.status === "all"
- ? args.status
- : "open";
const assignee = textArg(args, "assignee");
if (
assignee &&
@@ -225,47 +314,47 @@ export function addTaskTools(agents: Agents) {
!isPubkey(assignee)
)
throw new Error('assignee must be "me", "nobody" or a hex pubkey');
- const who = assignee === "me" ? session.viewer : assignee;
- const all = await readTasks(session, signal);
- const places = place
- ? await readPlaces(
- session,
- all.map((task) => task.home),
- signal,
- )
- : undefined;
- const tasks = all
+ const { tasks: found, complete } = await readTasks(reads, signal, {
+ status:
+ args.status === "all"
+ ? undefined
+ : args.status === "closed"
+ ? CLOSED
+ : OPEN,
+ assignee:
+ assignee === "me"
+ ? session.viewer
+ : assignee === "nobody"
+ ? null
+ : assignee,
+ within: place,
+ });
+ const tasks = found
.filter(
(task) =>
- (which === "all" ||
- isOpenStatus(task.status) === (which === "open")) &&
- (!who ||
- (who === "nobody"
- ? task.assignees.length === 0
- : task.assignees.includes(who))) &&
- (!place ||
- task.home === place ||
- (places && projectOf(task, places).id === place)) &&
- (!words || holdsWords(words, `${task.title} ${task.description}`)),
+ !words || holdsWords(words, `${task.title} ${task.description}`),
)
.sort(byRecent);
- if (!tasks.length) return "No tasks match.";
- return tasks
- .slice(0, LIST_LIMIT)
- .map((task) => summary(task, session))
- .concat(
- tasks.length > LIST_LIMIT
- ? [`…and ${tasks.length - LIST_LIMIT} more`]
- : [],
- )
- .join("\n");
+ const more = complete ? "" : INCOMPLETE;
+ if (!tasks.length) return `No tasks match.${more}`;
+ return (
+ tasks
+ .slice(0, LIST_LIMIT)
+ .map((task) => summary(task, session))
+ .concat(
+ tasks.length > LIST_LIMIT
+ ? [`…and ${tasks.length - LIST_LIMIT} more`]
+ : [],
+ )
+ .join("\n") + more
+ );
},
});
agents.addTool({
name: "tasks_create",
description:
- "Creates a task from what you're working on, without asking first: a short title, a Markdown description that makes sense to someone who can't read this conversation, and image links. It lives in place (default: this conversation), and everyone who can open that place can see it. It first looks for an open task about the same thing there: a clear match is returned instead, so comment on it with tasks_comment; a possible match is returned for the person to decide, and only then create with new_anyway. If you can't post in place, nothing is created: say so, never put it somewhere else. Reply with the task's id, where it lives and who can see it.",
+ "Creates a task from what you're working on, without asking first: a short title, a Markdown description that makes sense to someone who can't read this conversation, and image links. It lives in place (default: this conversation), and everyone who can open that place can see it. It first looks for an open task about the same thing there, across its whole project: a clear match is returned instead, so comment on it with tasks_comment; a possible match is returned for the person to decide, and only then create with new_anyway. If you can't see place or the person you work for can't post there, nothing is created: say so, never put it somewhere else. Reply with the task's id, where it lives and who can see it.",
inputSchema: {
type: "object",
properties: {
@@ -300,6 +389,7 @@ export function addTaskTools(agents: Agents) {
},
async call(client, context, args) {
const session = sessionOf(client);
+ const reads = agentReads(client, session);
const signal = deadline(client);
const home = channelArg(args, "place") ?? context.channel;
if (!isChannelId(home))
@@ -311,9 +401,13 @@ export function addTaskTools(agents: Agents) {
images: imagesArg(args) ?? [],
assignees: [],
});
- const open = (await readTasks(session, signal)).filter(
- (task) => task.home === home && isOpenStatus(task.status),
- );
+ const places = await readable(reads, home, signal);
+ // The whole project the place is in, or the place itself.
+ const project = places.get(home)?.parent ?? home;
+ const { tasks: open, complete } = await readTasks(reads, signal, {
+ status: OPEN,
+ within: project,
+ });
const scored = open
.map((task) => ({ task, score: sameness(fields.title, task.title) }))
.sort((a, b) => b.score - a.score);
@@ -321,17 +415,18 @@ export function addTaskTools(agents: Agents) {
if (best && best.score >= CLEAR_MATCH)
return `Not created: open task ${best.task.id} is about the same thing. Comment on it with tasks_comment instead.\n\n${summary(best.task, session)}`;
const possible = scored.filter((item) => item.score >= POSSIBLE_MATCH);
+ const unsure = complete ? "" : INCOMPLETE;
if (possible.length && args.new_anyway !== true)
return `Not created yet: these open tasks may be about the same thing. Ask the person whether one of them is it; if not, call tasks_create again with new_anyway.\n\n${possible
.slice(0, 5)
.map((item) => summary(item.task, session))
- .join("\n")}`;
+ .join("\n")}${unsure}`;
// Named before saving, so a retry after an unclear outcome can check.
const id = crypto.randomUUID();
const result = await saveTask(
session,
fields,
- { op: "create", home, id },
+ { op: "create", home, id, via: client.pubkey },
signal,
).catch((reason: unknown) => {
throw new Error(
@@ -349,15 +444,17 @@ export function addTaskTools(agents: Agents) {
() => "\nCouldn't link this conversation.",
)
: "";
- const places = await readPlaces(session, [home], signal);
- return `Created task ${id}.${linked}\n\n${describe(result.task, session, places)}`;
+ const checked = complete
+ ? ""
+ : "\n(The check for an existing task may have missed some.)";
+ return `Created task ${id}.${linked}${checked}\n\n${describe(result.task, session, places)}`;
},
});
agents.addTool({
name: "tasks_update",
description:
- "Changes a task: title, description, images, assignees, status, or place (moving it changes who can see it and its comments). Omitted fields stay. Set In progress when work starts; that assigns the person you work for. Set Done or Cancelled only with evidence, such as a merged pull request or someone saying it's finished, and give it as evidence: it's left as a comment. Otherwise comment on progress instead.",
+ "Changes a task: title, description, images, assignees or status. Omitted fields stay. Set In progress when work starts; that assigns the person you work for. Set Done or Cancelled only with evidence, such as a merged pull request or someone saying it's finished, and give it as evidence: it's commented first, and the task closes only once the comment is in. To move a task, give only id and place: you get a preview of what changes, show it to the person, and only once they agree call again with the same id and place and the preview's confirm. Otherwise comment on progress instead.",
inputSchema: {
type: "object",
properties: {
@@ -372,7 +469,8 @@ export function addTaskTools(agents: Agents) {
assignees: {
type: "array",
items: { type: "string" },
- description: "People's hex pubkeys, up to four; replaces the list",
+ description:
+ "People's hex pubkeys, up to four, who can see the task; replaces the list",
},
status: { type: "string", enum: [...statuses] },
evidence: {
@@ -381,7 +479,13 @@ export function addTaskTools(agents: Agents) {
},
place: {
type: "string",
- description: "Move it to this project, channel or chat id",
+ description:
+ "Move it to this project, channel or chat id, on its own: first a preview, then with confirm",
+ },
+ confirm: {
+ type: "string",
+ description:
+ "The confirm from a move preview, once the person agreed to it",
},
},
required: ["id"],
@@ -389,12 +493,17 @@ export function addTaskTools(agents: Agents) {
},
async call(client, _context, args) {
const session = sessionOf(client);
+ const reads = agentReads(client, session);
const id = textArg(args, "id") ?? "";
+ const place = channelArg(args, "place");
+ const signal = deadline(client);
+ if (place) return move(session, reads, id, place, args, signal);
+ if (args.confirm !== undefined)
+ throw new Error("confirm goes with the place of a move preview");
const title = textArg(args, "title");
const description = textArg(args, "description");
const images = imagesArg(args);
- const assignees = assigneesArg(args, session);
- const place = channelArg(args, "place");
+ const assignees = assigneesArg(args);
const status =
args.status === undefined ? undefined : statusOf(args.status);
if (args.status !== undefined && !status)
@@ -405,10 +514,20 @@ export function addTaskTools(agents: Agents) {
throw new Error(
"Done or Cancelled needs evidence: say in one line why, such as the merged pull request or who said it's finished",
);
- const signal = deadline(client);
+ const task = await current(reads, id, signal);
+ if (assignees)
+ await checkAssignees(session, reads, task.home, assignees, signal);
+ // The evidence comes first: no comment, no close.
+ if (closing && evidence && task.status !== status)
+ await postAgentComment(
+ client,
+ task,
+ `${statusLabels[status]}: ${evidence}`,
+ );
const viewer = session.viewer;
- const task = await change(
+ const saved = await change(
session,
+ reads,
id,
(base) => {
const people = assignees ?? base.assignees;
@@ -429,30 +548,106 @@ export function addTaskTools(agents: Agents) {
};
},
signal,
- place,
- );
- const noted =
- closing && evidence
- ? await postComment(
- session,
- task,
- `${statusLabels[task.status]}: ${evidence}`,
- signal,
- ).then(
- () => "",
- () =>
- "\nThe evidence comment didn't post; add it with tasks_comment.",
- )
- : "";
- const places = await readPlaces(session, [task.home], signal);
- return `Updated.${noted}\n\n${describe(task, session, places)}`;
+ ).catch((reason: unknown) => {
+ if (!closing) throw reason;
+ throw new Error(
+ `The evidence comment is in, but the task didn't close: ${
+ reason instanceof Error ? reason.message : "the save failed"
+ }`,
+ );
+ });
+ const places = await readPlaces(reads, [saved.home], signal);
+ return `Updated.\n\n${describe(saved, session, places)}`;
},
});
+ /** A move: first what it changes, by place, and who it unassigns; then,
+ * with that preview's confirm, the move itself. */
+ async function move(
+ session: RelaySession,
+ reads: TaskSource,
+ id: string,
+ to: string,
+ args: Args,
+ signal: AbortSignal,
+ ) {
+ const others = Object.keys(args).filter(
+ (key) => !["id", "place", "confirm"].includes(key),
+ );
+ if (others.length)
+ throw new Error(
+ `Move a task on its own: change ${others.join(", ")} in another call`,
+ );
+ const task = await current(reads, id, signal);
+ if (task.home === to) return "It already lives there. Nothing changed.";
+ await readable(reads, to, signal);
+ const places = await readPlaces(reads, [task.home, to], signal);
+ const confirm = textArg(args, "confirm");
+ if (confirm) {
+ const preview = previews.get(confirm);
+ previews.delete(confirm);
+ if (
+ !preview ||
+ preview.expires < Date.now() ||
+ preview.task !== task.id ||
+ preview.to !== to
+ )
+ throw new Error(
+ "That confirm isn't from a preview of this move. Preview it again.",
+ );
+ const moved = await change(
+ session,
+ reads,
+ id,
+ (base) => ({ ...base, assignees: preview.keep }),
+ signal,
+ to,
+ preview.revision,
+ );
+ return `Moved.\n\n${describe(moved, session, places)}`;
+ }
+ const { gain, lose } = accessChange(task.home, to, places);
+ const readers = await readReaders(reads, to, signal);
+ const keep = readers.anyone
+ ? task.assignees
+ : task.assignees.filter((pubkey) => readers.people.has(pubkey));
+ const dropped = task.assignees.filter((pubkey) => !keep.includes(pubkey));
+ for (const [key, value] of previews)
+ if (value.expires < Date.now()) previews.delete(key);
+ const token = crypto.randomUUID();
+ previews.set(token, {
+ task: task.id,
+ revision: task.revision,
+ to,
+ keep,
+ expires: Date.now() + PREVIEW_TTL,
+ });
+ const named = (list: readonly Place[]) =>
+ list.map((place) => placeLabel(place, places)).join(", ");
+ const destination = labelOf(to, places);
+ return [
+ `Not moved yet. Moving "${task.title}" to ${destination}:`,
+ ...(gain.length
+ ? [
+ `- Everyone in ${named(gain)} will be able to see it and its comments.`,
+ ]
+ : []),
+ ...(lose.length
+ ? [`- People who are only in ${named(lose)} will lose access.`]
+ : []),
+ ...dropped.map(
+ (pubkey) =>
+ `- ${nameOf(session, pubkey)} can't see ${destination} and will be unassigned.`,
+ ),
+ "",
+ `Show this to the person. Only if they agree, call tasks_update with id, place and confirm "${token}".`,
+ ].join("\n");
+ }
+
agents.addTool({
name: "tasks_comment",
description:
- "Comments on a task, such as progress, a summary of a thread about it, or the answer to a question in it. Everyone who can see the task reads it.",
+ "Comments on a task as you, such as progress, a summary of a thread about it, or the answer to a question in it. Everyone who can see the task reads it.",
inputSchema: {
type: "object",
properties: {
@@ -467,8 +662,12 @@ export function addTaskTools(agents: Agents) {
const signal = deadline(client);
const text = (textArg(args, "text") ?? "").trim();
if (!text) throw new Error("text must not be empty");
- const task = await current(session, textArg(args, "id") ?? "", signal);
- await postComment(session, task, text, signal);
+ const task = await current(
+ agentReads(client, session),
+ textArg(args, "id") ?? "",
+ signal,
+ );
+ await postAgentComment(client, task, text);
return `Commented on ${task.id}.`;
},
});
From e45dd10ebad9edadde9adbe43ad8514315407a40 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 09:16:29 -0800
Subject: [PATCH 13/18] feat(tasks): use the compact Combobox trigger for
assignees
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/TaskView.tsx | 12 ++++++++----
1 file changed, 8 insertions(+), 4 deletions(-)
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index 8215eab8c7..3650bbf6f2 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -230,7 +230,11 @@ function TaskDetails({
Edit
- setMoving(true)}>
+ setMoving(true)}
+ >
Move…
@@ -428,7 +432,7 @@ function AssigneePicker({
if (next.length <= MAX_ASSIGNEES) onChange(next.map((item) => item.id));
}}
>
-
+
{chosen.length ? (
- {listNames(dropped.map((key) => person(key).name))} can’t see{" "}
- {label} and will be unassigned.
+ {listNames(dropped.map((key) => person(key).name))} can’t see {label}{" "}
+ and will be unassigned.
) : null}
{error ? (
From 07cdaa59bc625e4a41aed173af43284bac969d61 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 10:45:28 -0800
Subject: [PATCH 14/18] fix(tasks): keep agent reads to the agent, and share
the place rules
A save reads back through the reader its caller gives it, so an agent's
conflict retry reads as the agent and stops when the task is gone or has
moved. Who can see a place now honors parent_access, for the assignee
picker, the agent's assignee check and the move preview alike, and a
relay refusal shows its reason. One rule says where a task can live: a
project, channel or chat, never a DM or a huddle. A failed home check
shows a retry instead of an empty comment thread.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/TaskComments.test.tsx | 16 +++
src/bundled/tasks/TaskComments.tsx | 6 +-
src/bundled/tasks/TaskView.tsx | 5 +-
src/bundled/tasks/TasksPanel.tsx | 9 +-
src/bundled/tasks/links.ts | 7 +-
src/bundled/tasks/places.ts | 69 +++++++++--
src/bundled/tasks/react.ts | 16 +--
src/bundled/tasks/store.test.ts | 38 ++++--
src/bundled/tasks/store.ts | 18 ++-
src/bundled/tasks/tools.test.ts | 151 +++++++++++++++++++++++-
src/bundled/tasks/tools.ts | 22 +++-
11 files changed, 309 insertions(+), 48 deletions(-)
diff --git a/src/bundled/tasks/TaskComments.test.tsx b/src/bundled/tasks/TaskComments.test.tsx
index bf91071fad..7b695d306b 100644
--- a/src/bundled/tasks/TaskComments.test.tsx
+++ b/src/bundled/tasks/TaskComments.test.tsx
@@ -145,6 +145,22 @@ it("offers to try again when the relay couldn't be asked", async () => {
expect(handles.get(home)?.retry).toHaveBeenCalled();
});
+it("shows a failed home check with a retry, not an empty thread", async () => {
+ const { handles, view } = setup();
+ view();
+ await answer(handles, conversation, {
+ status: "unavailable",
+ reason: "unavailable",
+ });
+ await answer(handles, home, { status: "unavailable", reason: "failed" });
+ expect(screen.queryByText("No comments yet.")).toBeNull();
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Couldn’t load comments.",
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(handles.get(home)?.retry).toHaveBeenCalled();
+});
+
it("says so where the community has no task comments", () => {
setup({ conversations: false }).view();
expect(
diff --git a/src/bundled/tasks/TaskComments.tsx b/src/bundled/tasks/TaskComments.tsx
index 45f010a707..136d8ed2b5 100644
--- a/src/bundled/tasks/TaskComments.tsx
+++ b/src/bundled/tasks/TaskComments.tsx
@@ -86,7 +86,11 @@ export function TaskComments({
Loading comments…
);
- if (reason === "failed")
+ // Either question going unanswered is a failure to show, never "no
+ // comments yet": the home's answer decides who may start them.
+ const homeFailed =
+ home.state.status === "unavailable" && home.state.reason === "failed";
+ if (reason === "failed" || homeFailed)
return (
Couldn’t load comments.
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index 3650bbf6f2..08562099e9 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -166,6 +166,7 @@ function TaskDetails({
setSaving(true);
try {
const result = await saveTask(
+ session,
session,
{ ...fieldsOf(task), ...next },
{ op: "update", base: task },
@@ -559,6 +560,7 @@ function LinkedConversations({
setBusy(true);
try {
await setLink(
+ session,
session,
task.id,
conversation,
@@ -741,6 +743,7 @@ function MoveTask({
setError("");
try {
const result = await saveTask(
+ session,
session,
{
...fieldsOf(task),
@@ -910,7 +913,7 @@ function TaskEditor({
setError("");
setSaving(true);
try {
- const result = await saveTask(session, draft, save);
+ const result = await saveTask(session, session, draft, save);
if (result.status === "saved") {
onSaved(result.task);
onDone(true);
diff --git a/src/bundled/tasks/TasksPanel.tsx b/src/bundled/tasks/TasksPanel.tsx
index 0597668551..3e0af5175a 100644
--- a/src/bundled/tasks/TasksPanel.tsx
+++ b/src/bundled/tasks/TasksPanel.tsx
@@ -73,7 +73,14 @@ export function TasksPanel({
if (linking) return;
setLinking(true);
try {
- await setLink(session, task, chat, true, AbortSignal.timeout(20_000));
+ await setLink(
+ session,
+ session,
+ task,
+ chat,
+ true,
+ AbortSignal.timeout(20_000),
+ );
setAttempt((count) => count + 1);
} catch (reason) {
notify(
diff --git a/src/bundled/tasks/links.ts b/src/bundled/tasks/links.ts
index 9c66fff0f0..518c8f92e0 100644
--- a/src/bundled/tasks/links.ts
+++ b/src/bundled/tasks/links.ts
@@ -70,7 +70,7 @@ export async function readLinks(
/** The link's head, including a deletion, or undefined when it never was. */
async function head(
- session: RelaySession,
+ session: Pick
,
id: string,
conversation: string,
signal: AbortSignal,
@@ -94,9 +94,10 @@ async function head(
/** Links `task` to `conversation`, or with `unlink` removes the link. Only
* people who can post in the conversation can. Doing what is already done
- * succeeds. */
+ * succeeds. The link's current state is read through `reader` alone. */
export async function setLink(
session: RelaySession,
+ reader: Pick,
task: string,
conversation: string,
linked: boolean,
@@ -105,7 +106,7 @@ export async function setLink(
const writer = session.configArtifactWriter;
if (!writer) throw new Error("This community connection can’t link tasks.");
const id = await linkId(task, conversation);
- const current = await head(session, id, conversation, signal);
+ const current = await head(reader, id, conversation, signal);
const deleted = !current || tag(current, "op") === "delete";
if (deleted !== linked) return;
const op = linked ? (current ? "restore" : "create") : "delete";
diff --git a/src/bundled/tasks/places.ts b/src/bundled/tasks/places.ts
index 476f2d181a..3602a9ec96 100644
--- a/src/bundled/tasks/places.ts
+++ b/src/bundled/tasks/places.ts
@@ -9,6 +9,7 @@ import { tag, type RelayEvent } from "../../features/relay/events";
import type { RelaySession } from "../../features/relay/session";
import { soloLabels } from "../../features/solo/labels";
import { channelVisibility } from "../../features/relay/channel-details-protocol";
+import { huddleParent } from "../../features/huddle/lifecycle";
import { isChannelId, isPubkey, type Task } from "./model";
export type Place = Readonly<{
@@ -19,8 +20,29 @@ export type Place = Readonly<{
parent?: string | undefined;
/** Open to everyone in the community. */
open?: true | undefined;
+ /** What it takes from the places above it (`parent_access`): `guest`
+ * lets their people read but not post, `none` shuts them out. */
+ parentAccess?: "guest" | "none" | undefined;
+ /** The relay's channel type (`stream`, `forum`, `dm`, …). */
+ type?: string | undefined;
+ huddle?: true | undefined;
+ archived?: true | undefined;
}>;
+/** The one rule for where a task can live, for the screens and the agent
+ * tools alike: a project, channel or chat that isn't archived. Never a DM or
+ * a huddle, where a task could get no comments and no place in Tasks. */
+export const canHoldTasks = (
+ place: Readonly<{
+ type?: string | undefined;
+ huddle?: true | undefined;
+ archived?: true | undefined;
+ }>,
+) =>
+ !place.archived &&
+ !place.huddle &&
+ (place.type === "stream" || place.type === "forum" || place.type === "solo");
+
/** A project as the Tasks page groups by it. `name` is undefined for a
* project the viewer can't read. */
export type ProjectGroup = Readonly<{
@@ -34,15 +56,33 @@ function placeOf(event: RelayEvent): Place | undefined {
const id = tag(event, "d");
if (!isChannelId(id)) return undefined;
const parent = tag(event, "parent");
+ const { type, labels } = channelIdentity(event);
return {
id,
name: metadataName(event) ?? id.slice(0, 8),
- kind: soloLabels(channelIdentity(event).labels) ? "chat" : "channel",
+ kind: soloLabels(labels) ? "chat" : "channel",
+ ...(type ? { type } : {}),
+ // As discovery tells a huddle's room: private, named for its parent.
+ ...(channelVisibility(event) === "private" &&
+ huddleParent(tag(event, "about"))
+ ? { huddle: true as const }
+ : {}),
+ ...(event.tags.some(
+ ([name, value]) => name === "archived" && value === "true",
+ )
+ ? { archived: true as const }
+ : {}),
...(isChannelId(parent) ? { parent } : {}),
...(channelVisibility(event) === "public" ? { open: true as const } : {}),
+ ...parentAccessOf(event),
};
}
+function parentAccessOf(event: RelayEvent): Pick {
+ const value = tag(event, "parent_access");
+ return value === "guest" || value === "none" ? { parentAccess: value } : {};
+}
+
/** A place other places are filed under. */
export const isProject = (id: string, places: ReadonlyMap) =>
[...places.values()].some((place) => place.parent === id);
@@ -58,9 +98,9 @@ export function placeLabel(
: `#${place.name}`;
}
-/** Who can see what lives in `home`: anyone, when it or a place it is filed
- * under is open; otherwise the members of those places, from their
- * relay-signed rosters. The relay refuses an assignee who can't. */
+/** Who can see what lives in `home`: anyone, when a place it is seen from
+ * is open; otherwise the members of those places, from their relay-signed
+ * rosters. The relay refuses an assignee who can't. */
export async function readReaders(
session: Pick,
home: string,
@@ -70,7 +110,7 @@ export async function readReaders(
const author = session.relayAuthor;
if (!read || !author) return { anyone: false, people: new Set() };
const places = await readPlaces(session, [home], signal);
- const chain = chainOf(home, places);
+ const chain = seenFrom(home, places);
if (chain.some((id) => places.get(id)?.open))
return { anyone: true, people: new Set() };
const rosters = await read(
@@ -134,13 +174,16 @@ export function projectOf(
: { id: undefined, name: undefined };
}
-/** `id` and the places it is filed under, nearest first: everyone who can
- * read one of these reads what lives in `id`. */
-function chainOf(id: string, places: ReadonlyMap) {
+/** The places whose people can see what lives in `id`: itself, then each
+ * place it is filed under, as far as `parent_access` lets them in. A place
+ * set to `none` keeps everyone above it out, as the relay does. */
+function seenFrom(id: string, places: ReadonlyMap) {
const chain = [id];
- for (let at = places.get(id)?.parent; at && !chain.includes(at); ) {
- chain.push(at);
- at = places.get(at)?.parent;
+ for (let place = places.get(id); place?.parentAccess !== "none"; ) {
+ const parent = place?.parent;
+ if (!parent || chain.includes(parent)) break;
+ chain.push(parent);
+ place = places.get(parent);
}
return chain;
}
@@ -153,8 +196,8 @@ export function accessChange(
to: string,
places: ReadonlyMap,
): Readonly<{ gain: readonly Place[]; lose: readonly Place[] }> {
- const before = chainOf(from, places);
- const after = chainOf(to, places);
+ const before = seenFrom(from, places);
+ const after = seenFrom(to, places);
const named = (ids: readonly string[]) =>
ids.flatMap((id) => places.get(id) ?? []);
return {
diff --git a/src/bundled/tasks/react.ts b/src/bundled/tasks/react.ts
index fa3bade9c7..d0466d8c08 100644
--- a/src/bundled/tasks/react.ts
+++ b/src/bundled/tasks/react.ts
@@ -13,7 +13,7 @@ import type {
import type { ChannelSummary } from "../../features/relay/contracts";
import { useChannelRoster } from "../../features/relay/react";
import type { Task } from "./model";
-import { type Place, readPlaces } from "./places";
+import { canHoldTasks, type Place, readPlaces } from "./places";
import { type TasksState, type TasksView, watchTasks } from "./store";
const loading: TasksView = {
@@ -106,16 +106,16 @@ export function usePlaces(
return places;
}
-/** Places a task can live in: channels and chats, not DMs, huddles or
- * archived ones. Whether the viewer may post there is the relay's answer
+/** Listed places a task can live in, by the one rule (`canHoldTasks`).
+ * Whether the viewer may post there is the relay's answer
* (`usePlaceAccess`), never this list's. */
export const isTaskPlace = (channel: ChannelSummary) =>
- !channel.archived &&
!channel.pending &&
- !channel.huddle &&
- (channel.channelType === "stream" ||
- channel.channelType === "forum" ||
- channel.channelType === "solo");
+ canHoldTasks({
+ type: channel.channelType,
+ huddle: channel.huddle,
+ archived: channel.archived,
+ });
/** The places the viewer knows of, those this device already knows they can
* post in first. */
diff --git a/src/bundled/tasks/store.test.ts b/src/bundled/tasks/store.test.ts
index e7b3261a81..644e685230 100644
--- a/src/bundled/tasks/store.test.ts
+++ b/src/bundled/tasks/store.test.ts
@@ -56,13 +56,18 @@ const tagsOf = (sign: ReturnType["sign"], call: number) =>
it("creates a task in its home, then edits only the revision it opened", async () => {
const { session: relay, sign } = session(async () => "");
- const created = await saveTask(relay, fields, { op: "create", home, id });
+ const created = await saveTask(relay, relay, fields, {
+ op: "create",
+ home,
+ id,
+ });
expect(created.status).toBe("saved");
expect(tagsOf(sign, 0)).toContainEqual(["op", "create"]);
expect(tagsOf(sign, 0)).toContainEqual(["h", home]);
expect(tagsOf(sign, 0).some(([name]) => name === "prev")).toBe(false);
if (created.status !== "saved") return;
await saveTask(
+ relay,
relay,
{ ...fields, status: "done" },
{ op: "update", base: created.task },
@@ -75,7 +80,11 @@ it("creates a task in its home, then edits only the revision it opened", async (
it("moves a task as a revision whose home is the new place", async () => {
const { session: relay, sign } = session(async () => "");
const base = taskOf(head("d".repeat(64))) as Task;
- const moved = await saveTask(relay, fields, { op: "move", base, home: away });
+ const moved = await saveTask(relay, relay, fields, {
+ op: "move",
+ base,
+ home: away,
+ });
expect(moved.status === "saved" && moved.task.home).toBe(away);
expect(tagsOf(sign, 0)).toContainEqual(["op", "move"]);
expect(tagsOf(sign, 0)).toContainEqual(["h", away]);
@@ -88,7 +97,7 @@ it("reports someone else's save as a conflict with their version", async () => {
throw new PublishRejected("rejected", "conflict: stale prev");
}, [theirs]);
const base = taskOf(head("d".repeat(64))) as Task;
- const result = await saveTask(relay, fields, { op: "update", base });
+ const result = await saveTask(relay, relay, fields, { op: "update", base });
expect(result).toEqual({ status: "conflict", current: taskOf(theirs) });
});
@@ -98,13 +107,18 @@ it("confirms an uncertain save from the head, else says it failed", async () =>
throw new Error("socket closed");
}, [head("f".repeat(64))]);
expect(
- (await saveTask(landed.session, fields, { op: "update", base })).status,
+ (
+ await saveTask(landed.session, landed.session, fields, {
+ op: "update",
+ base,
+ })
+ ).status,
).toBe("saved");
const lost = session(async () => {
throw new Error("socket closed");
}, [head("d".repeat(64))]);
await expect(
- saveTask(lost.session, fields, { op: "update", base }),
+ saveTask(lost.session, lost.session, fields, { op: "update", base }),
).rejects.toThrow("Couldn’t save the task. Try again.");
});
@@ -114,10 +128,14 @@ it("says why the relay refused, for an edit and for a move", async () => {
throw new PublishRejected("rejected", "restricted: not a member");
});
await expect(
- saveTask(refused.session, fields, { op: "update", base }),
+ saveTask(refused.session, refused.session, fields, { op: "update", base }),
).rejects.toThrow("You can only view tasks here.");
await expect(
- saveTask(refused.session, fields, { op: "move", base, home: away }),
+ saveTask(refused.session, refused.session, fields, {
+ op: "move",
+ base,
+ home: away,
+ }),
).rejects.toThrow("between places you can post in");
});
@@ -125,7 +143,11 @@ 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");
}, [head("f".repeat(64))]);
- const result = await saveTask(relay, fields, { op: "create", home, id });
+ const result = await saveTask(relay, relay, fields, {
+ op: "create",
+ home,
+ id,
+ });
expect(result.status).toBe("saved");
expect(tagsOf(sign, 0)).toContainEqual(["d", id]);
});
diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts
index 6e7d4b2594..89c2e4efa6 100644
--- a/src/bundled/tasks/store.ts
+++ b/src/bundled/tasks/store.ts
@@ -204,10 +204,13 @@ export type SaveTarget =
| Readonly<{ op: "update"; base: Task }>
| Readonly<{ op: "move"; base: Task; home: string }>;
-/** Saves one revision. A new task's caller keeps one `id` across retries, so
- * a create that landed unseen is found, not made twice. */
+/** Saves one revision, signed by the session's viewer. A new task's caller
+ * keeps one `id` across retries, so a create that landed unseen is found, not
+ * made twice. Whatever the save reads back, to see whose revision won, comes
+ * through `reader` alone: an agent's tool passes the agent's own reads. */
export async function saveTask(
session: RelaySession,
+ reader: TaskSource,
fields: TaskFields,
target: SaveTarget,
signal: AbortSignal = AbortSignal.timeout(20_000),
@@ -254,7 +257,7 @@ export async function saveTask(
delivery.status === "uncertain"
) {
// The head shows whether this revision landed, or whose did instead.
- const current = await readTask(session, id, signal, home).catch(
+ const current = await readTask(reader, id, signal, home).catch(
() => undefined,
);
if (current?.revision === event.id)
@@ -262,7 +265,9 @@ export async function saveTask(
if (delivery.status === "refused" && current)
return { status: "conflict", current };
if (delivery.status === "refused")
- throw new Error("Someone else changed this task. Try again.");
+ throw new Error(
+ "Someone else changed or removed this task. Nothing was saved.",
+ );
}
throw new Error(
delivery.status === "refused" && delivery.refusal === "permission"
@@ -271,6 +276,9 @@ export async function saveTask(
: "You can only view tasks here."
: delivery.status === "refused" && delivery.refusal === "too-large"
? "This task is too large to save. Shorten the description."
- : "Couldn’t save the task. Try again.",
+ : // 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.",
);
}
diff --git a/src/bundled/tasks/tools.test.ts b/src/bundled/tasks/tools.test.ts
index 6995c8952f..31ab7f91b8 100644
--- a/src/bundled/tasks/tools.test.ts
+++ b/src/bundled/tasks/tools.test.ts
@@ -17,6 +17,13 @@ const home = "33333333-3333-4333-8333-333333333333";
const secret = "55555555-5555-4555-8555-555555555555";
/** A channel Riley isn't in. */
const lobby = "77777777-7777-4777-8777-777777777777";
+/** A project Leo is in, a channel in it, and one shut off from it. */
+const project = "88888888-8888-4888-8888-888888888888";
+const filed = "99999999-9999-4999-8999-999999999999";
+const shut = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
+/** A DM and a huddle, where no task can live. */
+const dm = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
+const huddle = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
type Event = {
id: string;
@@ -46,12 +53,18 @@ const head = (
],
});
-const place = (d: string, name: string): Event => ({
+const place = (d: string, name: string, more: string[][] = []): Event => ({
id: d.replace(/-/g, "").padEnd(64, "0"),
pubkey: relay,
kind: 39000,
content: "",
- tags: [["d", d], ["name", name], ["private"]],
+ tags: [
+ ["d", d],
+ ["name", name],
+ ["t", more.find(([key]) => key === "t")?.[1] ?? "stream"],
+ ["private"],
+ ...more.filter(([key]) => key !== "t"),
+ ],
});
const roster = (d: string, members: string[]): Event => ({
...place(d, ""),
@@ -90,7 +103,11 @@ type Signed = { kind: number; content: string; tags: string[][] };
/** The owner can read `heads` and every place; the agent can read every
* place but `secret`, and what lives there. */
-function setup(publish: () => Promise, heads: () => Event[]) {
+function setup(
+ publish: () => Promise,
+ heads: () => Event[],
+ where = chat,
+) {
const signed: Signed[] = [];
const posted: Signed[] = [];
const places = () => [
@@ -102,6 +119,19 @@ function setup(publish: () => Promise, heads: () => Event[]) {
roster(home, [viewer, person]),
roster(chat, [viewer, person]),
roster(secret, [viewer]),
+ place(project, "Payments"),
+ place(filed, "billing", [["parent", project]]),
+ place(shut, "payroll-review", [
+ ["parent", project],
+ ["parent_access", "none"],
+ ]),
+ roster(project, [viewer, leo]),
+ roster(filed, [viewer]),
+ roster(shut, [viewer]),
+ place(dm, "", [["t", "dm"]]),
+ place(huddle, "huddle-cccccccc", [
+ ["about", `Buzz Huddle (buzz.huddles/v1)\nparent:${home}`],
+ ]),
];
const visible = (event: Event) =>
!event.tags.some(
@@ -157,7 +187,7 @@ function setup(publish: () => Promise, heads: () => Event[]) {
relay: () => ({ snapshot: () => ({ status: "ready", session }) }) as never,
addTool: (tool) => {
tools.set(tool.name, (args) =>
- tool.call(client as never, { channel: chat } as never, args),
+ tool.call(client as never, { channel: where } as never, args),
);
},
});
@@ -215,6 +245,25 @@ it("creates in the named place as its owner, via the agent, posting nothing", as
expect(posted).toHaveLength(0);
});
+it("never puts a task in a DM or a huddle", async () => {
+ // Talking in a DM, the agent is asked for a place instead.
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64))],
+ dm,
+ );
+ await expect(call("tasks_create", { title: "Fix it" })).rejects.toThrow(
+ "never a DM or a huddle. Ask which place it should go in",
+ );
+ await expect(
+ call("tasks_create", { title: "Fix it", place: huddle }),
+ ).rejects.toThrow("never a DM or a huddle");
+ await expect(call("tasks_update", { id, place: dm })).rejects.toThrow(
+ "never a DM or a huddle",
+ );
+ expect(signed).toHaveLength(0);
+});
+
it("returns a clear match instead of creating a duplicate", async () => {
const { call, signed } = setup(
async () => "",
@@ -363,6 +412,52 @@ it("refuses an assignee who can't see the task", async () => {
expect(signed).toHaveLength(0);
});
+it("counts a project's people only where the channel lets them in", async () => {
+ const there = (home: string) => () => [head("d".repeat(64), [], { home })];
+ // Filed in the project as usual: Leo, only in the project, can see it.
+ const open = setup(async () => "", there(filed));
+ await open.call("tasks_update", { id, assignees: [leo] });
+ expect(assignees(open.signed[0])).toEqual([leo]);
+ // Project access off: he can't.
+ const closed = setup(async () => "", there(shut));
+ await expect(
+ closed.call("tasks_update", { id, assignees: [leo] }),
+ ).rejects.toThrow("Leo can't see this task");
+ expect(closed.signed).toHaveLength(0);
+});
+
+it("names a project member a move shuts out", async () => {
+ const { call, signed } = setup(
+ async () => "",
+ () => [head("d".repeat(64), [["assignee", leo]], { home: filed })],
+ );
+ const preview = await call("tasks_update", { id, place: shut });
+ expect(preview).toContain(
+ "Leo can't see #payroll-review and will be unassigned.",
+ );
+ expect(preview).toContain("Payments");
+ const confirm = /confirm "([^"]+)"/.exec(preview)?.[1];
+ await call("tasks_update", { id, place: shut, confirm });
+ expect(assignees(signed[0])).toEqual([]);
+});
+
+it("shows the relay's reason when it refuses an assignee anyway", async () => {
+ const { call } = setup(
+ async () => {
+ throw new PublishRejected(
+ "rejected",
+ "invalid: assignee can't read this task",
+ );
+ },
+ () => [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",
+ );
+});
+
it("previews a move, by place, and moves only with its confirm", async () => {
const { call, signed } = setup(
async () => "",
@@ -462,6 +557,54 @@ it("reapplies an update over someone else's newer save", async () => {
expect(tagOf(signed[1], "status")).toBe("in_progress");
});
+it("never retries as the owner: a task moved where the agent can't read stays unclosed", async () => {
+ let current = head("d".repeat(64), [["status", "todo"]], {
+ title: "Launch checklist",
+ });
+ let calls = 0;
+ const { call, signed } = setup(
+ async () => {
+ if (calls++ === 0) {
+ // Moved into an owner-only chat while the agent was closing it.
+ current = head("c".repeat(64), [["status", "todo"]], {
+ home: secret,
+ title: "Launch checklist",
+ });
+ throw new PublishRejected("rejected", "conflict: stale prev");
+ }
+ return "";
+ },
+ () => [current],
+ );
+ const closing = call("tasks_update", {
+ id,
+ status: "done",
+ evidence: "Shipped",
+ });
+ await expect(closing).rejects.toThrow("Nothing was saved");
+ await expect(closing).rejects.not.toThrow("Launch checklist");
+ expect(artifacts(signed)).toHaveLength(1);
+});
+
+it("stops when a task it can still read moved during its change", async () => {
+ let current = head("d".repeat(64), [["status", "todo"]]);
+ let calls = 0;
+ const { call, signed } = setup(
+ async () => {
+ if (calls++ === 0) {
+ current = head("c".repeat(64), [["status", "todo"]], { home: chat });
+ throw new PublishRejected("rejected", "conflict: stale prev");
+ }
+ return "";
+ },
+ () => [current],
+ );
+ await expect(
+ call("tasks_update", { id, status: "in_progress" }),
+ ).rejects.toThrow("Someone moved this task");
+ expect(artifacts(signed)).toHaveLength(1);
+});
+
it("tells the agent which id to check after an unclear create", async () => {
const { call, signed } = setup(
async () => {
diff --git a/src/bundled/tasks/tools.ts b/src/bundled/tasks/tools.ts
index b8cf6b7b83..80114077f0 100644
--- a/src/bundled/tasks/tools.ts
+++ b/src/bundled/tasks/tools.ts
@@ -27,6 +27,7 @@ import {
} from "./model";
import {
accessChange,
+ canHoldTasks,
type Place,
placeLabel,
projectOf,
@@ -222,13 +223,18 @@ export function addTaskTools(agents: Agents) {
return task;
}
- /** Throws unless the agent can read place `id`. */
+ /** Throws unless the agent can read place `id` and a task can live there. */
async function readable(reads: TaskSource, id: string, signal: AbortSignal) {
const places = await readPlaces(reads, [id], signal);
- if (!places.has(id))
+ const place = places.get(id);
+ if (!place)
throw new Error(
"You can't see that place, so a task can't go there. Nothing changed.",
);
+ if (!canHoldTasks(place))
+ throw new Error(
+ "A task can live in a project, channel or chat that isn't archived, never a DM or a huddle. Ask which place it should go in. Nothing changed.",
+ );
return places;
}
@@ -244,6 +250,7 @@ export function addTaskTools(agents: Agents) {
revision?: string,
) {
let task = await current(reads, id, signal);
+ const from = task.home;
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
signal.throwIfAborted();
if (revision && task.revision !== revision)
@@ -254,9 +261,15 @@ 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, edit(task), target, signal);
+ const result = await saveTask(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.
task = result.current;
+ if (task.home !== from)
+ throw new Error(
+ "Someone moved this task while you were changing it. Nothing changed; read it again with tasks_find.",
+ );
}
throw new Error("Others keep changing this task. Try again.");
}
@@ -425,6 +438,7 @@ export function addTaskTools(agents: Agents) {
const id = crypto.randomUUID();
const result = await saveTask(
session,
+ reads,
fields,
{ op: "create", home, id, via: client.pubkey },
signal,
@@ -438,7 +452,7 @@ export function addTaskTools(agents: Agents) {
const chat = context.channel;
const linked =
args.link !== false && isChannelId(chat) && chat !== home
- ? await setLink(session, id, chat, true, signal).then(
+ ? await setLink(session, reads, id, chat, true, signal).then(
() =>
"\nLinked this conversation; only people who can read it see that.",
() => "\nCouldn't link this conversation.",
From 4f35b8a7fea6c0fd6238b8f97925e5699026d955 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 13:32:42 -0800
Subject: [PATCH 15/18] fix(tasks): keep the place rule where every create and
move passes
The store now refuses to create or move a task into a place that can't
hold one, so no screen or tool can skip the rule. The editor applies the
same rule to its starting place: from a DM or a huddle, "Where it lives"
starts empty and Save waits for a choice. The Tasks button is hidden in
DMs and huddles, where its panel could only be empty.
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/TaskView.test.tsx | 34 +++++++++++++++++-
src/bundled/tasks/TaskView.tsx | 13 ++++---
src/bundled/tasks/index.tsx | 16 +++++++++
src/bundled/tasks/places.ts | 5 ++-
src/bundled/tasks/store.test.ts | 55 +++++++++++++++++++++++++++--
src/bundled/tasks/store.ts | 11 ++++++
6 files changed, 126 insertions(+), 8 deletions(-)
diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx
index 0139545d0c..9484b03fec 100644
--- a/src/bundled/tasks/TaskView.test.tsx
+++ b/src/bundled/tasks/TaskView.test.tsx
@@ -35,6 +35,7 @@ const theirs = revision("c".repeat(64), "Their title");
const project = "33333333-3333-4333-8333-333333333333";
const launch = "44444444-4444-4444-8444-444444444444";
const leo = "c".repeat(64);
+const dm = "55555555-5555-4555-8555-555555555555";
type Answer = ChannelReachState;
const asking: Answer = { status: "loading" };
@@ -64,7 +65,13 @@ function setup(
created_at: 1,
kind: 39000,
content: "",
- tags: [["d", d], ["name", name], ["private"], ...extra],
+ tags: [
+ ["d", d],
+ ["name", name],
+ ["t", extra.find(([key]) => key === "t")?.[1] ?? "stream"],
+ ["private"],
+ ...extra.filter(([key]) => key !== "t"),
+ ],
});
const session = {
viewer,
@@ -95,6 +102,7 @@ function setup(
metadata(home, "design", [["parent", project]]),
metadata(project, "Payments"),
metadata(launch, "launch"),
+ metadata(dm, "", [["t", "dm"]]),
].filter((event) =>
(filter["#d"] as string[]).includes(event.tags[0]?.[1] ?? ""),
);
@@ -267,3 +275,27 @@ it("won't create a task where the relay says the viewer can't post", async () =>
await new Promise((resolve) => setTimeout(resolve, 0));
expect(signed).toHaveLength(0);
});
+
+it("starts a new task from a DM with no place, and won't create until one is picked", async () => {
+ const { session, signed } = setup(async () => "", {
+ [home]: opened(true),
+ [dm]: opened(true),
+ });
+ render(
+ {}}
+ onSaved={() => {}}
+ />,
+ );
+ fireEvent.change(screen.getByLabelText("Title"), {
+ target: { value: "From a DM" },
+ });
+ const create = screen.getByRole("button", { name: "Create task" });
+ await vi.waitFor(() => expect(create).toBeDisabled());
+ expect(screen.getByText("Choose a place")).toBeInTheDocument();
+ fireEvent.click(create);
+ expect(signed).toHaveLength(0);
+});
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index 08562099e9..f3d0cc5d10 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -59,6 +59,7 @@ import {
} from "./model";
import {
accessChange,
+ canHoldTasks,
type Place,
placeLabel,
projectOf,
@@ -871,7 +872,12 @@ function TaskEditor({
const [draft, setDraft] = useState(
kept?.fields ?? (task ? fieldsOf(task) : empty),
);
- const [home, setHome] = useState(kept?.home ?? startHome);
+ const [picked, setHome] = useState(kept?.home ?? startHome);
+ const startPlaces = usePlaces(session, picked ? [picked] : []);
+ const chosen = picked ? startPlaces.get(picked) : undefined;
+ // The store's rule for where a task can live: from a DM or a huddle, the
+ // place starts empty and must be chosen.
+ const home = chosen && !canHoldTasks(chosen) ? undefined : picked;
// The revision this draft builds on; a conflict moves it to theirs.
const [base, setBase] = useState(kept ? kept.base : task);
// One id for a new task across retries, so a create that landed unseen
@@ -888,8 +894,6 @@ function TaskEditor({
const files = useRef(null);
// Only a place the relay says the viewer can post in takes a new task.
const target = usePlaceAccess(session, task ? undefined : home);
- const startPlaces = usePlaces(session, home ? [home] : []);
- const chosen = home ? startPlaces.get(home) : undefined;
const problem =
!task && home
? placeProblem(
@@ -1011,6 +1015,7 @@ function TaskEditor({
description="People who can see this place can see the task."
value={home ?? ""}
placeholder="Choose a place"
+ required
groups={choices.groups}
onValueChange={setHome}
/>
@@ -1077,7 +1082,7 @@ function TaskEditor({
type="submit"
variant="prominent"
loading={saving}
- disabled={busy || !draft.title.trim()}
+ disabled={busy || !draft.title.trim() || (!task && !where)}
>
{task ? "Save" : "Create task"}
diff --git a/src/bundled/tasks/index.tsx b/src/bundled/tasks/index.tsx
index 3cc7bfbdfe..36557c150c 100644
--- a/src/bundled/tasks/index.tsx
+++ b/src/bundled/tasks/index.tsx
@@ -3,11 +3,13 @@ import type {
ChannelLauncherProps,
PanelProps,
} from "../../features/panels/service";
+import { useChannelRoster } from "../../features/relay/react";
import type { RelaySnapshot } from "../../features/relay/service";
import type { PluginModule } from "../../plugins/api";
import { ClipboardCheckIcon } from "../../shared/design-system/icons/index";
import { IconButton } from "../../shared/design-system/ui/IconButton";
import inlineStyles from "../../shared/InlineReference.module.css";
+import { canHoldTasks } from "./places";
import { taskLinkId, taskRoute } from "./route";
import { TaskLink } from "./TaskLink";
import { TasksPage } from "./TasksPage";
@@ -74,6 +76,20 @@ export const apply: PluginModule["apply"] = (ctx) => {
pressed,
available,
}: ChannelLauncherProps) {
+ const state = useSyncExternalStore(ctx.relay.subscribe, ctx.relay.snapshot);
+ const { channels } = useChannelRoster(state.session.channels);
+ const channel =
+ state.scope === context.scope
+ ? channels.find((item) => item.id === context.channelId)
+ : undefined;
+ // No task can live in a DM or a huddle, so their panel could only be
+ // empty. An archived place keeps it: its tasks are still there to read.
+ if (
+ channel &&
+ !channel.pending &&
+ !canHoldTasks({ type: channel.channelType, huddle: channel.huddle })
+ )
+ return null;
return (
,
ids: Iterable,
diff --git a/src/bundled/tasks/store.test.ts b/src/bundled/tasks/store.test.ts
index 644e685230..884a75a0e0 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 { readTask, saveTask } from "./store";
+import { NOT_A_TASK_PLACE, readTask, saveTask } from "./store";
const viewer = "a".repeat(64);
const id = "11111111-1111-4111-8111-111111111111";
@@ -32,6 +32,28 @@ const head = (revision: string, content: object = {}, at = home) => ({
],
});
+const relayKey = "e".repeat(64);
+const dm = "44444444-4444-4444-8444-444444444444";
+const huddle = "55555555-5555-4555-8555-555555555555";
+const place = (d: string, more: string[][] = [["t", "stream"]]) => ({
+ id: d.replace(/-/g, "").padEnd(64, "0"),
+ pubkey: relayKey,
+ sig: "",
+ created_at: 5,
+ kind: 39000,
+ content: "",
+ tags: [["d", d], ["name", d.slice(0, 4)], ["private"], ...more],
+});
+const places = [
+ place(home),
+ place(away),
+ place(dm, [["t", "dm"]]),
+ place(huddle, [
+ ["t", "stream"],
+ ["about", `Buzz Huddle (buzz.huddles/v1)\nparent:${home}`],
+ ]),
+];
+
function session(publish: () => Promise, heads: object[] = []) {
const sign = vi.fn(async (template: object) => ({
...template,
@@ -39,12 +61,20 @@ function session(publish: () => Promise, heads: object[] = []) {
pubkey: viewer,
sig: "",
}));
- const read = vi.fn(async () => heads);
+ const read = vi.fn(
+ async (filters: { kinds?: number[]; "#d"?: string[] }[]) =>
+ filters[0]?.kinds?.includes(39000)
+ ? places.filter((event) =>
+ filters[0]?.["#d"]?.includes(event.tags[0]?.[1] ?? ""),
+ )
+ : heads,
+ );
return {
sign,
read,
session: {
viewer,
+ relayAuthor: relayKey,
snapshotRead: read,
configArtifactWriter: { sign, publish: vi.fn(publish) },
} as unknown as RelaySession,
@@ -165,3 +195,24 @@ it("finds a moved task when its old home no longer has it", async () => {
]);
expect(read.mock.calls[1]?.[0]?.[0]).not.toHaveProperty("#h");
});
+
+it("never creates or moves a task into a DM or a huddle, whoever calls", async () => {
+ const { session: relay, sign } = session(async () => "");
+ const base = taskOf(head("d".repeat(64))) as Task;
+ for (const place of [dm, huddle]) {
+ await expect(
+ saveTask(relay, relay, fields, { op: "create", home: place, id }),
+ ).rejects.toThrow(NOT_A_TASK_PLACE);
+ await expect(
+ saveTask(relay, relay, fields, { op: "move", base, home: place }),
+ ).rejects.toThrow(NOT_A_TASK_PLACE);
+ }
+ await expect(
+ saveTask(relay, relay, fields, {
+ op: "create",
+ home: "66666666-6666-4666-8666-666666666666",
+ id,
+ }),
+ ).rejects.toThrow("You can’t see that place.");
+ expect(sign).not.toHaveBeenCalled();
+});
diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts
index 89c2e4efa6..80b9c8ea18 100644
--- a/src/bundled/tasks/store.ts
+++ b/src/bundled/tasks/store.ts
@@ -18,6 +18,7 @@ import {
taskOf,
taskTags,
} from "./model";
+import { canHoldTasks, readPlaces } from "./places";
export type TasksState = Readonly<{
status: "loading" | "live" | "error";
@@ -208,6 +209,9 @@ export type SaveTarget =
* keeps one `id` across retries, so a create that landed unseen is found, not
* made twice. Whatever the save reads back, to see whose revision won, comes
* through `reader` alone: an agent's tool passes the agent's own reads. */
+export const NOT_A_TASK_PLACE =
+ "A task can live in a project, channel or chat that isn’t archived, never a DM or a huddle. Nothing was saved.";
+
export async function saveTask(
session: RelaySession,
reader: TaskSource,
@@ -226,6 +230,13 @@ export async function saveTask(
// The signer of the first revision, carried forward as the relay checks.
const creator = base ? base.creator : viewer;
const via = base ? base.via : target.op === "create" ? target.via : undefined;
+ // Every screen and tool creates and moves through here, so this is where
+ // the rule for where a task can live is kept.
+ if (target.op !== "update") {
+ const place = (await readPlaces(reader, [home], signal)).get(home);
+ 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,
From e224935d0111485cfe7b6b4e3e03759363176798 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 13:58:52 -0800
Subject: [PATCH 16/18] chore(tasks): put saveTask's comment back above it
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/store.ts | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/bundled/tasks/store.ts b/src/bundled/tasks/store.ts
index 80b9c8ea18..225580ea88 100644
--- a/src/bundled/tasks/store.ts
+++ b/src/bundled/tasks/store.ts
@@ -205,13 +205,13 @@ export type SaveTarget =
| Readonly<{ op: "update"; base: Task }>
| Readonly<{ op: "move"; base: Task; home: string }>;
+export const NOT_A_TASK_PLACE =
+ "A task can live in a project, channel or chat that isn’t archived, never a DM or a huddle. Nothing was saved.";
+
/** Saves one revision, signed by the session's viewer. A new task's caller
* keeps one `id` across retries, so a create that landed unseen is found, not
* made twice. Whatever the save reads back, to see whose revision won, comes
* through `reader` alone: an agent's tool passes the agent's own reads. */
-export const NOT_A_TASK_PLACE =
- "A task can live in a project, channel or chat that isn’t archived, never a DM or a huddle. Nothing was saved.";
-
export async function saveTask(
session: RelaySession,
reader: TaskSource,
From e57ded742a00109b7d08e2ca1a92092aae3adac3 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 14:01:55 -0800
Subject: [PATCH 17/18] fix(tasks): say read-only once, under Comments
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/TaskComments.test.tsx | 1 +
src/bundled/tasks/TaskView.test.tsx | 3 ++-
src/bundled/tasks/TaskView.tsx | 3 ---
3 files changed, 3 insertions(+), 4 deletions(-)
diff --git a/src/bundled/tasks/TaskComments.test.tsx b/src/bundled/tasks/TaskComments.test.tsx
index 7b695d306b..34b4bd28ad 100644
--- a/src/bundled/tasks/TaskComments.test.tsx
+++ b/src/bundled/tasks/TaskComments.test.tsx
@@ -127,6 +127,7 @@ it("offers a view-only person no way to start comments", async () => {
});
await answer(handles, home, { status: "open", post: false, joined: false });
expect(screen.getByText("No comments yet.")).toBeInTheDocument();
+ expect(screen.getByText("Read-only access")).toBeInTheDocument();
expect(screen.queryByRole("button")).toBeNull();
});
diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx
index 9484b03fec..e645d10ded 100644
--- a/src/bundled/tasks/TaskView.test.tsx
+++ b/src/bundled/tasks/TaskView.test.tsx
@@ -183,7 +183,8 @@ it("shows someone view-only there no edit controls, whatever their list says", (
for (const name of ["Edit", "Move…", "More", "Link this chat", "Unlink"])
expect(screen.queryByRole("button", { name })).toBeNull();
expect(screen.queryByLabelText("Status")).toBeNull();
- expect(screen.getByText("Read-only access")).toBeInTheDocument();
+ // Comments say it once, where they'd try to act.
+ expect(screen.queryByText("Read-only access")).toBeNull();
});
it("shows neither edit controls nor read-only while the relay is asked", () => {
diff --git a/src/bundled/tasks/TaskView.tsx b/src/bundled/tasks/TaskView.tsx
index f3d0cc5d10..25338d97b8 100644
--- a/src/bundled/tasks/TaskView.tsx
+++ b/src/bundled/tasks/TaskView.tsx
@@ -262,9 +262,6 @@ function TaskDetails({
{statusLabels[task.status]}
- {access === "view" ? (
- Read-only access
- ) : null}
>
)}
From 735a96f8cfe7fed769516c5a7256d219352fad97 Mon Sep 17 00:00:00 2001
From: morgmart <98432065+morgmart@users.noreply.github.com>
Date: Mon, 16 Nov 2026 14:36:42 -0800
Subject: [PATCH 18/18] fix(tasks): tell a banned viewer so under Comments
Co-authored-by: Carl
Co-Authored-By: Claude Opus 5.5
Signed-off-by: morgmart <98432065+morgmart@users.noreply.github.com>
---
src/bundled/tasks/TaskComments.test.tsx | 14 ++++++++++++++
src/bundled/tasks/TaskComments.tsx | 7 +++++++
2 files changed, 21 insertions(+)
diff --git a/src/bundled/tasks/TaskComments.test.tsx b/src/bundled/tasks/TaskComments.test.tsx
index 34b4bd28ad..f04a519078 100644
--- a/src/bundled/tasks/TaskComments.test.tsx
+++ b/src/bundled/tasks/TaskComments.test.tsx
@@ -168,3 +168,17 @@ it("says so where the community has no task comments", () => {
screen.getByText("Comments aren’t available in this community yet."),
).toBeInTheDocument();
});
+
+it("says plainly that a banned viewer is banned, with nothing to retry", async () => {
+ const { handles, view } = setup();
+ view();
+ await answer(handles, conversation, {
+ status: "unavailable",
+ reason: "banned",
+ });
+ await answer(handles, home, { status: "unavailable", reason: "banned" });
+ expect(
+ screen.getByText("You’re banned from this community."),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole("button")).toBeNull();
+});
diff --git a/src/bundled/tasks/TaskComments.tsx b/src/bundled/tasks/TaskComments.tsx
index 136d8ed2b5..3d02f6d1a7 100644
--- a/src/bundled/tasks/TaskComments.tsx
+++ b/src/bundled/tasks/TaskComments.tsx
@@ -9,6 +9,7 @@ import {
} from "../../features/conversation/Conversation";
import type { ConversationHostServices } from "../../features/conversation/ConversationHost";
import { MessageManagementStatus } from "../../features/messages/MessageManagement";
+import { BANNED } from "../../features/relay/channel-access";
import { useChannelWindow } from "../../features/relay/react";
import type { RelaySession } from "../../features/relay/session";
import { Button } from "../../shared/design-system/ui/Button";
@@ -86,6 +87,12 @@ export function TaskComments({
Loading comments…
);
+ // A ban is the relay's answer, not a failure: nothing to try again.
+ if (
+ reason === "banned" ||
+ (home.state.status === "unavailable" && home.state.reason === "banned")
+ )
+ return {BANNED}
;
// Either question going unanswered is a failure to show, never "no
// comments yet": the home's answer decides who may start them.
const homeFailed =