From e363f3308c7ffa25f555e226739be83bf3748179 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Mon, 19 Oct 2026 01:06:04 +1100 Subject: [PATCH 1/2] Add portable TaskNotes task creation to Planner --- README.md | 21 ++- docs/capability-v2-migration.md | 13 +- public/.well-known/mdbase-app.json | 3 +- scripts/planner-manifest.mjs | 3 +- scripts/planner-manifest.test.mjs | 4 +- src/components/gantt-chart.tsx | 2 +- src/components/planner.create.test.tsx | 164 ++++++++++++++++++++ src/components/planner.empty.test.tsx | 155 +++++++++++++++++++ src/components/planner.native.test.tsx | 39 +++++ src/components/planner.test.tsx | 1 + src/components/planner.tsx | 82 ++++++++-- src/components/task-create-dialog.tsx | 110 ++++++++++++++ src/data/connect.test.ts | 2 +- src/data/demo-repository.ts | 18 +++ src/data/mdbase-repository.ts | 25 +++ src/data/next-planner-repository.test.ts | 184 +++++++++++++++++++++++ src/data/next-planner-repository.ts | 66 ++++++++ src/data/outcome.ts | 5 +- src/data/task-creation.ts | 55 +++++++ src/data/tasknotes-handoff.ts | 17 +++ src/domain/task.ts | 2 + src/generated-mdbase-app.json | 3 +- 22 files changed, 944 insertions(+), 30 deletions(-) create mode 100644 src/components/planner.create.test.tsx create mode 100644 src/components/planner.empty.test.tsx create mode 100644 src/components/task-create-dialog.tsx create mode 100644 src/data/task-creation.ts create mode 100644 src/data/tasknotes-handoff.ts diff --git a/README.md b/README.md index 4759962..ae662e2 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,17 @@ off to Planner for timeline work. ## Timeline interactions +Use **Add task** in the header, or **Add your first task** in an empty +collection. Planner creates a portable TaskNotes task through the collection's +implementing `tasknotes.task` type, using its default status and priority. The +new task is shared with TaskNotes, not a separate Planner task copy. Set its +schedule and other planning properties in the inspector after adding it. + +An empty collection shows **No tasks yet**. If a saved view or the current +filters hide tasks, Planner instead prompts you to change the view or filters. +A secondary TaskNotes link opens the same collection in the matching LAB, +staging, or production app; TaskNotes still owns its own sign-in and approval. + - Use the minus and plus controls to move between quarter, month, fortnight, week, work-week, day, hour, and quarter-hour scales. `Ctrl`/`Cmd` + wheel zooms around the pointer. @@ -117,7 +128,7 @@ local callback URLs are never deployed. The application requests full-collection authorization because mdbase saved views are collection-level resources. Task records are still selected and mutated only through `tasknotes.task`. Planner declares capability contract v2 -with required atomic groups `collection.read`, `records.edit`, `views.manage`, +with required atomic groups `collection.read`, `records.create`, `records.edit`, `views.manage`, and `definitions.manage` for these workflows: - inspect the collection contract @@ -125,14 +136,16 @@ and `definitions.manage` for these workflows: during authorization - query and read TaskNotes records - watch for collection changes -- update TaskNotes records +- create and update TaskNotes records - list and execute saved views - read, create, and update saved-view sources Atomic consent also grants record validation/rename, type reading/creation, and saved-view source deletion. Saved-view deletion is not record deletion, and no -independent operation permission is requested. Record creation/deletion, files, -offline replicas, and background scheduling remain excluded. See +independent operation permission is requested. Task creation also requires the +`add` file action; an older approval without it needs renewed consent. Record +deletion, arbitrary file operations, offline replicas, and background scheduling +remain excluded. See [the migration guard and rollout order](docs/capability-v2-migration.md): the vendored beta96 v2 candidate SDK is source-bound development evidence, not a published or signed release. This v2 draft must not deploy before the qualified v2 writer. diff --git a/docs/capability-v2-migration.md b/docs/capability-v2-migration.md index be5a518..353006b 100644 --- a/docs/capability-v2-migration.md +++ b/docs/capability-v2-migration.md @@ -77,7 +77,8 @@ and no optional capabilities: | Group | Consent meaning | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | | `collection.read` | Describe, changes, read/query, list/execute views, read view sources, validate records, and read types. | -| `records.edit` | Update and rename records; no record creation or deletion. | +| `records.create` | Create TaskNotes tasks through their implementing record contract. | +| `records.edit` | Update and rename records; no record deletion. | | `views.manage` | Create, update, and delete saved-view sources. Whole-group consent intentionally includes saved-view deletion, not record deletion. | | `definitions.manage` | Create/update types and assess/apply type packs. | @@ -87,10 +88,12 @@ deletion. These are atomic group meanings, not independently requested operation permissions. Setup assessment/application is handled by Connect's separate setup flow, with the existing provisions unchanged. -No `records.create`, `records.delete`, `offline.replica`, or -`background.schedule` is requested. Collection file actions `list`, `read`, -`replace` and `move` are declared because next accounts approve -`collection.read` and `records.edit` together with their matching file actions. Full-collection authorization remains +Planner now requests `records.create` for its add-task workflow, together with +the `add` file action. Existing approvals must grant this expanded declaration; +the app cannot treat an old edit-only grant as creation authority. +No `records.delete`, `offline.replica`, or `background.schedule` is requested. +Collection file actions `list`, `read`, `add`, `replace` and `move` accompany +`collection.read`, `records.create` and `records.edit`. Full-collection authorization remains necessary for Bases, while the application continues to select and mutate task records through `tasknotes.task` only. No app capability aliases or fabricated SDK groups were introduced; session state handling remains SDK-owned. diff --git a/public/.well-known/mdbase-app.json b/public/.well-known/mdbase-app.json index cc3a861..3010247 100644 --- a/public/.well-known/mdbase-app.json +++ b/public/.well-known/mdbase-app.json @@ -22,6 +22,7 @@ "contract_version": 2, "required": [ "collection.read", + "records.create", "records.edit", "views.manage", "definitions.manage" @@ -29,7 +30,7 @@ }, "access": "full_collection", "files": { - "required": ["list", "read", "replace", "move"], + "required": ["list", "read", "add", "replace", "move"], "scope": { "kind": "collection" } }, "configuration": [ diff --git a/scripts/planner-manifest.mjs b/scripts/planner-manifest.mjs index 59e8d03..6213457 100644 --- a/scripts/planner-manifest.mjs +++ b/scripts/planner-manifest.mjs @@ -9,6 +9,7 @@ export { TASKNOTES_TYPE_PACK_VERSION } from "./canonical-task-pack.mjs"; export const requiredCapabilities = Object.freeze([ "collection.read", + "records.create", "records.edit", "views.manage", "definitions.manage", @@ -46,7 +47,7 @@ export async function buildPlannerManifest({ appUrl, development = false }) { // Next accounts approve each record capability together with its file // actions: reading needs list and read, editing needs replace and move. files: { - required: ["list", "read", "replace", "move"], + required: ["list", "read", "add", "replace", "move"], scope: { kind: "collection" }, }, configuration: [ diff --git a/scripts/planner-manifest.test.mjs b/scripts/planner-manifest.test.mjs index 5898e36..b5d36e9 100644 --- a/scripts/planner-manifest.test.mjs +++ b/scripts/planner-manifest.test.mjs @@ -21,13 +21,14 @@ describe("Planner mdbase manifest", () => { contract_version: 2, required: [ "collection.read", + "records.create", "records.edit", "views.manage", "definitions.manage", ], }, files: { - required: ["list", "read", "replace", "move"], + required: ["list", "read", "add", "replace", "move"], scope: { kind: "collection" }, }, }); @@ -115,6 +116,7 @@ describe("Planner mdbase manifest", () => { contract_version: 2, required: [ "collection.read", + "records.create", "records.edit", "views.manage", "definitions.manage", diff --git a/src/components/gantt-chart.tsx b/src/components/gantt-chart.tsx index 0d259b5..4cbe751 100644 --- a/src/components/gantt-chart.tsx +++ b/src/components/gantt-chart.tsx @@ -621,7 +621,7 @@ export function GanttChart({ return (

