Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions firstmate/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<mate UUID>.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.

Expand Down
4 changes: 4 additions & 0 deletions firstmate/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 49 additions & 0 deletions firstmate/client/chat-drafts.ts
Original file line number Diff line number Diff line change
@@ -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<typeof persistDraft>;
transport: { read: () => Promise<string>; write: (text: string) => Promise<unknown> };
};
const slot = Symbol.for("paseo.firstmate.durable-chat-drafts");
const controllers: Map<string, Entry> = 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]);
}
20 changes: 9 additions & 11 deletions firstmate/client/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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([]);
}

Expand Down
95 changes: 95 additions & 0 deletions firstmate/client/draft-persistence.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { describe, it, expect, vi } from "vitest";
import { createDraftStore } from "./draft";
import { persistDraft } from "./draft-persistence";

function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>(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<string>();
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<void>();
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();
});
65 changes: 65 additions & 0 deletions firstmate/client/draft-persistence.ts
Original file line number Diff line number Diff line change
@@ -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<string>,
write: (text: string) => Promise<unknown>, report: (error: unknown) => void) {
let current = store.get(key);
let edited = current !== "";
let hydrated = false;
let dirty = edited;
let applying = false;
let timer: ReturnType<typeof setTimeout> | undefined;
let pending = Promise.resolve();
function flush(): Promise<void> {
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<void> | undefined;
function hydrate(): Promise<void> {
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(); } };
}
21 changes: 21 additions & 0 deletions firstmate/client/draft-send.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
11 changes: 11 additions & 0 deletions firstmate/client/draft-send.ts
Original file line number Diff line number Diff line change
@@ -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, "");
};
}
18 changes: 12 additions & 6 deletions firstmate/client/draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
},
};
}
Expand Down
2 changes: 2 additions & 0 deletions firstmate/index.client.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { stopChatDrafts } from "./client/chat-drafts";
import type { PluginClientContext, PluginWorkspaceCommandContext } from "@getpaseo/plugin/client";

import { FleetSurface, bindSettingsOpener } from "./client/fleet";
Expand Down Expand Up @@ -117,6 +118,7 @@ export default function contribute(client: PluginClientContext) {
});

return () => {
stopChatDrafts();
bindSettingsOpener(null);
};
}
4 changes: 4 additions & 0 deletions firstmate/index.server.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading