From ff76fc1c0df3107794a5b2e24c287c5bbb2f0a67 Mon Sep 17 00:00:00 2001 From: Cameron Taylor Date: Thu, 12 Nov 2026 12:20:47 +1100 Subject: [PATCH] fix(firstmate): Persist chat drafts across app restarts --- firstmate/AGENTS.md | 13 +++ firstmate/CHANGELOG.md | 4 + firstmate/client/chat-drafts.ts | 49 +++++++++++ firstmate/client/chat.tsx | 20 ++--- firstmate/client/draft-persistence.test.ts | 95 ++++++++++++++++++++++ firstmate/client/draft-persistence.ts | 65 +++++++++++++++ firstmate/client/draft-send.test.ts | 21 +++++ firstmate/client/draft-send.ts | 11 +++ firstmate/client/draft.ts | 18 ++-- firstmate/index.client.tsx | 2 + firstmate/index.server.ts | 4 + firstmate/package-lock.json | 4 +- firstmate/package.json | 2 +- firstmate/server/drafts.test.ts | 21 +++++ firstmate/server/drafts.ts | 28 +++++++ firstmate/shared/drafts.ts | 10 +++ 16 files changed, 347 insertions(+), 20 deletions(-) create mode 100644 firstmate/client/chat-drafts.ts create mode 100644 firstmate/client/draft-persistence.test.ts create mode 100644 firstmate/client/draft-persistence.ts create mode 100644 firstmate/client/draft-send.test.ts create mode 100644 firstmate/client/draft-send.ts create mode 100644 firstmate/server/drafts.test.ts create mode 100644 firstmate/server/drafts.ts create mode 100644 firstmate/shared/drafts.ts diff --git a/firstmate/AGENTS.md b/firstmate/AGENTS.md index e41a6a46..a0312d28 100644 --- a/firstmate/AGENTS.md +++ b/firstmate/AGENTS.md @@ -777,6 +777,19 @@ of those is a host module, so on iOS and Android the attach button is not drawn words only. A phone *browser* gets the button, and its picker offers the photo library and camera. Paste takes images only, as Paseo's does, so pasting text or a copied file still pastes text. +The chat's text is also saved through `firstmate.drafts.read/write` in +`plugin-data/firstmate/chat-drafts/.txt`, shared by clients of that host. +The synchronous store stays authoritative during typing; hydration cannot replace +an edit, and one retained controller per mate serializes writes across navigation +and plugin re-evaluation. Nonempty edits debounce for 300 ms, clears flush +immediately, and AppState background, chat unmount and plugin disposal flush. +The text stays in the composer until a successful send; a changed follow-up is +kept. A failed send leaves the text intact. Neither lifecycle flush nor an RPC +guarantees delivery before OS termination: the last 300 ms plus transport time +can be lost, and offline writes remain memory-only until retried on a later edit, +mount or lifecycle event. A success whose clear never reaches storage can reappear. +Attachments and card answers are not persisted. A new mate UUID gets a new draft. + The pending attachments live beside the draft on `globalThis` (`client/attachments.ts`), bytes and all, so a lost connection keeps them; a failed send puts them back unless something new was attached. diff --git a/firstmate/CHANGELOG.md b/firstmate/CHANGELOG.md index d9b386a5..8766612b 100644 --- a/firstmate/CHANGELOG.md +++ b/firstmate/CHANGELOG.md @@ -7,6 +7,10 @@ follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Every version as `@gpambrozio/paseo-firstmate` and tagged here, so a version is something to install and a line to read before you move. +## [0.4.1] + +- Save unsent chat text on the host so it returns after an app reload or relaunch. Typing is saved after 300 ms and flushed when the app backgrounds or the chat closes; an app killed before delivery can still lose the latest edit. Keep the draft until a send succeeds. + ## [0.4.0] — 2026-10-08 ### Added diff --git a/firstmate/client/chat-drafts.ts b/firstmate/client/chat-drafts.ts new file mode 100644 index 00000000..39e9a551 --- /dev/null +++ b/firstmate/client/chat-drafts.ts @@ -0,0 +1,49 @@ +import { useEffect } from "react"; +import { AppState } from "react-native"; +import { useRpc } from "@getpaseo/plugin/client"; +import { readChatDraft, writeChatDraft } from "../shared/drafts"; +import { drafts } from "./draft"; +import { persistDraft } from "./draft-persistence"; + +type Entry = { + controller: ReturnType; + transport: { read: () => Promise; write: (text: string) => Promise }; +}; +const slot = Symbol.for("paseo.firstmate.durable-chat-drafts"); +const controllers: Map = Reflect.get(globalThis, slot) ?? new Map(); +Reflect.set(globalThis, slot, controllers); +/** Keep the queue and listeners across host reconnects, but flush before disposal. */ +export function stopChatDrafts(): void { + controllers.forEach(entry => { void entry.controller.flush(); }); +} +export function useChatDraftPersistence(agentId: string): void { + const read = useRpc(readChatDraft); + const write = useRpc(writeChatDraft); + useEffect(() => { + let entry = controllers.get(agentId); + if (!entry) { + const transport = { + read: async () => (await read({ agentId })).text, + write: (text: string) => write({ agentId, text }), + }; + const created: Entry = { + transport, + controller: persistDraft(drafts, agentId, + () => transport.read(), text => transport.write(text), + error => console.warn("[firstmate] draft persistence failed", error)), + }; + entry = created; + controllers.set(agentId, entry); + } + entry.transport.read = async () => (await read({ agentId })).text; + entry.transport.write = text => write({ agentId, text }); + const active = entry.controller; + void active.hydrate(); + void active.flush(); + const subscription = AppState.addEventListener("change", state => { + if (state !== "active") void active.flush(); + else { void active.hydrate(); void active.flush(); } + }); + return () => { subscription.remove(); void active.flush(); }; + }, [agentId, read, write]); +} diff --git a/firstmate/client/chat.tsx b/firstmate/client/chat.tsx index 348c0b16..d33dd43b 100644 --- a/firstmate/client/chat.tsx +++ b/firstmate/client/chat.tsx @@ -23,6 +23,8 @@ import { type PendingAttachment, } from "./attachments"; import { drafts } from "./draft"; +import { prepareDraftSend } from "./draft-send"; +import { useChatDraftPersistence } from "./chat-drafts"; import { lookupIn, recentCandidates } from "./file-links"; import { useFollowEnd } from "./follow-end"; import { isSendKey, type WebKeyPressEvent } from "./keys"; @@ -108,6 +110,7 @@ export function MateChat({ /** Opens a home file in the Files view, the same way a watch's name does. */ onOpenFile: (path: string) => void; }) { + useChatDraftPersistence(mate.id); const toast = useToast(); /** Shared with the surface's suggestion buttons: one message on its way at a time — see `./mate-send`. */ const { sending, send, command: sendMateCommand } = useMateSender(mate.id); @@ -283,25 +286,20 @@ export function MateChat({ }; }, [theme, compact]); - /** - * The draft and its attachments are cleared as the message goes, not when - * the daemon answers: the box stays editable while it is in flight, and a - * follow-up typed in that second must not be wiped by the reply. A failed - * send puts the text back, unless something new has been typed since, and - * its attachments ahead of any attached since. - */ + /** Keep the text durable until delivery succeeds. A follow-up edit wins. */ function sendDraft(): void { const text = draft; const attached = attachments; if (!hasContent(text, attached) || sending) return; - // Through the stores only: this chat may be gone by the time the send fails, and the one on screen follows them. + const finish = prepareDraftSend(drafts, mate.id, text); const sent = send(captainMessage(text, attached), () => { - if (drafts.get(mate.id).trim() === "") drafts.set(mate.id, text); + finish(false); pendingAttachments.set(mate.id, restoreFailed(pendingAttachments.get(mate.id), attached)); + }, () => { + finish(true); }); - if (!sent) return; + if (!sent) { finish(false); return; } follow.pin(); - setDraft(""); setAttachments([]); } diff --git a/firstmate/client/draft-persistence.test.ts b/firstmate/client/draft-persistence.test.ts new file mode 100644 index 00000000..e778ed89 --- /dev/null +++ b/firstmate/client/draft-persistence.test.ts @@ -0,0 +1,95 @@ +import { describe, it, expect, vi } from "vitest"; +import { createDraftStore } from "./draft"; +import { persistDraft } from "./draft-persistence"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} +describe("durable chat drafts", () => { + it("restores from durable storage into a fresh JS runtime", async () => { + let disk = ""; + const first = createDraftStore({}); + const save = persistDraft(first, "mate", async () => disk, async text => { disk = text; }, vi.fn()); + await save.ready; + first.set("mate", "unfinished"); + await save.flush(); + save.stop(); + const fresh = createDraftStore({}); + const restored = persistDraft(fresh, "mate", async () => disk, async () => {}, vi.fn()); + await restored.ready; + expect(fresh.get("mate")).toBe("unfinished"); + restored.stop(); + }); + it("typing then clearing while hydration waits wins over the old saved text", async () => { + const read = deferred(); + const store = createDraftStore({}); + const write = vi.fn(async (_text: string) => {}); + const saved = persistDraft(store, "mate", () => read.promise, write, vi.fn()); + store.set("mate", "new"); + store.set("mate", ""); + read.resolve("stale"); + await saved.ready; + await saved.flush(); + expect(store.get("mate")).toBe(""); + expect(write).toHaveBeenLastCalledWith(""); + saved.stop(); + }); + it("serializes a clear after an in-flight save so it cannot resurrect text", async () => { + const blocked = deferred(); + const store = createDraftStore({}); + let disk = ""; + const saved = persistDraft(store, "mate", async () => disk, async text => { + if (text) await blocked.promise; + disk = text; + }, vi.fn()); + await saved.ready; + store.set("mate", "old"); + const first = saved.flush(); + store.set("mate", ""); + const clear = saved.flush(); + blocked.resolve(); + await Promise.all([first, clear]); + expect(disk).toBe(""); + saved.stop(); + }); + it("keeps failed writes dirty for retry on reconnect or lifecycle flush", async () => { + const store = createDraftStore({}); + const write = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValue(undefined); + const report = vi.fn(); + const saved = persistDraft(store, "mate", async () => "", write, report); + await saved.ready; + store.set("mate", "keep me"); + await saved.flush(); + await saved.flush(); + expect(write).toHaveBeenLastCalledWith("keep me"); + expect(write).toHaveBeenCalledTimes(2); + expect(report).toHaveBeenCalledTimes(1); + saved.stop(); + }); +}); + +it("retries failed hydration without erasing the saved draft", async () => { + const store = createDraftStore({}); + const read = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValue("saved"); + const write = vi.fn(); + const saved = persistDraft(store, "mate", read, write, vi.fn()); + await saved.ready; + expect(write).not.toHaveBeenCalled(); + await saved.hydrate(); + expect(store.get("mate")).toBe("saved"); + saved.stop(); +}); + +it("a re-evaluated bundle's store notifies the existing persistence controller", async () => { + const root = {}; + const old = createDraftStore(root); + const write = vi.fn(async (_text: string) => {}); + const saved = persistDraft(old, "mate", async () => "", write, vi.fn()); + await saved.ready; + createDraftStore(root).set("mate", "after reconnect"); + await saved.flush(); + expect(write).toHaveBeenLastCalledWith("after reconnect"); + saved.stop(); +}); diff --git a/firstmate/client/draft-persistence.ts b/firstmate/client/draft-persistence.ts new file mode 100644 index 00000000..508e30ca --- /dev/null +++ b/firstmate/client/draft-persistence.ts @@ -0,0 +1,65 @@ +import type { DraftStore } from "./draft"; + +/** One controller per composer, retained across navigation. Writes never overlap. + * The 300 ms debounce is flushed on background/unmount; neither a flush nor + * an RPC can guarantee delivery if the OS kills the app before it completes. + */ +export function persistDraft(store: DraftStore, key: string, read: () => Promise, + write: (text: string) => Promise, report: (error: unknown) => void) { + let current = store.get(key); + let edited = current !== ""; + let hydrated = false; + let dirty = edited; + let applying = false; + let timer: ReturnType | undefined; + let pending = Promise.resolve(); + function flush(): Promise { + clearTimeout(timer); + timer = undefined; + if (!hydrated || !dirty) return pending; + dirty = false; + const text = current; + pending = pending.then(async () => { + try { await write(text); } + catch (error) { dirty = true; report(error); } + }); + return pending; + } + function schedule(): void { + clearTimeout(timer); + timer = setTimeout(() => { void flush(); }, 300); + } + const unsubscribe = store.subscribe(() => { + if (applying || current === store.get(key)) return; + current = store.get(key); + edited = true; + dirty = true; + if (current === "") void flush(); + else schedule(); + }); + let loaded = false; + let loading: Promise | undefined; + function hydrate(): Promise { + if (loaded) return Promise.resolve(); + if (loading) return loading; + loading = read().then(text => { + loaded = true; + if (!edited) { + current = text; + applying = true; + store.set(key, text); + applying = false; + } + hydrated = true; + if (dirty) void flush(); + }, error => { + // Retry hydration on reconnect; never save an untouched empty box. + hydrated = true; + report(error); + if (dirty) void flush(); + }).finally(() => { loading = undefined; }); + return loading; + } + const ready = hydrate(); + return { ready, hydrate, flush, stop: () => { unsubscribe(); void flush(); } }; +} diff --git a/firstmate/client/draft-send.test.ts b/firstmate/client/draft-send.test.ts new file mode 100644 index 00000000..03636a46 --- /dev/null +++ b/firstmate/client/draft-send.test.ts @@ -0,0 +1,21 @@ +import { it, expect } from "vitest"; +import { createDraftStore } from "./draft"; +import { prepareDraftSend } from "./draft-send"; + +it("keeps a failed send durable, then clears a successful unchanged send", () => { + const store = createDraftStore({}); + store.set("mate", "words"); + prepareDraftSend(store, "mate", "words")(false); + expect(store.get("mate")).toBe("words"); + prepareDraftSend(store, "mate", "words")(true); + expect(store.get("mate")).toBe(""); +}); +it("does not clear a follow-up even when it is retyped identically", () => { + const store = createDraftStore({}); + store.set("mate", "words"); + const finish = prepareDraftSend(store, "mate", "words"); + store.set("mate", "other"); + store.set("mate", "words"); + finish(true); + expect(store.get("mate")).toBe("words"); +}); diff --git a/firstmate/client/draft-send.ts b/firstmate/client/draft-send.ts new file mode 100644 index 00000000..479ac0cf --- /dev/null +++ b/firstmate/client/draft-send.ts @@ -0,0 +1,11 @@ +import type { DraftStore } from "./draft"; + +/** Clear only after delivery, and only if no follow-up edit occurred meanwhile. */ +export function prepareDraftSend(store: DraftStore, key: string, text: string): (success: boolean) => void { + let changed = false; + const stop = store.subscribe(() => { if (store.get(key) !== text) changed = true; }); + return success => { + stop(); + if (success && !changed && store.get(key) === text) store.set(key, ""); + }; +} diff --git a/firstmate/client/draft.ts b/firstmate/client/draft.ts index fe52f3ef..e0262577 100644 --- a/firstmate/client/draft.ts +++ b/firstmate/client/draft.ts @@ -7,8 +7,8 @@ * connection is back, so every module-scope variable starts over and the * draft with it. The app evaluates the bundle in its own global scope, though, * so a slot on `globalThis` is still there for the new evaluation to find: a - * draft lasts as long as the app does. Not persisted, and not shared between - * devices. + * draft lasts as long as the app does. The CHAT composer also persists text + * through `chat-drafts`; card answers remain memory-only. */ export interface DraftStore { get(key: string): string; @@ -33,17 +33,23 @@ export function createDraftStore(root: object): DraftStore { Reflect.set(root, SLOT, drafts); } const store = drafts; - const listeners = new Set<() => void>(); + const listenerSlot = Symbol.for("paseo.firstmate.draft-listeners"); + let listeners = Reflect.get(root, listenerSlot) as Set<() => void> | undefined; + if (!listeners) { + listeners = new Set<() => void>(); + Reflect.set(root, listenerSlot, listeners); + } + const sharedListeners = listeners; return { get: (key) => store.get(key) ?? "", set: (key, text) => { if (text === "") store.delete(key); else store.set(key, text); - listeners.forEach((listener) => listener()); + sharedListeners.forEach((listener) => listener()); }, subscribe: (listener) => { - listeners.add(listener); - return () => listeners.delete(listener); + sharedListeners.add(listener); + return () => sharedListeners.delete(listener); }, }; } diff --git a/firstmate/index.client.tsx b/firstmate/index.client.tsx index 5fb5232f..ee1e4603 100644 --- a/firstmate/index.client.tsx +++ b/firstmate/index.client.tsx @@ -1,3 +1,4 @@ +import { stopChatDrafts } from "./client/chat-drafts"; import type { PluginClientContext, PluginWorkspaceCommandContext } from "@getpaseo/plugin/client"; import { FleetSurface, bindSettingsOpener } from "./client/fleet"; @@ -117,6 +118,7 @@ export default function contribute(client: PluginClientContext) { }); return () => { + stopChatDrafts(); bindSettingsOpener(null); }; } diff --git a/firstmate/index.server.ts b/firstmate/index.server.ts index b760d6f1..a96f9547 100644 --- a/firstmate/index.server.ts +++ b/firstmate/index.server.ts @@ -1,3 +1,5 @@ +import { readChatDraft, writeChatDraft } from "./server/drafts"; +import { readChatDraft as readChatDraftRpc, writeChatDraft as writeChatDraftRpc } from "./shared/drafts"; import type { PluginServerContext } from "@getpaseo/plugin/server"; import { migrateLegacyFiles, readFirstmateConfig, resolveHome, updateFirstmateConfig } from "./server/config"; @@ -55,6 +57,8 @@ import { displaySettings } from "./shared/settings"; export default function contribute(server: PluginServerContext) { migrateLegacyFiles(); + server.handle(readChatDraftRpc, async ({ agentId }) => ({ text: await readChatDraft(agentId) })); + server.handle(writeChatDraftRpc, async ({ agentId, text }) => { await writeChatDraft(agentId, text); return {}; }); const reports = new ReportCache(); const steers = new CaptainSteers(); // The scripts in the home's watches/ folder, run on their schedules; see server/watches.ts. diff --git a/firstmate/package-lock.json b/firstmate/package-lock.json index dc9479da..cb2d6c10 100644 --- a/firstmate/package-lock.json +++ b/firstmate/package-lock.json @@ -1,12 +1,12 @@ { "name": "@gpambrozio/paseo-firstmate", - "version": "0.4.0", + "version": "0.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@gpambrozio/paseo-firstmate", - "version": "0.4.0", + "version": "0.4.1", "license": "MIT", "devDependencies": { "@getpaseo/client": "0.11.0", diff --git a/firstmate/package.json b/firstmate/package.json index 1e9c730d..bba87c28 100644 --- a/firstmate/package.json +++ b/firstmate/package.json @@ -1,6 +1,6 @@ { "name": "@gpambrozio/paseo-firstmate", - "version": "0.4.0", + "version": "0.4.1", "description": "Paseo plugin: talk to one first mate agent that runs a crew of Paseo agents in their own worktrees, with a live board of the crew", "license": "MIT", "homepage": "https://github.com/gpambrozio/paseo-plugins/tree/main/firstmate", diff --git a/firstmate/server/drafts.test.ts b/firstmate/server/drafts.test.ts new file mode 100644 index 00000000..9b8835e8 --- /dev/null +++ b/firstmate/server/drafts.test.ts @@ -0,0 +1,21 @@ +import { it, expect } from "vitest"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readChatDraft, writeChatDraft, chatDraftFile } from "./drafts"; + +it("persists text and clears in arrival order in an isolated plugin home", async () => { + const before = process.env.PASEO_HOME; + process.env.PASEO_HOME = await mkdtemp(join(tmpdir(), "fm-drafts-")); + const id = "12345678-1234-4234-8234-123456789abc"; + try { + expect(await readChatDraft(id)).toBe(""); + await writeChatDraft(id, "words"); + expect(await readChatDraft(id)).toBe("words"); + await Promise.all([writeChatDraft(id, "older"), writeChatDraft(id, "")]); + expect(await readFile(chatDraftFile(id), "utf8")).toBe(""); + } finally { + if (before === undefined) delete process.env.PASEO_HOME; + else process.env.PASEO_HOME = before; + } +}); diff --git a/firstmate/server/drafts.ts b/firstmate/server/drafts.ts new file mode 100644 index 00000000..7a41419c --- /dev/null +++ b/firstmate/server/drafts.ts @@ -0,0 +1,28 @@ +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { randomUUID } from "node:crypto"; +import { pluginDir } from "./data-dir"; +import { serialized } from "./serialize"; + +/** RPC schemas validate the UUID before it becomes a filename. */ +export function chatDraftFile(agentId: string): string { + return join(pluginDir(), "chat-drafts", `${agentId}.txt`); +} +export async function readChatDraft(agentId: string): Promise { + return serialized(chatDraftFile(agentId), async () => { + try { return await readFile(chatDraftFile(agentId), "utf8"); } + catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return ""; + throw error; + } + }); +} +export async function writeChatDraft(agentId: string, text: string): Promise { + return serialized(chatDraftFile(agentId), async () => { + const directory = join(pluginDir(), "chat-drafts"); + await mkdir(directory, { recursive: true }); + const temporary = join(directory, `${agentId}.${randomUUID()}.tmp`); + await writeFile(temporary, text, { mode: 0o600 }); + await rename(temporary, chatDraftFile(agentId)); + }); +} diff --git a/firstmate/shared/drafts.ts b/firstmate/shared/drafts.ts new file mode 100644 index 00000000..58bad17f --- /dev/null +++ b/firstmate/shared/drafts.ts @@ -0,0 +1,10 @@ +import { defineRpc } from "@getpaseo/plugin"; +import { z } from "zod"; + +const key = z.object({ agentId: z.string().uuid() }); +export const readChatDraft = defineRpc({ + name: "firstmate.drafts.read", input: key, output: z.object({ text: z.string() }), +}); +export const writeChatDraft = defineRpc({ + name: "firstmate.drafts.write", input: key.extend({ text: z.string() }), output: z.object({}), +});