Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mobilehog): save composer drafts per chat (#109524)

Dylan Martina22e8155fe8d
diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/index.tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/index.tsx
index c4b71aad28f5..aa85ae152c19 100644
--- a/products/desktop/apps/mobilehog/src/app/(drawer)/index.tsx
+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/index.tsx
@@ -12,6 +12,7 @@ import { DrawerScene } from "@/components/DrawerScene";
import { Logomark } from "@/components/Icons";
import type { Photo } from "@/lib/attachments";
import { sessionIdentity, useAuth } from "@/lib/auth";
+import { moveDraft, NEW_CHAT_DRAFT } from "@/lib/cache";
import {
createAndRunTask,
useDefaultRepository,
@@ -59,6 +60,7 @@ export default function NewChatScreen() {
});
if (sessionIdentity() !== identity) return;
adopt(tempId, task);
+ moveDraft(tempId, task.id);
invalidateTasks();
router.replace({
pathname: "/(drawer)/task/[id]",
@@ -67,6 +69,9 @@ export default function NewChatScreen() {
} catch (err) {
if (sessionIdentity() !== identity) return;
failPending(tempId, err instanceof Error ? err.message : String(err));
+ // The placeholder chat cannot resend, so give the message back to the
+ // new-chat composer.
+ throw err;
}
};
@@ -86,6 +91,7 @@ export default function NewChatScreen() {
repository={repository.data ?? null}
onSend={send}
autoFocus
+ draftKey={NEW_CHAT_DRAFT}
/>
</View>
</KeyboardStickyView>
diff --git a/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx b/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx
index f08608a70dd9..0e97531716a1 100644
--- a/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx
+++ b/products/desktop/apps/mobilehog/src/app/(drawer)/task/[id].tsx
@@ -184,6 +184,7 @@ export default function TaskScreen() {
onStop={isPending ? undefined : () => cancelTurn(id)}
busy={session?.turnActive}
sending={isPending}
+ draftKey={id}
/>
</View>
</View>
diff --git a/products/desktop/apps/mobilehog/src/components/Composer.tsx b/products/desktop/apps/mobilehog/src/components/Composer.tsx
index 7eec5876a8df..c6de0fa7243b 100644
--- a/products/desktop/apps/mobilehog/src/components/Composer.tsx
+++ b/products/desktop/apps/mobilehog/src/components/Composer.tsx
@@ -2,7 +2,7 @@ import { Host, Image as SymbolImage } from "@expo/ui/swift-ui";
import { getReasoningEffortOptions } from "@posthog/shared";
import * as Haptics from "expo-haptics";
import { useFocusEffect, useRouter } from "expo-router";
-import { useCallback, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import {
ActivityIndicator,
Alert,
@@ -26,6 +26,8 @@ import { Glass } from "@/components/Glass";
import { ArrowUpIcon, StopIcon } from "@/components/Icons";
import { Waveform } from "@/components/Waveform";
import { MAX_PHOTOS, type Photo, pickPhotos } from "@/lib/attachments";
+import { sessionIdentity } from "@/lib/auth";
+import { beginSend, type Draft, loadDraft, saveDraft } from "@/lib/cache";
import { useComposer } from "@/lib/composer";
import { useDictation } from "@/lib/dictation";
import { shortModelName } from "@/lib/models";
@@ -56,8 +58,12 @@ interface ComposerProps {
busy?: boolean;
sending?: boolean;
autoFocus?: boolean;
+ // Where the unsent text and photos are kept; omit to keep no draft.
+ draftKey?: string;
}
+const DRAFT_DELAY = 400;
+
export function Composer({
placeholder,
repository,
@@ -66,10 +72,14 @@ export function Composer({
busy,
sending,
autoFocus,
+ draftKey,
}: ComposerProps) {
const router = useRouter();
- const [text, setText] = useState("");
- const [photos, setPhotos] = useState<Photo[]>([]);
+ const [initial] = useState(() => (draftKey ? loadDraft(draftKey) : null));
+ const [text, setText] = useState(initial?.text ?? "");
+ const [photos, setPhotos] = useState<Photo[]>(initial?.photos ?? []);
+ const latest = useRef<Draft>({ text, photos });
+ const hydratedKey = useRef(draftKey);
const withSpeech = (base: string, heard: string): string =>
[base.trim(), heard.trim()].filter(Boolean).join(" ");
const dictation = useDictation((heard) =>
@@ -89,6 +99,38 @@ export function Composer({
!sending &&
!dictation.stopping;
+ useEffect(() => {
+ latest.current = { text, photos };
+ }, [text, photos]);
+
+ // The chat screen stays mounted across chats, so swap drafts with the key.
+ useEffect(() => {
+ if (draftKey === hydratedKey.current) return;
+ hydratedKey.current = draftKey;
+ const saved = draftKey ? loadDraft(draftKey) : null;
+ setText(saved?.text ?? "");
+ setPhotos(saved?.photos ?? []);
+ }, [draftKey]);
+
+ useEffect(() => {
+ if (!draftKey) return;
+ const timer = setTimeout(
+ () => saveDraft(draftKey, { text, photos }),
+ DRAFT_DELAY,
+ );
+ return () => clearTimeout(timer);
+ }, [draftKey, text, photos]);
+
+ // Leaving inside the debounce window still keeps the draft. A sign-out or
+ // project switch remounts the app after the session changed, so skip that.
+ useEffect(() => {
+ if (!draftKey) return;
+ const identity = sessionIdentity();
+ return () => {
+ if (sessionIdentity() === identity) saveDraft(draftKey, latest.current);
+ };
+ }, [draftKey]);
+
const attach = async (): Promise<void> => {
try {
const picked = await pickPhotos(MAX_PHOTOS - photos.length);
@@ -124,13 +166,22 @@ export function Composer({
const attached = photos;
setText("");
setPhotos([]);
+ latest.current = { text: "", photos: [] };
+ const settle = draftKey
+ ? beginSend(draftKey, { text: value, photos: attached })
+ : undefined;
try {
await onSend(value, attached);
} catch {
- // Keep a draft the person started while the send was in flight.
- setText((current) => current || value);
- setPhotos((current) => (current.length ? current : attached));
+ settle?.(false);
+ if (hydratedKey.current === draftKey) {
+ // Keep a draft the person started while the send was in flight.
+ setText((current) => (current.trim() ? current : value));
+ setPhotos((current) => (current.length ? current : attached));
+ }
+ return;
}
+ settle?.(true);
};
return (
diff --git a/products/desktop/apps/mobilehog/src/lib/cache.test.ts b/products/desktop/apps/mobilehog/src/lib/cache.test.ts
new file mode 100644
index 000000000000..ebec466bd030
--- /dev/null
+++ b/products/desktop/apps/mobilehog/src/lib/cache.test.ts
@@ -0,0 +1,280 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => {
+ const stores = new Map<string, Map<string, string>>();
+ const existing = new Set<string>();
+ const session = {
+ region: "us",
+ host: "https://us.posthog.com",
+ apiKey: "key",
+ projectId: 1,
+ projectName: "Project",
+ userId: 7,
+ userName: "Max",
+ };
+ const auth = { session: session as typeof session | null };
+
+ function createMMKV({ id }: { id: string }) {
+ let data = stores.get(id);
+ if (!data) {
+ data = new Map();
+ stores.set(id, data);
+ }
+ const values = data;
+ return {
+ getString: (key: string) => values.get(key),
+ set: (key: string, value: string) => values.set(key, value),
+ remove: (key: string) => values.delete(key),
+ contains: (key: string) => values.has(key),
+ };
+ }
+
+ class MockFile {
+ exists: boolean;
+ constructor(uri: string) {
+ this.exists = existing.has(uri);
+ }
+ }
+
+ return { auth, createMMKV, existing, MockFile, session, stores };
+});
+
+vi.mock("react-native-mmkv", () => ({
+ createMMKV: mocks.createMMKV,
+ deleteMMKV: (id: string) => mocks.stores.delete(id),
+}));
+vi.mock("expo-secure-store", () => ({
+ getItem: () => "secret",
+ setItem: vi.fn(),
+}));
+vi.mock("expo-crypto", () => ({ getRandomBytes: () => new Uint8Array(16) }));
+vi.mock("expo-file-system", () => ({ File: mocks.MockFile }));
+vi.mock("@/lib/auth", () => ({
+ useAuth: { getState: () => mocks.auth },
+}));
+
+import type { Photo } from "./attachments";
+import {
+ accountStore,
+ beginSend,
+ clearAccountCache,
+ keepUnsent,
+ loadDraft,
+ moveDraft,
+ NEW_CHAT_DRAFT,
+ saveDraft,
+} from "./cache";
+
+function photo(uri: string): Photo {
+ return { id: uri, uri, name: "photo.jpg", mimeType: "image/jpeg", size: 3 };
+}
+
+function draftIndex(): string[] {
+ const store = accountStore(mocks.session as never);
+ return JSON.parse(store.getString("draft-1-index") ?? "[]");
+}
+
+beforeEach(() => {
+ mocks.stores.clear();
+ mocks.existing.clear();
+ mocks.auth.session = { ...mocks.session };
+ clearAccountCache(mocks.session as never);
+});
+
+describe("drafts", () => {
+ it("restores the text and photos that were saved", () => {
+ mocks.existing.add("file:///a.jpg");
+ saveDraft("task-1", { text: "hello", photos: [photo("file:///a.jpg")] });
+
+ expect(loadDraft("task-1")).toEqual({
+ text: "hello",
+ photos: [photo("file:///a.jpg")],
+ });
+ expect(loadDraft(NEW_CHAT_DRAFT)).toBeNull();
+ });
+
+ it("drops photos whose file is gone", () => {
+ mocks.existing.add("file:///kept.jpg");
+ saveDraft("task-1", {
+ text: "look",
+ photos: [photo("file:///kept.jpg"), photo("file:///purged.jpg")],
+ });
+
+ expect(loadDraft("task-1")?.photos).toEqual([photo("file:///kept.jpg")]);
+ });
+
+ it("returns nothing when only missing photos remain", () => {
+ saveDraft("task-1", { text: " ", photos: [photo("file:///purged.jpg")] });
+
+ expect(loadDraft("task-1")).toBeNull();
+ });
+
+ it("removes the key when the draft is empty", () => {
+ saveDraft("task-1", { text: "hello", photos: [] });
+ saveDraft("task-1", { text: " ", photos: [] });
+
+ expect(loadDraft("task-1")).toBeNull();
+ expect(draftIndex()).toEqual([]);
+ });
+
+ it("drops photos with missing fields", () => {
+ mocks.existing.add("file:///a.jpg");
+ const { name: _, ...partial } = photo("file:///a.jpg");
+ saveDraft("task-1", { text: "look", photos: [partial as Photo] });
+
+ expect(loadDraft("task-1")).toEqual({ text: "look", photos: [] });
+ });
+
+ it("ignores index entries that are not strings", () => {
+ accountStore(mocks.session as never).set(
+ "draft-1-index",
+ JSON.stringify([1, "task-1", null]),
+ );
+ saveDraft("task-2", { text: "two", photos: [] });
+
+ expect(draftIndex()).toEqual(["task-2", "task-1"]);
+ });
+
+ it("keeps only the most recent drafts", () => {
+ for (let index = 0; index < 51; index++) {
+ saveDraft(`task-${index}`, { text: `draft ${index}`, photos: [] });
+ }
+
+ expect(loadDraft("task-0")).toBeNull();
+ expect(loadDraft("task-1")?.text).toBe("draft 1");
+ expect(loadDraft("task-50")?.text).toBe("draft 50");
+ expect(draftIndex()).toHaveLength(50);
+ });
+
+ it("keeps drafts per project", () => {
+ saveDraft(NEW_CHAT_DRAFT, { text: "first project", photos: [] });
+ mocks.auth.session = { ...mocks.session, projectId: 2 };
+
+ expect(loadDraft(NEW_CHAT_DRAFT)).toBeNull();
+ });
+
+ it("does nothing without a session", () => {
+ mocks.auth.session = null;
+ saveDraft("task-1", { text: "hello", photos: [] });
+
+ expect(loadDraft("task-1")).toBeNull();
+ expect(mocks.stores.size).toBe(0);
+ });
+
+ it("is wiped with the account cache", () => {
+ saveDraft("task-1", { text: "hello", photos: [] });
+ clearAccountCache(mocks.session as never);
+
+ expect(loadDraft("task-1")).toBeNull();
+ });
+
+ it("ignores a corrupt entry", () => {
+ accountStore(mocks.session as never).set("draft-1-task-1", "{");
+
+ expect(loadDraft("task-1")).toBeNull();
+ });
+
+ it("moves a draft and sends later saves to the new key", () => {
+ saveDraft("new-1", { text: "typed", photos: [] });
+ moveDraft("new-1", "task-1");
+
+ expect(loadDraft("task-1")?.text).toBe("typed");
+ expect(draftIndex()).toEqual(["task-1"]);
+
+ saveDraft("new-1", { text: "typed more", photos: [] });
+
+ expect(loadDraft("task-1")?.text).toBe("typed more");
+ expect(draftIndex()).toEqual(["task-1"]);
+ });
+});
+
+describe("keepUnsent", () => {
+ const unsent = { text: "sent", photos: [photo("file:///sent.jpg")] };
+
+ it("restores the unsent message into an empty draft", () => {
+ expect(keepUnsent({ text: " ", photos: [] }, unsent)).toEqual(unsent);
+ });
+
+ it("keeps what was typed since the send", () => {
+ const typed = { text: "new", photos: [photo("file:///new.jpg")] };
+
+ expect(keepUnsent(typed, unsent)).toEqual(typed);
+ expect(keepUnsent({ text: "new", photos: [] }, unsent)).toEqual({
+ text: "new",
+ photos: unsent.photos,
+ });
+ });
+});
+
+describe("sending a draft", () => {
+ it("keeps the message saved until the send goes out", () => {
+ saveDraft("task-1", { text: "hello", photos: [] });
+ const settle = beginSend("task-1", { text: "hello", photos: [] });
+
+ expect(loadDraft("task-1")).toBeNull();
+ expect(draftIndex()).toEqual(["task-1"]);
+
+ settle(true);
+
+ expect(loadDraft("task-1")).toBeNull();
+ expect(draftIndex()).toEqual([]);
+ });
+
+ it("keeps text typed during the send after it goes out", () => {
+ const settle = beginSend("task-1", { text: "hello", photos: [] });
+ saveDraft("task-1", { text: "next", photos: [] });
+ settle(true);
+
+ expect(loadDraft("task-1")?.text).toBe("next");
+ });
+
+ it("returns the message to the draft when the send fails", () => {
+ const settle = beginSend("task-1", { text: "hello", photos: [] });
+ saveDraft("task-1", { text: " ", photos: [] });
+ settle(false);
+
+ expect(loadDraft("task-1")?.text).toBe("hello");
+ });
+
+ it("restores a send the app did not finish", async () => {
+ beginSend("task-1", { text: "hello", photos: [] });
+ vi.resetModules();
+ const relaunched = await import("./cache");
+
+ expect(relaunched.loadDraft("task-1")?.text).toBe("hello");
+ relaunched.saveDraft("task-1", { text: "", photos: [] });
+ expect(relaunched.loadDraft("task-1")).toBeNull();
+ });
+
+ it("does not write after the project changed", () => {
+ const settle = beginSend("task-1", { text: "hello", photos: [] });
+ mocks.auth.session = { ...mocks.session, projectId: 2 };
+ settle(false);
+
+ expect(loadDraft("task-1")).toBeNull();
+ mocks.auth.session = { ...mocks.session };
+ expect(loadDraft("task-1")?.text).toBe("hello");
+ });
+
+ it("keeps a pending message out of another account", () => {
+ beginSend(NEW_CHAT_DRAFT, { text: "private", photos: [] });
+ const other = { ...mocks.session, host: "https://eu.posthog.com" };
+ mocks.auth.session = other;
+ saveDraft(NEW_CHAT_DRAFT, { text: "", photos: [] });
+
+ expect(loadDraft(NEW_CHAT_DRAFT)).toBeNull();
+ expect(accountStore(other as never).getString("draft-1-new-chat")).toBe(
+ undefined,
+ );
+ });
+
+ it("drops pending messages with the account cache", () => {
+ beginSend(NEW_CHAT_DRAFT, { text: "private", photos: [] });
+ clearAccountCache(mocks.session as never);
+ saveDraft(NEW_CHAT_DRAFT, { text: "", photos: [] });
+
+ expect(
+ accountStore(mocks.session as never).getString("draft-1-new-chat"),
+ ).toBe(undefined);
+ });
+});
diff --git a/products/desktop/apps/mobilehog/src/lib/cache.ts b/products/desktop/apps/mobilehog/src/lib/cache.ts
index cacea9cecb66..04f38e2da52e 100644
--- a/products/desktop/apps/mobilehog/src/lib/cache.ts
+++ b/products/desktop/apps/mobilehog/src/lib/cache.ts
@@ -5,8 +5,10 @@ import {
persistQueryClientSubscribe,
} from "@tanstack/react-query-persist-client";
import * as Crypto from "expo-crypto";
+import { File } from "expo-file-system";
import * as SecureStore from "expo-secure-store";
import { createMMKV, deleteMMKV, type MMKV } from "react-native-mmkv";
+import type { Photo } from "@/lib/attachments";
import { type Session, useAuth } from "@/lib/auth";
import type { Block } from "@/lib/transcript";
@@ -51,6 +53,7 @@ export function accountStore(session: Session): MMKV {
export function clearAccountCache(session: Session): void {
const id = storeId(session);
stores.delete(id);
+ accountDrafts.delete(id);
deleteMMKV(id);
}
@@ -97,23 +100,57 @@ export function persistQueryCache(
}
const TRANSCRIPT_LIMIT = 50;
+const DRAFT_LIMIT = 50;
+
+// The new-chat composer has no task id yet.
+export const NEW_CHAT_DRAFT = "new-chat";
interface SavedTranscript {
savedAt: number;
blocks: Block[];
}
-function transcriptScope(): { store: MMKV; prefix: string } | null {
+export interface Draft {
+ text: string;
+ photos: Photo[];
+}
+
+function projectScope(kind: string): { store: MMKV; prefix: string } | null {
const { session } = useAuth.getState();
if (!session) return null;
return {
store: accountStore(session),
- prefix: `transcript-${session.projectId}`,
+ prefix: `${kind}-${session.projectId}`,
};
}
+function readIndex(store: MMKV, prefix: string): string[] {
+ try {
+ const order = JSON.parse(store.getString(`${prefix}-index`) ?? "[]");
+ return Array.isArray(order)
+ ? order.filter((item): item is string => typeof item === "string")
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+// Moves the id to the front and drops the oldest entries past the limit.
+function touchIndex(
+ store: MMKV,
+ prefix: string,
+ id: string,
+ limit: number,
+): void {
+ const order = [id, ...readIndex(store, prefix).filter((item) => item !== id)];
+ for (const stale of order.slice(limit)) {
+ store.remove(`${prefix}-${stale}`);
+ }
+ store.set(`${prefix}-index`, JSON.stringify(order.slice(0, limit)));
+}
+
export function loadTranscript(taskId: string): Block[] | null {
- const scope = transcriptScope();
+ const scope = projectScope("transcript");
const raw = scope?.store.getString(`${scope.prefix}-${taskId}`);
if (!raw) return null;
try {
@@ -124,21 +161,185 @@ export function loadTranscript(taskId: string): Block[] | null {
}
}
-// Keeps the most recently saved chats and drops the oldest past the limit.
export function saveTranscript(taskId: string, blocks: Block[]): void {
- const scope = transcriptScope();
+ const scope = projectScope("transcript");
if (!scope || blocks.length === 0) return;
- const { store, prefix } = scope;
const saved: SavedTranscript = { savedAt: Date.now(), blocks };
- store.set(`${prefix}-${taskId}`, JSON.stringify(saved));
- const indexKey = `${prefix}-index`;
- let order: string[] = [];
+ scope.store.set(`${scope.prefix}-${taskId}`, JSON.stringify(saved));
+ touchIndex(scope.store, scope.prefix, taskId, TRANSCRIPT_LIMIT);
+}
+
+interface AccountDrafts {
+ // A placeholder chat gets its task id after its screen saved under the
+ // temporary id, so writes to that id follow the move.
+ moved: Map<string, string>;
+ // Messages whose send has not settled, by storage id. A saved message with
+ // no entry here is from a send the app did not finish.
+ sending: Map<string, Draft>;
+}
+
+interface DraftScope {
+ store: MMKV;
+ prefix: string;
+ key: string;
+ id: string;
+ drafts: AccountDrafts;
+}
+
+const accountDrafts = new Map<string, AccountDrafts>();
+
+function draftScope(key: string): DraftScope | null {
+ const { session } = useAuth.getState();
+ if (!session) return null;
+ const account = storeId(session);
+ let drafts = accountDrafts.get(account);
+ if (!drafts) {
+ drafts = { moved: new Map(), sending: new Map() };
+ accountDrafts.set(account, drafts);
+ }
+ const prefix = `draft-${session.projectId}`;
+ const target = drafts.moved.get(`${prefix}-${key}`) ?? key;
+ return {
+ store: accountStore(session),
+ prefix,
+ key: target,
+ id: `${prefix}-${target}`,
+ drafts,
+ };
+}
+
+function hasContent(draft: Draft): boolean {
+ return draft.text.trim().length > 0 || draft.photos.length > 0;
+}
+
+// Picker copies live in the caches directory, which iOS can purge between
+// launches, so photos whose file is gone are dropped.
+function isUsablePhoto(value: unknown): value is Photo {
+ const photo = value as Partial<Photo> | null;
+ if (
+ typeof photo?.id !== "string" ||
+ typeof photo.uri !== "string" ||
+ typeof photo.name !== "string" ||
+ typeof photo.mimeType !== "string" ||
+ typeof photo.size !== "number"
+ ) {
+ return false;
+ }
try {
- order = JSON.parse(store.getString(indexKey) ?? "[]");
- } catch {}
- order = [taskId, ...order.filter((id) => id !== taskId)];
- for (const stale of order.slice(TRANSCRIPT_LIMIT)) {
- store.remove(`${prefix}-${stale}`);
+ return new File(photo.uri).exists;
+ } catch {
+ return false;
}
- store.set(indexKey, JSON.stringify(order.slice(0, TRANSCRIPT_LIMIT)));
+}
+
+function parseDraft(value: unknown): Draft {
+ const draft = (value ?? {}) as { text?: unknown; photos?: unknown };
+ return {
+ text: typeof draft.text === "string" ? draft.text : "",
+ photos: Array.isArray(draft.photos)
+ ? draft.photos.filter(isUsablePhoto)
+ : [],
+ };
+}
+
+function readDraft(
+ store: MMKV,
+ id: string,
+): { draft: Draft; unsent: Draft | null } | null {
+ const raw = store.getString(id);
+ if (!raw) return null;
+ try {
+ const saved = JSON.parse(raw);
+ return {
+ draft: parseDraft(saved),
+ unsent: saved?.unsent ? parseDraft(saved.unsent) : null,
+ };
+ } catch {
+ return null;
+ }
+}
+
+function removeDraft({ store, prefix, key, id }: DraftScope): void {
+ if (!store.contains(id)) return;
+ store.remove(id);
+ store.set(
+ `${prefix}-index`,
+ JSON.stringify(readIndex(store, prefix).filter((item) => item !== key)),
+ );
+}
+
+function writeDraft(scope: DraftScope, draft: Draft): void {
+ const unsent = scope.drafts.sending.get(scope.id);
+ if (!hasContent(draft) && !unsent) {
+ removeDraft(scope);
+ return;
+ }
+ scope.store.set(
+ scope.id,
+ JSON.stringify({ text: draft.text, photos: draft.photos, unsent }),
+ );
+ touchIndex(scope.store, scope.prefix, scope.key, DRAFT_LIMIT);
+}
+
+// What the composer gets back when a send fails: text and photos typed since
+// then win over the unsent ones.
+export function keepUnsent(typed: Draft, unsent: Draft): Draft {
+ return {
+ text: typed.text.trim() ? typed.text : unsent.text,
+ photos: typed.photos.length ? typed.photos : unsent.photos,
+ };
+}
+
+export function loadDraft(key: string): Draft | null {
+ const scope = draftScope(key);
+ if (!scope) return null;
+ const saved = readDraft(scope.store, scope.id);
+ if (!saved) return null;
+ let { draft } = saved;
+ if (saved.unsent && !scope.drafts.sending.has(scope.id)) {
+ draft = keepUnsent(draft, saved.unsent);
+ writeDraft(scope, draft);
+ }
+ return hasContent(draft) ? draft : null;
+}
+
+export function saveDraft(key: string, draft: Draft): void {
+ const scope = draftScope(key);
+ if (scope) writeDraft(scope, { text: draft.text, photos: draft.photos });
+}
+
+// Keeps the message in the saved draft until the send settles, so it survives
+// the app closing mid-send. Call the result with whether the send went out.
+export function beginSend(
+ key: string,
+ message: Draft,
+): (sent: boolean) => void {
+ const scope = draftScope(key);
+ if (!scope) return () => {};
+ scope.drafts.sending.set(scope.id, message);
+ writeDraft(scope, { text: "", photos: [] });
+ return (sent) => {
+ if (scope.drafts.sending.get(scope.id) === message) {
+ scope.drafts.sending.delete(scope.id);
+ }
+ const current = projectScope("draft");
+ if (current?.store !== scope.store || current.prefix !== scope.prefix) {
+ return;
+ }
+ const typed = readDraft(scope.store, scope.id)?.draft ?? {
+ text: "",
+ photos: [],
+ };
+ writeDraft(scope, sent ? typed : keepUnsent(typed, message));
+ };
+}
+
+export function moveDraft(from: string, to: string): void {
+ const source = draftScope(from);
+ const target = draftScope(to);
+ if (!source || !target) return;
+ source.drafts.moved.set(source.id, target.key);
+ const saved = readDraft(source.store, source.id);
+ removeDraft(source);
+ if (saved) writeDraft(target, saved.draft);
}