Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(chat): persist conversation migration links (#1772)
Henry Su15b5b3fd87e6
diff --git a/preload.js b/preload.jsindex b8e1e68e6..2861dad05 100644--- a/preload.js+++ b/preload.js@@ -1078,6 +1078,8 @@ contextBridge.exposeInMainWorld("electronAPI", {ipcRenderer.invoke("db-get-conversation-by-client-id", clientId),upsertConversationFromCloud: (cloudConv, messages) =>ipcRenderer.invoke("db-upsert-conversation-from-cloud", cloudConv, messages),+ acknowledgeConversationCreate: (id, snapshot, cloudId) =>+ ipcRenderer.invoke("db-acknowledge-conversation-create", id, snapshot, cloudId),markConversationSynced: (id, cloudId) =>ipcRenderer.invoke("db-mark-conversation-synced", id, cloudId),hardDeleteConversation: (id) => ipcRenderer.invoke("db-hard-delete-conversation", id),diff --git a/src/helpers/database.js b/src/helpers/database.jsindex c0332428d..d57da12e2 100644--- a/src/helpers/database.js+++ b/src/helpers/database.js@@ -5434,6 +5434,80 @@ class DatabaseManager {}}+ acknowledgeConversationCreate(id, snapshot, cloudId) {+ try {+ if (!this.db) throw new Error("Database not initialized");+ if (!snapshot || !cloudId) {+ return { success: false, outcome: "unresolved", cloud_id: null };+ }++ return this.db.transaction(() => {+ const current = this.db+ .prepare(+ `SELECT c.*, COUNT(m.id) AS message_count+ FROM agent_conversations c+ LEFT JOIN agent_messages m ON m.conversation_id = c.id+ WHERE c.id = ?+ GROUP BY c.id`+ )+ .get(id);+ const expectedClientId = snapshot.client_conversation_id ?? null;++ if (!current || (current.client_conversation_id ?? null) !== expectedClientId) {+ const identityStillExists = expectedClientId+ ? this.db+ .prepare("SELECT 1 FROM agent_conversations WHERE client_conversation_id = ?")+ .get(expectedClientId)+ : null;+ return {+ success: true,+ outcome: identityStillExists ? "unresolved" : "orphaned",+ cloud_id: null,+ };+ }++ if (current.cloud_id) {+ return { success: true, outcome: "already-linked", cloud_id: current.cloud_id };+ }++ if (current.deleted_at) {+ this.db+ .prepare(+ `UPDATE agent_conversations+ SET cloud_id = ?, sync_status = 'pending'+ WHERE id = ? AND cloud_id IS NULL`+ )+ .run(cloudId, id);+ return { success: true, outcome: "delete-pending", cloud_id: cloudId };+ }++ const unchanged =+ current.title === snapshot.title &&+ current.updated_at === snapshot.updated_at &&+ Number(current.message_count) === snapshot.message_count;+ if (!unchanged) {+ return { success: true, outcome: "changed", cloud_id: null };+ }++ this.db+ .prepare(+ `UPDATE agent_conversations+ SET cloud_id = ?, sync_status = 'synced'+ WHERE id = ? AND cloud_id IS NULL`+ )+ .run(cloudId, id);+ return { success: true, outcome: "synced", cloud_id: cloudId };+ })();+ } catch (error) {+ debugLogger.error(+ "Error acknowledging conversation create",+ { error: error.message },+ "database"+ );+ throw error;+ }+ }+hardDeleteConversation(id) {try {if (!this.db) throw new Error("Database not initialized");diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex c4a4b01e9..db918fe43 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -2292,6 +2292,9 @@ class IPCHandlers {ipcMain.handle("db-upsert-conversation-from-cloud", (_, cloudConv, messages) =>this.databaseManager.upsertConversationFromCloud(cloudConv, messages));+ ipcMain.handle("db-acknowledge-conversation-create", (_, id, snapshot, cloudId) =>+ this.databaseManager.acknowledgeConversationCreate(id, snapshot, cloudId)+ );ipcMain.handle("db-mark-conversation-synced", (_, id, cloudId) =>this.databaseManager.markConversationSynced(id, cloudId));diff --git a/src/services/SyncService.ts b/src/services/SyncService.tsindex dd4061276..227f45148 100644--- a/src/services/SyncService.ts+++ b/src/services/SyncService.ts@@ -4,6 +4,7 @@ import type {SpaceItem,TranscriptionItem,ConversationPreview,+ ConversationCreateSnapshot,} from "../types/electron";import { NotesService, type CloudNote } from "./NotesService.js";import { ConversationsService } from "./ConversationsService.js";@@ -147,6 +148,24 @@ const PURGED_SPACE_GUARD_LOCK = "openwhispr-purged-spaces";const NOTE_UPDATE_404_KEY = "noteUpdate404Counts";const FOLDER_UPDATE_404_KEY = "folderUpdate404Counts";+interface ConversationCreateSource {+ client_conversation_id?: string | null;+ title: string;+ updated_at: string;+ messages: readonly unknown[];+}++function conversationCreateSnapshot(+ conversation: ConversationCreateSource+): ConversationCreateSnapshot {+ return {+ client_conversation_id: conversation.client_conversation_id ?? null,+ title: conversation.title,+ updated_at: conversation.updated_at,+ message_count: conversation.messages.length,+ };+}+function readPurgedSpaceIds(): Record<string, PurgedSpaceEntry> {try {const raw = localStorage.getItem(PURGED_SPACE_GUARD_KEY);@@ -878,6 +897,27 @@ export class SyncService {return synced?.cloud_id ?? null;}+ private async acknowledgeConversationCreate(+ localId: number,+ snapshot: ConversationCreateSnapshot,+ cloudId: string+ ): Promise<void> {+ const result = await window.electronAPI.acknowledgeConversationCreate?.(+ localId,+ snapshot,+ cloudId+ );+ if (!result?.success) return;++ const shouldDeleteCreate =+ result.outcome === "changed" ||+ result.outcome === "orphaned" ||+ (result.outcome === "already-linked" && result.cloud_id !== cloudId);+ if (shouldDeleteCreate) {+ await ConversationsService.delete(cloudId);+ }+ }+private async pushConversation(id: number): Promise<void> {const full = await window.electronAPI.getAgentConversation?.(id);if (!full) return;@@ -885,8 +925,9 @@ export class SyncService {if (full.cloud_id) {await ConversationsService.update(full.cloud_id, { title: full.title });} else {+ const snapshot = conversationCreateSnapshot(full);const cloud = await ConversationsService.create({- client_conversation_id: String(full.id),+ client_conversation_id: full.client_conversation_id ?? String(full.id),title: full.title,created_at: full.created_at,updated_at: full.updated_at,@@ -900,12 +941,7 @@ export class SyncService {: null,})),});- const linked = await window.electronAPI.markConversationSynced?.(full.id, cloud.id);- if (linked?.success === false) {- // The local row was purged while POST was in flight. It cannot carry a- // delete tombstone, so retire the orphaned cloud row immediately.- await ConversationsService.delete(cloud.id);- }+ await this.acknowledgeConversationCreate(full.id, snapshot, cloud.id);}}@@ -2053,11 +2089,12 @@ export class SyncService {try {const full = await window.electronAPI.getAgentConversation?.(conv.id);if (!full) continue;+ const snapshot = conversationCreateSnapshot(full);const cloudConv = await ConversationsService.create({- client_conversation_id: conv.client_conversation_id ?? String(conv.id),- title: conv.title,- created_at: conv.created_at,- updated_at: conv.updated_at,+ client_conversation_id: full.client_conversation_id ?? String(full.id),+ title: full.title,+ created_at: full.created_at,+ updated_at: full.updated_at,messages: full.messages.map((m) => ({role: m.role,content: m.content,@@ -2068,10 +2105,7 @@ export class SyncService {: null,})),});- const linked = await window.electronAPI.markConversationSynced?.(conv.id, cloudConv.id);- if (linked?.success === false) {- await ConversationsService.delete(cloudConv.id);- }+ await this.acknowledgeConversationCreate(full.id, snapshot, cloudConv.id);} catch (err) {console.error("Conversation sync failed:", err);}diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.tsindex 96401d5cc..d24c9a593 100644--- a/src/stores/chatStore.ts+++ b/src/stores/chatStore.ts@@ -14,13 +14,11 @@ interface ConversationItem {interface ChatState {conversations: ConversationItem[];activeConversationId: number | null;- migration: { total: number; done: number } | null;}const useChatStore = create<ChatState>()(() => ({conversations: [],activeConversationId: null,- migration: null,}));export async function initializeConversations(limit = 50): Promise<ConversationItem[]> {@@ -81,46 +79,3 @@ export function useActiveConversation(): ConversationItem | null {return state.conversations.find((c) => c.id === state.activeConversationId) ?? null;});}--export function useChatMigration(): { total: number; done: number } | null {- return useChatStore((state) => state.migration);-}--export async function startConversationMigration(): Promise<void> {- const allConversations = (await window.electronAPI?.getAgentConversations?.(9999)) ?? [];- const unsynced = allConversations.filter((c) => !c.cloud_id);- if (unsynced.length === 0) return;-- useChatStore.setState({ migration: { total: unsynced.length, done: 0 } });-- const { ConversationsService } = await import("../services/ConversationsService.js");-- for (const conv of unsynced) {- try {- const messages = (await window.electronAPI?.getAgentMessages?.(conv.id)) ?? [];- const cloudConv = await ConversationsService.create({- client_conversation_id: conv.client_conversation_id ?? String(conv.id),- title: conv.title,- created_at: conv.created_at,- updated_at: conv.updated_at,- messages: messages.map((m) => ({- role: m.role,- content: m.content,- })),- });- updateConversation({ ...conv, cloud_id: cloudConv.id });- useChatStore.setState((s) => ({- migration: s.migration- ? {- total: s.migration.total,- done: Math.min(s.migration.done + 1, s.migration.total),- }- : null,- }));- } catch (err) {- console.error("Conversation migration failed:", err);- }- }-- useChatStore.setState({ migration: null });-}diff --git a/src/types/electron.ts b/src/types/electron.tsindex 6d8f78d43..d3ba7145d 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -861,6 +861,19 @@ export interface ConversationPreview {last_message_role?: "user" | "assistant" | "system" | null;}+export interface ConversationCreateSnapshot {+ client_conversation_id?: string | null;+ title: string;+ updated_at: string;+ message_count: number;+}++export interface ConversationCreateAckResult {+ success: boolean;+ outcome: "synced" | "changed" | "already-linked" | "delete-pending" | "orphaned" | "unresolved";+ cloud_id?: string | null;+}+export type OnboardingDemoKind = "dictation" | "assistant";export type OnboardingDemoStatus = "listening" | "processing" | "partial" | "success" | "error";export interface OnboardingDemoEvent {@@ -2226,7 +2239,8 @@ declare global {id: number;title: string;archived_at?: string;- cloud_id?: string;+ cloud_id?: string | null;+ client_conversation_id?: string | null;created_at: string;updated_at: string;messages: Array<{@@ -2816,6 +2830,11 @@ declare global {cloudConv: Record<string, unknown>,messages: Array<Record<string, unknown>>) => Promise<void>;+ acknowledgeConversationCreate?: (+ id: number,+ snapshot: ConversationCreateSnapshot,+ cloudId: string+ ) => Promise<ConversationCreateAckResult | undefined>;markConversationSynced?: (id: number,cloudId: stringdiff --git a/test/helpers/harness/electronApiBridge.js b/test/helpers/harness/electronApiBridge.jsindex 415fe84ab..606f46a1c 100644--- a/test/helpers/harness/electronApiBridge.js+++ b/test/helpers/harness/electronApiBridge.js@@ -134,6 +134,8 @@ function createElectronApi(db, options = {}) {getConversationByClientId: async (clientId) => db.getConversationByClientId(clientId),upsertConversationFromCloud: async (cloudConv, messages) =>db.upsertConversationFromCloud(cloudConv, messages),+ acknowledgeConversationCreate: async (id, snapshot, cloudId) =>+ db.acknowledgeConversationCreate(id, snapshot, cloudId),markConversationSynced: async (id, cloudId) => db.markConversationSynced(id, cloudId),hardDeleteConversation: async (id) => db.hardDeleteConversation(id),diff --git a/test/helpers/syncServiceConversations.test.js b/test/helpers/syncServiceConversations.test.jsindex 7bbeb70e1..a4178402f 100644--- a/test/helpers/syncServiceConversations.test.js+++ b/test/helpers/syncServiceConversations.test.js@@ -59,6 +59,83 @@ function queryParam(path, name) {return new URLSearchParams(query ?? "").get(name);}+function pauseNextConversationCreate(api) {+ const request = api.cloudApiRequest;+ let resume;+ let signalStarted;+ const started = new Promise((resolve) => {+ signalStarted = resolve;+ });+ const resumed = new Promise((resolve) => {+ resume = resolve;+ });++ api.cloudApiRequest = async (options) => {+ if (options.method === "POST" && options.path === "/api/conversations/create") {+ signalStarted();+ await resumed;+ api.cloudApiRequest = request;+ }+ return request(options);+ };++ return { started, resume };+}++test("a conversation changed during create retries with its complete message history", async (t) => {+ const ctx = await setup(t);+ if (!ctx) return;+ const { db, cloud, api, service } = ctx;+ const conversation = db.createAgentConversation("In-flight conversation");+ db.addAgentMessage(conversation.id, "user", "first message");+ const gate = pauseNextConversationCreate(api);++ const firstSync = service.syncAll(true);+ await gate.started;+ db.addAgentMessage(conversation.id, "assistant", "late message");+ gate.resume();+ await firstSync;++ const pending = db.getAgentConversation(conversation.id);+ assert.equal(pending.cloud_id, null);+ assert.equal(pending.sync_status, "pending");+ assert.equal(cloud.logFor("/api/conversations/delete").length, 1);++ await service.syncAll(true);++ const creates = cloud.logFor("/api/conversations/create");+ assert.equal(creates.length, 2);+ assert.deepEqual(+ creates[1].body.messages.map((message) => message.content),+ ["first message", "late message"]+ );+ const synced = db.getAgentConversation(conversation.id);+ assert.ok(synced.cloud_id);+ assert.equal(synced.sync_status, "synced");++ await service.syncAll(true);+ assert.equal(cloud.logFor("/api/conversations/create").length, 2);+});++test("a losing concurrent conversation create is deleted without replacing the winner", async (t) => {+ const ctx = await setup(t);+ if (!ctx) return;+ const { db, cloud, api, service } = ctx;+ const conversation = db.createAgentConversation("Concurrent conversation");+ db.addAgentMessage(conversation.id, "user", "hello");+ const gate = pauseNextConversationCreate(api);++ const sync = service.syncAll(true);+ await gate.started;+ db.markConversationSynced(conversation.id, "cloud-winner");+ gate.resume();+ await sync;++ const current = db.getAgentConversation(conversation.id);+ assert.equal(current.cloud_id, "cloud-winner");+ assert.equal(cloud.logFor("/api/conversations/delete").length, 1);+});+test("pullConversations applies a strictly newer cloud copy and rejects older and tied ones", async (t) => {const ctx = await setup(t);if (!ctx) return;