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" 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/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..bd6348f3a1 --- /dev/null +++ b/src/bundled/tasks/README.md @@ -0,0 +1,18 @@ +# Tasks + +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, 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, or to find what you should work on. + +- 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 new file mode 100644 index 0000000000..9ece83053b --- /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 "todo": + return ; + case "in_progress": + return ; + case "done": + return ; + case "cancelled": + return ; + } +} diff --git a/src/bundled/tasks/TaskComments.test.tsx b/src/bundled/tasks/TaskComments.test.tsx new file mode 100644 index 0000000000..f04a519078 --- /dev/null +++ b/src/bundled/tasks/TaskComments.test.tsx @@ -0,0 +1,184 @@ +// @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.getByText("Read-only access")).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("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( + 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 new file mode 100644 index 0000000000..3d02f6d1a7 --- /dev/null +++ b/src/bundled/tasks/TaskComments.tsx @@ -0,0 +1,188 @@ +// 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 } from "react"; +import { + ConversationChannel, + ConversationComposer, + ConversationTimeline, +} 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"; +import type { Task } from "./model"; +import { useReach } from "./react"; +import styles from "./Tasks.module.css"; + +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… +

+ ); + // 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 = + home.state.status === "unavailable" && home.state.reason === "failed"; + if (reason === "failed" || homeFailed) + return ( +
+

Couldn’t load comments.

+ +
+ ); + // 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 ? ( + + ) : 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}

