Cache notes in one place, and serialise a project's writes
Implements the design spec's §2 — "notes cached in zustand keyed by
project id" — which the plan substituted with a hook-local `useState`.
Sharing the `NotesPanel` *component* between the Project Home sub-tab and
the dock did not share the *cache*. Both resolve to the same project, so
two panels mount two `useNotes(P)`, each with its own list. Edit a note
in the dock and blur; the tab's copy is still pre-edit, and the tab's
next blur commits `{...staleRecord, title, body}` — the dock's edit gone
from disk with no error and no indicator. That is the feature's own
primary workflow: take notes in the dock while the agent runs, which is
the reason the dock exists, then go back to the tab.
`notesByProject` plus a per-project in-flight flag now hold the list.
Both surfaces render from one array; two panels mounting for one project
make one read; and because the write is keyed by project, a response
that lands after the user has moved on updates the project it belongs to
rather than whichever is on screen. This is also the boundary §8 says a
detached notes window needs.
Three more bugs in the same code, fixed with it:
- Delete-after-edit could resurrect the note. Clicking Delete with the
textarea focused fires blur first, so `save_note` and `delete_note` go
out back to back; Rust's `write_lock` stops them interleaving but does
not order them, and a delete that wins the lock is undone by the
upsert behind it. A project's mutations now go through one promise
chain, module-scoped for the reason `useTerminal`'s input queue is.
- An unsaved draft vanished when any other note was saved, because the
re-read replaced the list with the backend's. "New note" now persists,
so the backend owns the row from the start — chosen over merging local
drafts because a local-only row in a *shared* cache would exist in the
panel that made it and nowhere else.
- The save outcome was reported for the wrong project after a switch:
the guard covered only the list replacement, so the new project's
SaveIndicator flashed "Saved ✓" for the old project's write. The
indicator now resets on a project change and reports only its own.
`NotesPanel` also re-seeds its draft when the *stored* text of the note
it has selected changes, so an edit made in the other surface reaches
the editor and not only the list. It never overwrites something
half-typed; that still blurs into a last-writer-wins save, as any
blur-commit editor does.
NotesPanel.shared.test.tsx is the configuration none of the existing
tests had: two panels, one project, the real hook. Four of its six
assertions fail against the previous implementation.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HjL1E2JFNctUqCYotUwqqb
This commit is contained in:
+173
-10
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderHook, act, waitFor } from "@testing-library/react";
|
||||
import { useNotes } from "./useNotes";
|
||||
import { useAppState } from "../store/appState";
|
||||
import type { Note } from "../lib/types";
|
||||
|
||||
const listNotes = vi.fn();
|
||||
@@ -13,14 +14,6 @@ vi.mock("../lib/tauri-commands", () => ({
|
||||
deleteNote: (p: string, id: string) => deleteNote(p, id),
|
||||
}));
|
||||
|
||||
const pushToast = vi.fn();
|
||||
vi.mock("../store/appState", () => ({
|
||||
useAppState: Object.assign(
|
||||
(selector: (s: unknown) => unknown) => selector({ pushToast }),
|
||||
{ getState: () => ({ pushToast }) },
|
||||
),
|
||||
}));
|
||||
|
||||
const note = (over: Partial<Note> = {}): Note => ({
|
||||
id: "n1",
|
||||
title: "Deploy",
|
||||
@@ -31,8 +24,35 @@ const note = (over: Partial<Note> = {}): Note => ({
|
||||
...over,
|
||||
});
|
||||
|
||||
/** The toasts the hook pushed. The store is real, so this is what a user sees. */
|
||||
const toasts = () => useAppState.getState().toasts;
|
||||
|
||||
/**
|
||||
* A stand-in for the Rust store: one list per project, upsert and delete
|
||||
* applied to it, `list_notes` reading it back. Several of these tests are about
|
||||
* what the *list* looks like after a sequence of writes, which a per-call
|
||||
* `mockResolvedValueOnce` cannot express.
|
||||
*/
|
||||
function fakeBackend(initial: Record<string, Note[]> = {}) {
|
||||
const files: Record<string, Note[]> = { ...initial };
|
||||
listNotes.mockImplementation(async (p: string) => [...(files[p] ?? [])]);
|
||||
saveNote.mockImplementation(async (p: string, n: Note) => {
|
||||
const list = files[p] ?? (files[p] = []);
|
||||
const at = list.findIndex((x) => x.id === n.id);
|
||||
if (at === -1) list.unshift(n);
|
||||
else list[at] = n;
|
||||
return n;
|
||||
});
|
||||
deleteNote.mockImplementation(async (p: string, id: string) => {
|
||||
files[p] = (files[p] ?? []).filter((x) => x.id !== id);
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
// The cache is shared app state now, so it has to be reset like any other.
|
||||
useAppState.setState({ notesByProject: {}, notesLoading: {}, toasts: [] });
|
||||
listNotes.mockResolvedValue([note()]);
|
||||
saveNote.mockImplementation(async (_p: string, n: Note) => n);
|
||||
deleteNote.mockResolvedValue(undefined);
|
||||
@@ -60,7 +80,7 @@ describe("useNotes", () => {
|
||||
|
||||
expect(ok).toBe(false);
|
||||
expect(result.current.saveState.status).toBe("failed");
|
||||
expect(pushToast).toHaveBeenCalled();
|
||||
expect(toasts()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("replaces the saved note in place rather than appending", async () => {
|
||||
@@ -128,7 +148,7 @@ describe("useNotes", () => {
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.notes).toHaveLength(0);
|
||||
expect(pushToast).toHaveBeenCalled();
|
||||
expect(toasts()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("ends with the list the backend returned when saving a new note", async () => {
|
||||
@@ -206,4 +226,147 @@ describe("useNotes", () => {
|
||||
expect(result.current.notes).toHaveLength(1);
|
||||
expect(result.current.notes[0].id).toBe("n2");
|
||||
});
|
||||
|
||||
it("keeps the notes already on screen when a refresh fails", async () => {
|
||||
// The second surface mounting for a project is a refresh behind a list the
|
||||
// user is already reading. One shared cache means a failed refresh would
|
||||
// otherwise blank both panels.
|
||||
fakeBackend({ p1: [note()] });
|
||||
const tab = renderHook(() => useNotes("p1"));
|
||||
await waitFor(() => expect(tab.result.current.loading).toBe(false));
|
||||
|
||||
listNotes.mockRejectedValueOnce(new Error("read failed"));
|
||||
const dock = renderHook(() => useNotes("p1"));
|
||||
await waitFor(() => expect(toasts()).toHaveLength(1));
|
||||
|
||||
expect(tab.result.current.notes).toHaveLength(1);
|
||||
expect(dock.result.current.notes).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not report the old project's save on the new project's indicator", async () => {
|
||||
// The indicator is per-panel and reads "Saved ✓". Firing it after a switch
|
||||
// tells the user their *current* project was written when it was not.
|
||||
const { result, rerender } = renderHook(
|
||||
({ projectId }: { projectId: string }) => useNotes(projectId),
|
||||
{ initialProps: { projectId: "p1" } },
|
||||
);
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
let resolveSave: ((n: Note) => void) | undefined;
|
||||
saveNote.mockImplementationOnce(
|
||||
() => new Promise((resolve) => (resolveSave = resolve)),
|
||||
);
|
||||
let savePromise: Promise<boolean> | undefined;
|
||||
await act(async () => {
|
||||
savePromise = result.current.saveNote(note({ body: "edited" }));
|
||||
});
|
||||
|
||||
rerender({ projectId: "p2" });
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
await act(async () => {
|
||||
resolveSave?.(note({ body: "edited" }));
|
||||
await savePromise;
|
||||
});
|
||||
|
||||
expect(result.current.saveState.status).toBe("idle");
|
||||
});
|
||||
|
||||
it("still reports a save on the indicator of the project it was made for", async () => {
|
||||
const { result } = renderHook(() => useNotes("p1"));
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveNote(note({ body: "edited" }));
|
||||
});
|
||||
|
||||
expect(result.current.saveState.status).toBe("saved");
|
||||
});
|
||||
|
||||
it("serialises a project's writes so an edit cannot be re-inserted after its delete", async () => {
|
||||
// Clicking Delete while the textarea has focus fires blur first, so a save
|
||||
// and a delete go out back to back. The Rust write lock stops them
|
||||
// interleaving but does not order them: a delete that wins the lock is
|
||||
// undone by the upsert behind it, and the note comes back on next load.
|
||||
const files = fakeBackend({ p1: [note()] });
|
||||
const { result } = renderHook(() => useNotes("p1"));
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
const order: string[] = [];
|
||||
saveNote.mockImplementationOnce(async (p: string, n: Note) => {
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
order.push("save");
|
||||
files[p] = [n];
|
||||
return n;
|
||||
});
|
||||
deleteNote.mockImplementationOnce(async (p: string, id: string) => {
|
||||
order.push("delete");
|
||||
files[p] = (files[p] ?? []).filter((x) => x.id !== id);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
const save = result.current.saveNote(note({ body: "typo fixed" }));
|
||||
const del = result.current.deleteNote("n1");
|
||||
await Promise.all([save, del]);
|
||||
});
|
||||
|
||||
expect(order).toEqual(["save", "delete"]);
|
||||
expect(files.p1).toHaveLength(0);
|
||||
expect(result.current.notes).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("keeps a new note when another note is saved right after it", async () => {
|
||||
// A purely local draft used to be wiped by the next re-read: two clicks of
|
||||
// "New note", type in the second, blur, and the first row was gone.
|
||||
const files = fakeBackend({ p1: [note()] });
|
||||
const { result } = renderHook(() => useNotes("p1"));
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
let first: Note | null = null;
|
||||
await act(async () => {
|
||||
first = await result.current.createNote();
|
||||
await result.current.createNote();
|
||||
});
|
||||
expect(result.current.notes).toHaveLength(3);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveNote(note({ body: "edited" }));
|
||||
});
|
||||
|
||||
expect(result.current.notes).toHaveLength(3);
|
||||
expect(result.current.notes.some((n) => n.id === first!.id)).toBe(true);
|
||||
expect(files.p1).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("shares one cache between every hook watching the same project", async () => {
|
||||
// The Project Home sub-tab and the dock both mount a panel for the same
|
||||
// project. Two caches meant an edit in one was invisible to the other, and
|
||||
// the other's next blur wrote its stale copy back over it.
|
||||
fakeBackend({ p1: [note()] });
|
||||
const tab = renderHook(() => useNotes("p1"));
|
||||
const dock = renderHook(() => useNotes("p1"));
|
||||
await waitFor(() => expect(tab.result.current.loading).toBe(false));
|
||||
await waitFor(() => expect(dock.result.current.loading).toBe(false));
|
||||
|
||||
// One read for both — the in-flight flag is per project, not per hook.
|
||||
expect(listNotes).toHaveBeenCalledTimes(1);
|
||||
|
||||
await act(async () => {
|
||||
await dock.result.current.saveNote(note({ body: "written in the dock" }));
|
||||
});
|
||||
|
||||
expect(tab.result.current.notes[0].body).toBe("written in the dock");
|
||||
expect(tab.result.current.notes).toBe(dock.result.current.notes);
|
||||
});
|
||||
|
||||
it("does not blank an already-loaded list when a second panel mounts", async () => {
|
||||
fakeBackend({ p1: [note()] });
|
||||
const tab = renderHook(() => useNotes("p1"));
|
||||
await waitFor(() => expect(tab.result.current.loading).toBe(false));
|
||||
|
||||
const dock = renderHook(() => useNotes("p1"));
|
||||
// No "Loading notes…" flash on the second surface.
|
||||
expect(dock.result.current.loading).toBe(false);
|
||||
expect(dock.result.current.notes).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user