No tasks match these controls

-

Change the project, search, or completed-task filter.

+

Change the saved view, search, or task filters.

); diff --git a/src/components/planner.create.test.tsx b/src/components/planner.create.test.tsx new file mode 100644 index 0000000..c1257e6 --- /dev/null +++ b/src/components/planner.create.test.tsx @@ -0,0 +1,164 @@ +import { + cleanup, + fireEvent, + render, + screen, + within, + waitFor, +} from "@testing-library/react"; +import { MdbaseError } from "@mdbase-dev/sdk"; +import { DemoPlannerRepository } from "../data/demo-repository"; +import { Planner } from "./planner"; + +beforeEach(() => { + vi.stubGlobal( + "matchMedia", + vi.fn(() => ({ matches: false })), + ); + HTMLElement.prototype.scrollTo = vi.fn(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +async function setup(empty = true) { + const repository = new DemoPlannerRepository(); + const collection = await repository.load(); + const created = { + ...collection.tasks[0], + id: crypto.randomUUID(), + title: "First shared task", + }; + const load = vi + .spyOn(repository, "load") + .mockResolvedValue({ ...collection, tasks: empty ? [] : collection.tasks }); + repository.createTask = vi.fn(async () => { + load.mockResolvedValue({ ...collection, tasks: [created] }); + return created; + }); + render(); + await screen.findByRole("button", { name: /Sample tasks/ }); + return { repository, created }; +} + +describe("Planner task creation", () => { + it("offers an empty-state action and a persistent add control, then shows the created task", async () => { + const { repository } = await setup(); + expect(screen.getByRole("button", { name: "Add task" })).toBeEnabled(); + fireEvent.click( + screen.getByRole("button", { name: "Add your first task" }), + ); + const dialog = screen.getByRole("dialog", { name: "Add task" }); + const title = within(dialog).getByRole("textbox", { name: "Task title" }); + expect(title).toHaveFocus(); + expect( + within(dialog).getByRole("button", { name: "Add task" }), + ).toBeDisabled(); + fireEvent.change(title, { target: { value: "First shared task" } }); + fireEvent.submit( + within(dialog).getByRole("button", { name: "Add task" }).closest("form")!, + ); + await waitFor(() => + expect(repository.createTask).toHaveBeenCalledWith( + "First shared task", + expect.any(String), + ), + ); + await waitFor(() => + expect(screen.queryByRole("dialog", { name: "Add task" })).toBeNull(), + ); + expect(screen.queryByText("No tasks yet")).toBeNull(); + expect(screen.getAllByText("First shared task").length).toBeGreaterThan(0); + expect(screen.getByRole("button", { name: "Add task" })).toBeEnabled(); + }); + + it("keeps add available with existing tasks and preserves a refused draft without reporting success", async () => { + const { repository } = await setup(false); + vi.mocked(repository.createTask).mockRejectedValueOnce( + new Error("The collection refused this task."), + ); + fireEvent.click(screen.getByRole("button", { name: "Add task" })); + const dialog = screen.getByRole("dialog", { name: "Add task" }); + const title = within(dialog).getByRole("textbox", { name: "Task title" }); + fireEvent.change(title, { target: { value: "Keep this draft" } }); + fireEvent.click(within(dialog).getByRole("button", { name: "Add task" })); + expect(await within(dialog).findByRole("alert")).toHaveTextContent( + "The collection refused this task.", + ); + expect(title).toHaveValue("Keep this draft"); + expect(screen.getByRole("dialog", { name: "Add task" })).toBeVisible(); + expect(screen.queryByText("Task added")).toBeNull(); + }); + + it("retains the original title and creation identity after an unknown outcome and reopening", async () => { + const { repository } = await setup(); + vi.mocked(repository.createTask).mockRejectedValueOnce( + new MdbaseError({ + code: "outcome_unknown", + recovery: "refresh", + message: "The result is unknown", + }), + ); + fireEvent.click(screen.getByRole("button", { name: "Add task" })); + let dialog = screen.getByRole("dialog", { name: "Add task" }); + fireEvent.change( + within(dialog).getByRole("textbox", { name: "Task title" }), + { target: { value: "Original task" } }, + ); + fireEvent.click(within(dialog).getByRole("button", { name: "Add task" })); + expect(await within(dialog).findByRole("alert")).toHaveTextContent( + /same task creation/, + ); + const intent = vi.mocked(repository.createTask).mock.calls[0][1]; + expect( + within(dialog).getByRole("textbox", { name: "Task title" }), + ).toHaveAttribute("readonly"); + fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + fireEvent.click(screen.getByRole("button", { name: "Add task" })); + dialog = screen.getByRole("dialog", { name: "Add task" }); + expect( + within(dialog).getByRole("textbox", { name: "Task title" }), + ).toHaveValue("Original task"); + fireEvent.click(within(dialog).getByRole("button", { name: "Add task" })); + await waitFor(() => + expect(repository.createTask).toHaveBeenLastCalledWith( + "Original task", + intent, + ), + ); + await waitFor(() => + expect(screen.queryByRole("dialog", { name: "Add task" })).toBeNull(), + ); + }); + + it("does not send a second creation or allow cancellation while the first is in flight", async () => { + const { repository, created } = await setup(); + let complete!: (value: typeof created) => void; + vi.mocked(repository.createTask).mockImplementation( + () => + new Promise((resolve) => { + complete = resolve; + }), + ); + fireEvent.click(screen.getByRole("button", { name: "Add task" })); + const dialog = screen.getByRole("dialog", { name: "Add task" }); + fireEvent.change( + within(dialog).getByRole("textbox", { name: "Task title" }), + { target: { value: "Only once" } }, + ); + const form = within(dialog) + .getByRole("button", { name: "Add task" }) + .closest("form")!; + fireEvent.submit(form); + fireEvent.submit(form); + expect(repository.createTask).toHaveBeenCalledTimes(1); + expect( + within(dialog).getByRole("button", { name: "Cancel" }), + ).toBeDisabled(); + complete(created); + await waitFor(() => + expect(screen.queryByRole("dialog", { name: "Add task" })).toBeNull(), + ); + }); +}); diff --git a/src/components/planner.empty.test.tsx b/src/components/planner.empty.test.tsx new file mode 100644 index 0000000..486febf --- /dev/null +++ b/src/components/planner.empty.test.tsx @@ -0,0 +1,155 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { DemoPlannerRepository } from "../data/demo-repository"; +import type { PlannerCollection } from "../domain/task"; +import { Planner } from "./planner"; + +const collectionId = "22222222-2222-4222-8222-222222222222"; +const originalHref = location.href; + +beforeEach(() => { + vi.stubGlobal( + "matchMedia", + vi.fn(() => ({ matches: false })), + ); + HTMLElement.prototype.scrollTo = vi.fn(); + vi.stubEnv("VITE_MDBASE_ENV", ""); + vi.stubEnv("VITE_MDBASE_CONNECT_URL", ""); +}); +afterEach(() => { + cleanup(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + history.replaceState(null, "", originalHref); +}); + +async function showCollection(patch: Partial = {}) { + const repository = new DemoPlannerRepository(); + const collection = { + ...(await repository.load()), + id: collectionId, + name: "My planning collection", + ...patch, + }; + vi.spyOn(repository, "load").mockResolvedValue(collection); + render(); + await screen.findByRole("button", { name: /My planning collection/ }); + return { repository, collection }; +} + +describe("Planner empty states", () => { + it.each([ + [ + "lab", + "https://connect-lab.mdbase.dev", + "https://lab.tasknotes-app.pages.dev", + ], + [ + "", + "https://connect-staging.mdbase.dev", + "https://staging.tasknotes-app.pages.dev", + ], + ["", "", "https://app.tasknotes.dev"], + ])( + "hands an empty collection to TaskNotes in its deployment (%s, %s)", + async (environment, connectUrl, origin) => { + vi.stubEnv("VITE_MDBASE_ENV", environment); + vi.stubEnv("VITE_MDBASE_CONNECT_URL", connectUrl); + history.replaceState( + null, + "", + "/?collection=11111111-1111-4111-8111-111111111111&demo=1&code=not-forwarded&server=https://wrong.example/#private", + ); + await showCollection({ tasks: [] }); + expect( + screen.getByRole("heading", { name: "No tasks yet" }), + ).toBeVisible(); + expect( + screen.getByText( + /Add your first task here, or create tasks in TaskNotes/, + ), + ).toBeVisible(); + const link = screen.getByRole("link", { + name: /Create tasks in TaskNotes/, + }); + const destination = new URL(link.getAttribute("href")!); + expect(destination.origin).toBe(origin); + expect([...destination.searchParams]).toEqual([ + ["collection", collectionId], + ]); + expect(destination.hash).toBe(""); + expect(link).toHaveAttribute("target", "_blank"); + expect(link.getAttribute("rel")?.split(" ")).toContain("noopener"); + expect(screen.queryByText("No tasks match these controls")).toBeNull(); + expect(screen.getByRole("button", { name: "Add task" })).toBeEnabled(); + }, + ); + + it("keeps search-filtered tasks distinct from a collection with no tasks", async () => { + await showCollection(); + fireEvent.change(screen.getByRole("searchbox", { name: "Search tasks" }), { + target: { value: "nothing matches this phrase" }, + }); + expect( + screen.getByRole("heading", { name: "No tasks match these controls" }), + ).toBeVisible(); + expect(screen.queryByText("No tasks yet")).toBeNull(); + expect( + screen.queryByRole("link", { name: /Create tasks in TaskNotes/ }), + ).toBeNull(); + }); + + it("keeps completed-only tasks distinct and lets the completed filter reveal them", async () => { + const sample = await new DemoPlannerRepository().load(); + await showCollection({ tasks: [{ ...sample.tasks[0], completed: true }] }); + expect( + screen.getByRole("heading", { name: "No tasks match these controls" }), + ).toBeVisible(); + expect(screen.queryByText("No tasks yet")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Completed" })); + expect(screen.getAllByText(sample.tasks[0].title).length).toBeGreaterThan( + 0, + ); + expect(screen.queryByText("No tasks match these controls")).toBeNull(); + }); + + it("does not claim the collection is empty when a saved view returns no tasks", async () => { + const view = { + key: "TaskNotes/Views/empty.base#empty", + path: "TaskNotes/Views/empty.base", + id: "empty", + name: "Empty saved view", + format: "obsidian.base", + revision: "revision", + writable: true, + options: {}, + }; + await showCollection({ tasks: [], views: [view], activeView: view }); + expect( + screen.getByRole("heading", { name: "No tasks match these controls" }), + ).toBeVisible(); + expect( + screen.getByText("Change the saved view, search, or task filters."), + ).toBeVisible(); + expect(screen.queryByText("No tasks yet")).toBeNull(); + expect( + screen.queryByRole("link", { name: /Create tasks in TaskNotes/ }), + ).toBeNull(); + }); + + it("does not call a failed task load an empty collection", async () => { + const repository = new DemoPlannerRepository(); + vi.spyOn(repository, "load").mockRejectedValue( + new Error("Task index unavailable"), + ); + render(); + expect( + await screen.findByRole("heading", { + name: "This collection could not be opened", + }), + ).toBeVisible(); + expect(screen.queryByText("No tasks yet")).toBeNull(); + expect( + screen.queryByRole("link", { name: /Create tasks in TaskNotes/ }), + ).toBeNull(); + }); +}); diff --git a/src/components/planner.native.test.tsx b/src/components/planner.native.test.tsx index b28c430..90cf2e0 100644 --- a/src/components/planner.native.test.tsx +++ b/src/components/planner.native.test.tsx @@ -66,6 +66,45 @@ describe("Planner native client surface (SDK testing fake, not native acceptance expect(close).not.toHaveBeenCalled(); }); + it("hands the native empty collection to TaskNotes and replaces the state after a watched creation", async () => { + vi.stubEnv("VITE_MDBASE_ENV", "lab"); + try { + const { client, repository, replica, record } = await nativeFixture(); + replica.deleteElsewhere(record.path); + render(); + expect( + await screen.findByRole("heading", { name: "No tasks yet" }), + ).toBeVisible(); + const link = screen.getByRole("link", { + name: /Create tasks in TaskNotes/, + }); + const destination = new URL(link.getAttribute("href")!); + expect(destination.origin).toBe("https://lab.tasknotes-app.pages.dev"); + expect(destination.searchParams.get("collection")).toBe( + client.hello.collection, + ); + const created = replica.seed({ + path: "tasks/first.md", + types: ["task"], + frontmatter: { + id: "first-task", + title: "Created in TaskNotes", + status: "open", + }, + }); + replica.editElsewhere(created.path, { + body: "The task arrived from another app.", + }); + expect(await screen.findByText("Created in TaskNotes")).toBeVisible(); + expect(screen.queryByText("No tasks yet")).toBeNull(); + expect( + screen.queryByRole("link", { name: /Create tasks in TaskNotes/ }), + ).toBeNull(); + } finally { + vi.unstubAllEnvs(); + } + }); + it("shows an exact-contract refusal instead of an empty or ready planning ledger", async () => { const { client, repository, catalog } = await nativeFixture(); vi.mocked(client.describe).mockResolvedValue({ ...catalog, contracts: [] }); diff --git a/src/components/planner.test.tsx b/src/components/planner.test.tsx index b22c73c..7a26e28 100644 --- a/src/components/planner.test.tsx +++ b/src/components/planner.test.tsx @@ -410,6 +410,7 @@ function repositoryFixture( ): PlannerRepository { return { load: vi.fn(async () => structuredClone(collection)), + createTask: vi.fn(), updateSchedule: vi.fn(), updateDependencies: vi.fn(), updateProperties: vi.fn(), diff --git a/src/components/planner.tsx b/src/components/planner.tsx index 588626a..2a84746 100644 --- a/src/components/planner.tsx +++ b/src/components/planner.tsx @@ -2,6 +2,7 @@ import { CollectionSaveWarning } from "@mdbase-dev/ui/collections"; import { CalendarDays, BookmarkPlus, + Plus, Check, ChevronDown, CircleAlert, @@ -40,8 +41,10 @@ import { } from "./connection-notice"; import { GanttChart } from "./gantt-chart"; import { TaskInspector } from "./task-inspector"; +import { TaskCreateDialog } from "./task-create-dialog"; import { useModalFocus } from "./use-modal-focus"; import { errorMessage, isOperationOutcomeUnknown } from "../data/outcome"; +import { taskNotesHref } from "../data/tasknotes-handoff"; import type { PlannerCollection, @@ -82,6 +85,7 @@ export function Planner({ const [activeViewKey, setActiveViewKey] = useState(() => new URLSearchParams(location.search).get("view"), ); + const [createOpen, setCreateOpen] = useState(false); const [saveOpen, setSaveOpen] = useState(false); const saveDialogRef = useRef(null); useModalFocus(saveOpen, saveDialogRef, () => setSaveOpen(false)); @@ -383,6 +387,14 @@ export function Planner({

{collection.activeView?.name ?? "Timeline"}

+ + + Create tasks in TaskNotes + (opens in a new tab) + + + ) : ( + setSelectedId(task.id)} + onZoom={(direction) => + setZoom((value) => clampZoom(value + direction)) + } + /> + )} {selected ? ( ) : null} + setCreateOpen(false)} + onSettled={refreshPendingMutations} + onCreated={(task) => { + setQuery(""); + setProject("all"); + setStatus("all"); + setPriority("all"); + if (activeViewKey) chooseView(""); + else void load(true); + setSelectedId(task.id); + }} + /> {saveOpen ? (
({ + title: "", + intent: crypto.randomUUID(), + })); + const [busy, setBusy] = useState(false); + const [failure, setFailure] = useState(null); + const pending = useRef(false); + const form = useRef(null); + const unknown = failure !== null && isOperationOutcomeUnknown(failure); + function close() { + if (pending.current) return; + // An uncertain write is not a cancelled write. Reopening retains its identity. + if (!unknown) { + setDraft({ title: "", intent: crypto.randomUUID() }); + setFailure(null); + } + onClose(); + } + useModalFocus(open, form, close); + + async function submit(event: FormEvent) { + event.preventDefault(); + if (pending.current || disabled || !draft.title.trim()) return; + pending.current = true; + setBusy(true); + setFailure(null); + try { + const task = await repository.createTask(draft.title, draft.intent); + setDraft({ title: "", intent: crypto.randomUUID() }); + onClose(); + onCreated(task); + } catch (reason) { + setFailure(reason); + } finally { + pending.current = false; + setBusy(false); + onSettled(); + } + } + + if (!open) return null; + return ( +
+ void submit(event)} + > +
+

Add task

+
+ + {failure !== null ? ( +

+ {errorMessage(failure)} + {unknown + ? " Retry uses this same task creation; do not add a second copy." + : ""} +

+ ) : null} +
+ + +
+ +
+ ); +} diff --git a/src/data/connect.test.ts b/src/data/connect.test.ts index 4afad80..73e68ec 100644 --- a/src/data/connect.test.ts +++ b/src/data/connect.test.ts @@ -55,7 +55,7 @@ describe("Planner's installed Connect runtime", () => { expect(Object.keys(effective.values)).toEqual( manifest.requirements.capabilities.required, ); - expect(operations).not.toContain("create"); + expect(operations).toContain("create"); expect(operations).not.toContain("delete"); expect(operations.some((op) => /file|timer|sync/i.test(op))).toBe(false); // Prior Planner grant's exact operation union is not authority for whole v2 groups. diff --git a/src/data/demo-repository.ts b/src/data/demo-repository.ts index 26721c3..10c1cff 100644 --- a/src/data/demo-repository.ts +++ b/src/data/demo-repository.ts @@ -76,6 +76,24 @@ export class DemoPlannerRepository implements PlannerRepository { return structuredClone(this.collection); } + async createTask(title: string, intent: string): Promise { + if (!title.trim()) throw new Error("Give this task a title."); + const previous = this.collection.tasks.find((task) => task.id === intent); + if (previous) return structuredClone(previous); + const task = demoTasks(dateFromDate(new Date()))[0]; + const next = { + ...task, + id: intent, + path: `tasks/${intent}.md`, + title: title.trim(), + scheduled: undefined, + due: undefined, + blockedBy: [], + }; + this.collection.tasks.push(next); + return structuredClone(next); + } + async updateSchedule( task: PlannerTask, update: ScheduleUpdate, diff --git a/src/data/mdbase-repository.ts b/src/data/mdbase-repository.ts index 51b5ea5..1c668ce 100644 --- a/src/data/mdbase-repository.ts +++ b/src/data/mdbase-repository.ts @@ -22,8 +22,10 @@ import { type StatusConfig, } from "@tasknotes/model"; import { parse, stringify } from "yaml"; +import { parseFrontmatter } from "@tasknotes/model/frontmatter"; import { requireOutcome } from "./outcome"; +import { taskCreationFields, taskCreationPath } from "./task-creation"; import type { PlannerCollection, @@ -114,6 +116,29 @@ export class MdbasePlannerRepository implements PlannerRepository { return structuredClone(this.collection); } + async createTask(title: string, intent: string): Promise { + if (!title.trim()) throw new Error("Give this task a title."); + await this.load(); + const config = this.taskTypes.values().next().value; + if (!config) + throw new Error("The TaskNotes contract has no implementing types."); + const type = requireOutcome( + await this.connection.readType({ name: config.typeName }), + ); + const path = taskCreationPath( + parseFrontmatter(type.document).frontmatter, + intent, + ); + const saved = requireOutcome( + await this.connection.create({ + ...(path === undefined ? {} : { path }), + contract: { ...contract, type: config.typeName }, + frontmatter: taskCreationFields(title, intent, config), + }), + ); + return this.taskFromRecord(saved); + } + async updateSchedule( task: PlannerTask, update: ScheduleUpdate, diff --git a/src/data/next-planner-repository.test.ts b/src/data/next-planner-repository.test.ts index 7ddc8c5..2b1ada2 100644 --- a/src/data/next-planner-repository.test.ts +++ b/src/data/next-planner-repository.test.ts @@ -1,12 +1,15 @@ import { connect, toValue, + toPlain, + MdbaseError, type MdbaseClient, type wire, } from "@mdbase-dev/sdk"; import { MemoryReplica } from "@mdbase-dev/sdk/testing"; import { TASKNOTES_CONTRACT_DIGEST } from "@tasknotes/model/mdbase"; import { TASKNOTES_SPEC_VERSION } from "@tasknotes/model"; +import { specFrontmatterToTaskInfo } from "@tasknotes/model/operations"; import { NextPlannerRepository } from "./next-planner-repository"; import type { NextPlannerViewAccess } from "./next-planner-views"; import type { PlannerView } from "../domain/task"; @@ -206,6 +209,187 @@ describe("NextPlannerRepository (SDK stand-in, not LAB)", () => { await expect(f.repo.load()).rejects.toThrow("same portable identity"); }); + it("creates TaskNotes records through the implementing contract with mapped defaults and stable retry identity", async () => { + const f = await fixture(); + f.replica.seedResource( + "_types/todo.md", + "---\nname: todo\ncollection:\n path:\n folder: work\n---\n", + ); + await f.repo.load(); + const create = vi.spyOn(f.client, "create"); + const intent = crypto.randomUUID(); + const saved = await f.repo.createTask(" A task from Planner ", intent); + expect(saved).toMatchObject({ + id: intent, + title: "A task from Planner", + providerType: "todo", + status: "open", + priority: "normal", + }); + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + id: intent, + path: `work/${intent}.md`, + contract: { + id: "tasknotes.task", + version: TASKNOTES_SPEC_VERSION, + type: "todo", + }, + frontmatter: expect.objectContaining({ + id: intent, + title: "A task from Planner", + status: "open", + priority: "normal", + }), + }), + expect.objectContaining({ intent, signal: expect.any(AbortSignal) }), + ); + const stored = await f.client.get( + { path: saved.path }, + { body: true, effective: true }, + ); + expect(stored.types).toEqual(["todo"]); + expect(stored.frontmatter.get("headline")).toBe("A task from Planner"); + expect(stored.frontmatter.get("state")).toBe("open"); + expect(stored.frontmatter.get("urgency")).toBe("normal"); + expect(stored.frontmatter.has("title")).toBe(false); + const portable = await f.client.getContract(stored.id, { + id: "tasknotes.task", + version: TASKNOTES_SPEC_VERSION, + type: "todo", + }); + const taskNotes = specFrontmatterToTaskInfo( + Object.fromEntries( + [...portable.fields].map(([key, value]) => [key, toPlain(value)]), + ), + portable.path, + ); + expect(taskNotes).toMatchObject({ + title: "A task from Planner", + status: "open", + priority: "normal", + }); + // A second app reading the portable contract sees the same task, not a Planner-only copy. + const other = new NextPlannerRepository( + f.client, + "The same collection", + f.views, + ); + repositories.push(other); + expect( + (await other.load()).tasks.find((task) => task.id === intent)?.title, + ).toBe("A task from Planner"); + expect((await f.repo.createTask("A task from Planner", intent)).id).toBe( + intent, + ); + expect( + (await f.repo.load()).tasks.filter((task) => task.id === intent), + ).toHaveLength(1); + }); + + it("does not submit blank titles or an unconfirmed creation policy", async () => { + const f = await fixture(); + await f.repo.load(); + const create = vi.spyOn(f.client, "create"); + await expect(f.repo.createTask(" ", crypto.randomUUID())).rejects.toThrow( + /title/i, + ); + f.replica.seedResource("_types/todo.md", "---\nname: todo\n---\n"); + const get = f.client.resources.get.bind(f.client.resources); + vi.spyOn(f.client.resources, "get").mockImplementation(async (...args) => ({ + ...(await get(...args)), + state: "pending", + })); + await expect( + f.repo.createTask("Not yet", crypto.randomUUID()), + ).rejects.toThrow(/confirmed/); + expect(create).not.toHaveBeenCalled(); + }); + + it("reports pending creates as saved on this device and later refusals through the ledger", async () => { + const f = await fixture({ pending: true }); + f.replica.seedResource( + "_types/todo.md", + "---\nname: todo\ncollection:\n path:\n folder: work\n---\n", + ); + await f.repo.load(); + const save = f.client.save.bind(f.client); + vi.spyOn(f.client, "save").mockImplementation((write, options) => + save(write, { ...options, timeoutMs: 10 }), + ); + f.replica.setOnline(false); + const task = await f.repo.createTask( + "Waiting for the log", + crypto.randomUUID(), + ); + expect(task.title).toBe("Waiting for the log"); + await vi.waitFor(() => expect(f.repo.savedOnDevice()).toBe(true)); + expect(f.client.ledger.getSnapshot().pending).toHaveLength(1); + const [pending] = f.client.ledger.getSnapshot().pending; + f.replica.reject(pending.mutationId, { + code: "conflict", + recovery: "refresh", + message: "The log refused creation", + }); + await vi.waitFor(() => + expect(f.repo.rejectedWrites()).toEqual([ + { id: pending.mutationId, message: "The log refused creation" }, + ]), + ); + }); + + it("does not duplicate a task when the first create committed but its caller lost the reply", async () => { + const f = await fixture(); + f.replica.seedResource( + "_types/todo.md", + "---\nname: todo\ncollection:\n path:\n folder: work\n---\n", + ); + await f.repo.load(); + const save = f.client.save.bind(f.client); + vi.spyOn(f.client, "save").mockImplementationOnce(async (...args) => { + await save(...args); + throw new MdbaseError({ + code: "outcome_unknown", + recovery: "refresh", + message: "Reply lost after commit", + }); + }); + const intent = crypto.randomUUID(); + await expect( + f.repo.createTask("One shared task", intent), + ).rejects.toMatchObject({ code: "outcome_unknown" }); + expect((await f.repo.createTask("One shared task", intent)).id).toBe( + intent, + ); + expect( + (await f.repo.load()).tasks.filter((task) => task.id === intent), + ).toHaveLength(1); + }); + + it("preserves unknown receipt evidence rather than acknowledging it as a terminal refusal", async () => { + const f = await fixture(); + f.replica.seedResource("_types/todo.md", "---\nname: todo\n---\n"); + await f.repo.load(); + const acknowledge = vi.spyOn(f.client.ledger, "acknowledge"); + vi.spyOn(f.client, "save").mockImplementation(async (write) => { + const captured = await write; + return { + outcome: "rejected", + mutationId: captured.mutationId, + records: [], + problem: { + code: "outcome_unknown", + recovery: "refresh", + message: "The result is unknown", + }, + }; + }); + await expect( + f.repo.createTask("Do not abandon", crypto.randomUUID()), + ).rejects.toMatchObject({ code: "outcome_unknown" }); + expect(acknowledge).not.toHaveBeenCalled(); + }); + it("writes canonical schedule fields through the task contract", async () => { const f = await fixture(); const [item] = (await f.repo.load()).tasks; diff --git a/src/data/next-planner-repository.ts b/src/data/next-planner-repository.ts index 7dc68fb..dffd8a2 100644 --- a/src/data/next-planner-repository.ts +++ b/src/data/next-planner-repository.ts @@ -18,6 +18,9 @@ import { taskInfoToSpecFields, } from "@tasknotes/model/operations"; import { stringify } from "yaml"; +import { parseFrontmatter } from "@tasknotes/model/frontmatter"; +import { taskCreationFields, taskCreationPath } from "./task-creation"; +import { isOperationOutcomeUnknown } from "./outcome"; import type { JsonObject } from "@mdbase-dev/connect"; import type { PlannerCollection, @@ -120,6 +123,69 @@ export class NextPlannerRepository implements PlannerRepository { }; } + async createTask(title: string, intent: string): Promise { + if (!title.trim()) throw new Error("Give this task a title."); + const signal = this.signal(); + await this.revalidateConfigurations(signal); + const generation = this.generation; + const description = await this.client.describe(signal); + const configurations = configurationsFromDescription(description); + if ( + configurationSignature(configurations) !== + configurationSignature(this.configurations) + ) + throw new Error("The collection changed. Reload Planner before editing."); + const config = configurations.values().next().value!; + const type = description.types.find( + (type) => type.name === config.typeName, + )!; + const source = await this.client.resources.get(type.path, signal); + if (source.state !== "confirmed" || source.text === undefined) + throw new Error( + "The TaskNotes type definition must be confirmed before creating tasks.", + ); + const path = taskCreationPath( + parseFrontmatter(source.text).frontmatter, + intent, + ); + const frontmatter = taskCreationFields(title, intent, config); + signal.throwIfAborted(); + if (generation !== this.generation) throw changed(); + const result = await this.client.save( + this.client.create( + { + id: intent, + ...(path === undefined ? {} : { path }), + contract: { + id: "tasknotes.task", + version: TASKNOTES_SPEC_VERSION, + type: config.typeName, + }, + frontmatter: frontmatter as Record, + }, + { intent, signal }, + ), + { readBack: true, signal }, + ); + if (result.outcome === "rejected") { + const failure = result.problem + ? new MdbaseError(result.problem) + : new Error("The task creation was rejected."); + if (!isOperationOutcomeUnknown(failure)) + await this.client.ledger.acknowledge(result.mutationId); + throw failure; + } + if (!result.record) + throw new Error( + "The created task is unavailable. Reconcile the original creation before adding it again.", + ); + if (result.record.state.hold || result.record.state.unresolved) + throw new Error( + "The new task has a conflict. Resolve it in TaskNotes before planning.", + ); + return task(result.record, configurations); + } + updateSchedule( item: PlannerTask, update: ScheduleUpdate, diff --git a/src/data/outcome.ts b/src/data/outcome.ts index 981951e..d083775 100644 --- a/src/data/outcome.ts +++ b/src/data/outcome.ts @@ -14,8 +14,9 @@ export function requireOutcome( export function isOperationOutcomeUnknown(reason: unknown): boolean { return ( - reason instanceof MdbaseConnectError && - reason.problem.operation_outcome === "unknown" + (reason instanceof MdbaseConnectError && + reason.problem.operation_outcome === "unknown") || + describeError(reason)?.code === "outcome_unknown" ); } diff --git a/src/data/task-creation.ts b/src/data/task-creation.ts new file mode 100644 index 0000000..e77c583 --- /dev/null +++ b/src/data/task-creation.ts @@ -0,0 +1,55 @@ +import { taskInfoToSpecFields } from "@tasknotes/model/operations"; +import { validateTask } from "@tasknotes/model/validation"; +import { getCurrentDateString } from "@tasknotes/model/date"; +import type { JsonObject } from "@mdbase-dev/connect"; +import type { TaskTypeConfiguration } from "./mdbase-repository"; + +/** The same portable fields TaskNotes writes; the SDK maps contract roles to + * the selected implementing type. Never mint a Planner-specific task type. */ +export function taskCreationFields( + title: string, + id: string, + config: TaskTypeConfiguration, +): JsonObject { + const now = new Date().toISOString(); + const task = { + title: title.trim(), + status: config.defaultStatus, + priority: config.defaultPriority, + dateCreated: now, + dateModified: now, + ...(config.statuses.some( + (status) => status.value === config.defaultStatus && status.isCompleted, + ) + ? { completedDate: getCurrentDateString() } + : {}), + }; + if (!task.title) throw new Error("Give this task a title."); + const validation = validateTask(task); + if (!validation.valid) + throw new Error(validation.issues.map((issue) => issue.message).join("\n")); + if (!config.fields.title) + throw new Error("This task type does not expose a title."); + return Object.fromEntries( + Object.entries({ id, ...taskInfoToSpecFields(task) }).filter( + ([role]) => config.fields[role], + ), + ) as JsonObject; +} + +/** Native path patterns belong to mdbase. TaskNotes runtime templates do not: + * use a stable UUID filename in that type's declared folder, without copying + * TaskNotes' filename/template interpreter or guessing a folder from the title. */ +export function taskCreationPath( + definition: Record, + id: string, +): string | undefined { + const collection = definition.collection as + { path?: { pattern?: string; folder?: string } } | undefined; + const policy = collection?.path; + if (policy?.pattern) return undefined; + const folder = policy?.folder ?? "tasks"; // TaskNotes' default when the type declares no folder. + if (typeof folder !== "string" || !folder.trim()) + throw new Error("The task type has an invalid records folder."); + return `${folder.replace(/\/+$/, "")}/${id}.md`; +} diff --git a/src/data/tasknotes-handoff.ts b/src/data/tasknotes-handoff.ts new file mode 100644 index 0000000..bc3b27e --- /dev/null +++ b/src/data/tasknotes-handoff.ts @@ -0,0 +1,17 @@ +import { mdbaseAppHref } from "@mdbase-dev/ui/apps"; + +/** Open the loaded collection, not a stale URL selection or a demo/view URL. + * TaskNotes still owns its own sign-in, approval and task creation. */ +export function taskNotesHref(collectionId: string): string { + const origin = + import.meta.env.VITE_MDBASE_ENV === "lab" + ? "https://lab.tasknotes-app.pages.dev" + : import.meta.env.VITE_MDBASE_CONNECT_URL === + "https://connect-staging.mdbase.dev" + ? "https://staging.tasknotes-app.pages.dev" + : "https://app.tasknotes.dev"; + return mdbaseAppHref( + origin, + `${location.origin}/?collection=${encodeURIComponent(collectionId)}`, + ); +} diff --git a/src/domain/task.ts b/src/domain/task.ts index fbc9b45..b2eebef 100644 --- a/src/domain/task.ts +++ b/src/domain/task.ts @@ -105,6 +105,8 @@ export interface RejectedPlannerWrite { export interface PlannerRepository { load(viewKey?: string): Promise; + /** One intent per draft; retrying it must not create another task. */ + createTask(title: string, intent: string): Promise; updateSchedule( task: PlannerTask, update: ScheduleUpdate, diff --git a/src/generated-mdbase-app.json b/src/generated-mdbase-app.json index cc3a861..3010247 100644 --- a/src/generated-mdbase-app.json +++ b/src/generated-mdbase-app.json @@ -22,6 +22,7 @@ "contract_version": 2, "required": [ "collection.read", + "records.create", "records.edit", "views.manage", "definitions.manage" @@ -29,7 +30,7 @@ }, "access": "full_collection", "files": { - "required": ["list", "read", "replace", "move"], + "required": ["list", "read", "add", "replace", "move"], "scope": { "kind": "collection" } }, "configuration": [ From 46e9966af84dda2df0878219ae6220cf07976166 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Mon, 19 Oct 2026 01:11:48 +1100 Subject: [PATCH 2/2] Verify native task capture and keep add controls reachable on phones --- e2e/planner.spec.ts | 25 +++++++++++++++ src/components/planner.native.test.tsx | 42 +++++++++++++++++++++++++- src/components/planner.tsx | 3 ++ src/components/task-create-dialog.tsx | 1 + src/styles.css | 13 ++++++-- 5 files changed, 80 insertions(+), 4 deletions(-) diff --git a/e2e/planner.spec.ts b/e2e/planner.spec.ts index d3e84ca..873bd31 100644 --- a/e2e/planner.spec.ts +++ b/e2e/planner.spec.ts @@ -5,6 +5,31 @@ test.beforeEach(async ({ page }) => { await expect(page.getByRole("heading", { name: "Timeline" })).toBeVisible(); }); +for (const width of [1440, 834, 390, 360]) { + test(`adds an ordinary task from the persistent control at ${width}px`, async ({ + page, + }) => { + await page.setViewportSize({ width, height: 900 }); + const add = page.getByRole("button", { name: "Add task", exact: true }); + await expect(add).toBeInViewport(); + await add.click(); + const dialog = page.getByRole("dialog", { name: "Add task", exact: true }); + const title = dialog.getByRole("textbox", { name: "Task title" }); + await expect(title).toBeFocused(); + await title.fill("A task captured in Planner"); + await dialog.getByRole("button", { name: "Add task", exact: true }).click(); + await expect(dialog).toHaveCount(0); + await expect( + page.getByRole("heading", { name: "A task captured in Planner" }), + ).toBeVisible(); + expect( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + ).toBe(true); + }); +} + test("zooms and toggles TaskNotes completion", async ({ page }) => { await expect(page.locator(".zoom-control output")).toHaveText("Weeks"); const timeline = page.locator(".gantt-scroll"); diff --git a/src/components/planner.native.test.tsx b/src/components/planner.native.test.tsx index 90cf2e0..9de9184 100644 --- a/src/components/planner.native.test.tsx +++ b/src/components/planner.native.test.tsx @@ -1,6 +1,14 @@ -import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import { + cleanup, + fireEvent, + render, + screen, + waitFor, + within, +} from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { MdbaseClient } from "@mdbase-dev/sdk"; +import { TASKNOTES_SPEC_VERSION } from "@tasknotes/model"; import { nativePlannerFixture } from "../test/native-planner-fixture"; import { NextPlannerRepository } from "../data/next-planner-repository"; import { Planner } from "./planner"; @@ -105,6 +113,38 @@ describe("Planner native client surface (SDK testing fake, not native acceptance } }); + it("creates through the empty-state form and reads back the shared native task", async () => { + const { client, repository, replica, record } = await nativeFixture(); + replica.deleteElsewhere(record.path); + replica.seedResource( + "_types/task.md", + "---\nname: task\ncollection:\n path:\n folder: tasks\n---\n", + ); + render(); + fireEvent.click( + await screen.findByRole("button", { name: "Add your first task" }), + ); + const dialog = screen.getByRole("dialog", { name: "Add task" }); + fireEvent.change( + within(dialog).getByRole("textbox", { name: "Task title" }), + { target: { value: "Shared native task" } }, + ); + fireEvent.click(within(dialog).getByRole("button", { name: "Add task" })); + await waitFor(() => + expect(screen.queryByRole("dialog", { name: "Add task" })).toBeNull(), + ); + expect(screen.queryByText("No tasks yet")).toBeNull(); + expect(screen.getAllByText("Shared native task").length).toBeGreaterThan(0); + const [task] = (await repository.load()).tasks; + const projected = await client.getContract( + { path: task.path }, + { id: "tasknotes.task", version: TASKNOTES_SPEC_VERSION, type: "task" }, + ); + expect(projected.fields.get("title")).toBe("Shared native task"); + expect(projected.fields.get("status")).toBe("open"); + expect(projected.fields.get("id")).toBe(task.id); + }); + it("shows an exact-contract refusal instead of an empty or ready planning ledger", async () => { const { client, repository, catalog } = await nativeFixture(); vi.mocked(client.describe).mockResolvedValue({ ...catalog, contracts: [] }); diff --git a/src/components/planner.tsx b/src/components/planner.tsx index 2a84746..70abfb3 100644 --- a/src/components/planner.tsx +++ b/src/components/planner.tsx @@ -388,6 +388,8 @@ export function Planner({