+ +
+ ); + if (window.status !== "ready" && !window.rows.length) + return ( +

+ Loading comments… +

+ ); + 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}` : ""} + +
+ +
+
+ ); +} diff --git a/src/bundled/tasks/TaskView.test.tsx b/src/bundled/tasks/TaskView.test.tsx new file mode 100644 index 0000000000..e645d10ded --- /dev/null +++ b/src/bundled/tasks/TaskView.test.tsx @@ -0,0 +1,302 @@ +// @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 type { ChannelReachState } from "../../features/relay/channel-reach"; +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"; +import { TaskView } from "./TaskView"; + +afterEach(cleanup); + +const viewer = "a".repeat(64); +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: 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); +const dm = "55555555-5555-4555-8555-555555555555"; + +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, + answers: Record = { [home]: opened(true) }, +) { + const signed: { tags: string[][] }[] = []; + const channels: ChannelSummary[] = [ + { id: home, name: "design", channelType: "stream", viewerRole: "member" }, + { id: launch, name: "launch", channelType: "stream", readOnly: true }, + ]; + 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], + ["t", extra.find(([key]) => key === "t")?.[1] ?? "stream"], + ["private"], + ...extra.filter(([key]) => key !== "t"), + ], + }); + const session = { + viewer, + relayAuthor: "e".repeat(64), + media: () => undefined, + profiles: { + snapshot: () => profiles, + subscribe: () => () => {}, + ensure: async () => {}, + }, + channels: { + ensureList: () => () => {}, + subscribeList: () => () => {}, + list: () => list, + reach: (channel: string) => ({ + snapshot: () => answers[channel] ?? asking, + subscribe: () => () => {}, + retry() {}, + release() {}, + }), + }, + 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"), + metadata(dm, "", [["t", "dm"]]), + ].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); + 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( + {}} + 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 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…", "More", "Link this chat", "Unlink"]) + expect(screen.queryByRole("button", { name })).toBeNull(); + expect(screen.queryByLabelText("Status")).toBeNull(); + // 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", () => { + 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 where the relay says the viewer can post, posting nothing", async () => { + const { session, signed } = setup(async () => ""); + const onSaved = vi.fn(); + render( + {}} + onSaved={onSaved} + />, + ); + fireEvent.change(screen.getByLabelText("Title"), { + target: { value: "From this chat" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Create task" })); + await vi.waitFor(() => expect(onSaved).toHaveBeenCalled()); + expect(signed).toHaveLength(1); + 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); +}); + +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 new file mode 100644 index 0000000000..25338d97b8 --- /dev/null +++ b/src/bundled/tasks/TaskView.tsx @@ -0,0 +1,1089 @@ +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 type { RelaySession } from "../../features/relay/session"; +import { avatarMedia } from "../../shared/avatar-source"; +import { + ChatCircleIcon, + HashIcon, + ImageIcon, + LinkIcon, + 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 { 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"; +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, + type TaskFields, + type TaskImage, + type TaskStatus, +} from "./model"; +import { + accessChange, + canHoldTasks, + 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"; + +const empty: TaskFields = { + title: "", + description: "", + status: "todo", + images: [], + 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; +}>; + +const fieldsOf = (task: Task): TaskFields => ({ + title: task.title, + description: task.description, + status: task.status, + images: task.images, + assignees: task.assignees, +}); + +const message = (reason: unknown, fallback: string) => + reason instanceof Error ? reason.message : fallback; + +export type TaskViewProps = { + session: RelaySession; + /** The task's current revision; undefined starts a new task. */ + 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; + onSaved(task: Task): void; + /** 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; +}; + +/** 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, task } = props; + const [editing, setEditing] = useState(!task || !!props.draft); + if (editing || !task) + return ( + { + props.onDraftChange?.(undefined); + setEditing(false); + if (!saved && !task) props.onDiscard?.(); + }} + /> + ); + return ( + setEditing(true)} + /> + ); +} + +function TaskDetails({ + session, + task, + currentChat, + openConversation, + onSaved, + edit, + comments, +}: TaskViewProps & { task: Task; edit(): void }) { + const notify = useToastNotification(); + // 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]); + 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, + 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] } : {}), + }); + }; + return ( +
+
+

{task.title}

+ +

+ {project.id && project.id !== task.home + ? `${project.name ?? "Private project"}${home ? ` · ${placeLabel(home, places)}` : ""}` + : home + ? placeLabel(home, places) + : ""} +

+
+
+ {canEdit ? ( + <> + + ) : ( +

+ There’s nowhere else you can move this task. +

+ )} + {problem ? ( +
+

{problem}

+ {target.access === "failed" ? ( + + ) : null} +
+ ) : null} + {problem === undefined && change?.gain.length ? ( +

+ Everyone in {placeList(change.gain, named)} will be able to see this + task and its comments. +

+ ) : null} + {problem === undefined && change?.lose.length ? ( +

+ 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 ? ( +

+ {error} +

+ ) : null} + + ); +} + +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, + home: startHome, + draft: kept, + onDraftChange, + onSaved, + onDone, +}: TaskViewProps & { onDone(saved: boolean): void }) { + const inputId = useId(); + const choices = useHomeChoices(session); + const [draft, setDraft] = useState( + kept?.fields ?? (task ? fieldsOf(task) : empty), + ); + 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 + // is found rather than made twice. + const [taskId] = useState(() => kept?.id ?? task?.id ?? crypto.randomUUID()); + useEffect( + () => onDraftChange?.({ fields: draft, base, id: taskId, home }), + [draft, base, taskId, home, onDraftChange], + ); + const [conflict, setConflict] = useState(); + const [error, setError] = useState(""); + const [saving, setSaving] = useState(false); + const [uploading, setUploading] = useState(false); + 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 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 save: SaveTarget | undefined = base + ? { op: "update", base } + : where + ? { op: "create", home: where, id: taskId } + : undefined; + if (!save) { + setError(problem || "Choose where this task lives."); + return; + } + setError(""); + setSaving(true); + try { + const result = await saveTask(session, session, draft, save); + if (result.status === "saved") { + onSaved(result.task); + onDone(true); + } else { + // Keep the person's text; the next Save is a deliberate overwrite. + setConflict(result.current); + setBase(result.current); + } + } catch (reason) { + setError(message(reason, "Couldn’t save the task.")); + } finally { + setSaving(false); + } + }; + const upload = async (list: FileList | null) => { + // 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/"), + ); + 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 ( +
{ + event.preventDefault(); + void submit(); + }} + onPaste={(event) => { + if (event.clipboardData.files.length) { + event.preventDefault(); + void upload(event.clipboardData.files); + } + }} + > + {conflict ? ( +
+

+ Someone else changed this task. Your text is kept. Saving now + replaces their version. +

+ +
+ ) : null} + + update({ title: event.target.value })} + /> + + {task ? null : ( +