Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix: data loss, syncing and chat

Chadpihab4dee6b53bfd
diff --git a/preload.js b/preload.js
index fab8f1934..2305e1cbb 100644
--- a/preload.js
+++ b/preload.js
@@ -913,9 +913,12 @@ contextBridge.exposeInMainWorld("electronAPI", {
getNoteByClientId: (clientNoteId) => ipcRenderer.invoke("db-get-note-by-client-id", clientNoteId),
upsertNoteFromCloud: (cloudNote, localFolderId, localSpaceId) =>
ipcRenderer.invoke("db-upsert-note-from-cloud", cloudNote, localFolderId, localSpaceId),
- markNoteSynced: (id, cloudId) => ipcRenderer.invoke("db-mark-note-synced", id, cloudId),
- markNoteSyncedIfUnchanged: (id, cloudId, snapshotUpdatedAt) =>
- ipcRenderer.invoke("db-mark-note-synced-if-unchanged", id, cloudId, snapshotUpdatedAt),
+ markNoteSynced: (id, cloudId, cloudUpdatedAt) =>
+ ipcRenderer.invoke("db-mark-note-synced", id, cloudId, cloudUpdatedAt),
+ markNoteSyncedIfUnchanged: (id, cloudId, snapshotUpdatedAt, cloudUpdatedAt) =>
+ ipcRenderer.invoke("db-mark-note-synced-if-unchanged", id, cloudId, snapshotUpdatedAt, cloudUpdatedAt),
+ setNoteCloudBase: (id, cloudUpdatedAt) =>
+ ipcRenderer.invoke("db-set-note-cloud-base", id, cloudUpdatedAt),
markNoteSyncError: (id) => ipcRenderer.invoke("db-mark-note-sync-error", id),
hardDeleteNote: (id) => ipcRenderer.invoke("db-hard-delete-note", id),
diff --git a/src/helpers/cloudSyncGuards.js b/src/helpers/cloudSyncGuards.js
index 8f1459a8f..9826f49f6 100644
--- a/src/helpers/cloudSyncGuards.js
+++ b/src/helpers/cloudSyncGuards.js
@@ -42,5 +42,9 @@ export function buildNoteUpdatePayload(note, cloudFolderId) {
expected_speaker_count: note.expected_speaker_count,
folder_id: cloudFolderId ?? null,
updated_at: note.updated_at,
+ // The server revision this device last acked; the server 409s when a newer
+ // write landed since. Omitted for pre-guard rows (null base), which keeps
+ // the legacy last-write-wins contract for them.
+ ...(note.cloud_updated_at ? { base_updated_at: note.cloud_updated_at } : {}),
};
}
diff --git a/src/helpers/database.js b/src/helpers/database.js
index 6a6ce57f9..bdf66000b 100644
--- a/src/helpers/database.js
+++ b/src/helpers/database.js
@@ -849,6 +849,16 @@ class DatabaseManager {
if (!err.message.includes("duplicate column")) throw err;
}
+ // Server updated_at this device last acked (push response or pull),
+ // echoed verbatim as base_updated_at on the next PATCH so the server can
+ // 409 a stale overwrite. Local edits never touch it; NULL means the note
+ // predates the guard and pushes last-write-wins once.
+ try {
+ this.db.exec("ALTER TABLE notes ADD COLUMN cloud_updated_at TEXT");
+ } catch (err) {
+ if (!err.message.includes("duplicate column")) throw err;
+ }
+
// Space vector purges owed to Qdrant while the sidecar was down/booting;
// drained once the vector index is ready.
this.db.exec(`
@@ -3586,8 +3596,9 @@ class DatabaseManager {
INSERT INTO notes (client_note_id, cloud_id, title, content, enhanced_content,
enhancement_prompt, enhanced_at_content_hash, note_type, source_file,
audio_duration_seconds, transcript, folder_id, space_id, participants, calendar_event_id,
- diarization_enabled, expected_speaker_count, updated_by_user_id, sync_status, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?)
+ diarization_enabled, expected_speaker_count, updated_by_user_id, sync_status, created_at, updated_at,
+ cloud_updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'synced', ?, ?, ?)
ON CONFLICT(client_note_id) DO UPDATE SET
cloud_id = excluded.cloud_id,
title = excluded.title,
@@ -3615,7 +3626,8 @@ class DatabaseManager {
updated_by_user_id = COALESCE(excluded.updated_by_user_id, updated_by_user_id),
sync_status = 'synced',
left_team = 0,
- updated_at = excluded.updated_at
+ updated_at = excluded.updated_at,
+ cloud_updated_at = excluded.cloud_updated_at
`);
stmt.run(
cloudNote.client_note_id,
@@ -3637,6 +3649,7 @@ class DatabaseManager {
cloudNote.expected_speaker_count ?? null,
cloudNote.updated_by_user_id || null,
cloudNote.created_at,
+ cloudNote.updated_at,
cloudNote.updated_at
);
return this.db
@@ -3648,14 +3661,17 @@ class DatabaseManager {
}
}
- markNoteSynced(id, cloudId) {
+ markNoteSynced(id, cloudId, cloudUpdatedAt = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ // cloud_updated_at is overwritten even with null: a forked row that
+ // re-creates under a new cloud_id must not keep the old note's base (a
+ // null base just means that push settles last-write-wins once).
this.db
.prepare(
- "UPDATE notes SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ?"
+ "UPDATE notes SET sync_status = 'synced', cloud_id = ?, left_team = 0, cloud_updated_at = ? WHERE id = ?"
)
- .run(cloudId, id);
+ .run(cloudId, cloudUpdatedAt, id);
return { success: true };
} catch (error) {
debugLogger.error("Error marking note synced", { error: error.message }, "database");
@@ -3667,9 +3683,17 @@ class DatabaseManager {
// PATCH was in flight — a mid-flight edit must stay pending so its content
// still pushes (a blind settle would let the next pass re-PATCH the stale
// snapshot over a teammate's newer server copy).
- markNoteSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt) {
+ markNoteSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt, cloudUpdatedAt = null) {
try {
if (!this.db) throw new Error("Database not initialized");
+ // The base advances unconditionally: even when a mid-flight edit keeps
+ // the row pending, the PATCH landed — the next push must echo the new
+ // server revision or it would 409 against this device's own write.
+ if (cloudUpdatedAt) {
+ this.db
+ .prepare("UPDATE notes SET cloud_updated_at = ? WHERE id = ?")
+ .run(cloudUpdatedAt, id);
+ }
const result = this.db
.prepare(
"UPDATE notes SET sync_status = 'synced', cloud_id = ?, left_team = 0 WHERE id = ? AND updated_at = ?"
@@ -3686,6 +3710,20 @@ class DatabaseManager {
}
}
+ // Records the server revision the user knowingly overwrites ("Keep editing"
+ // on the conflict banner). Deliberately leaves updated_at and sync_status
+ // alone — the local edit stays pending and pushes with the advanced base.
+ setNoteCloudBase(id, cloudUpdatedAt) {
+ try {
+ if (!this.db) throw new Error("Database not initialized");
+ this.db.prepare("UPDATE notes SET cloud_updated_at = ? WHERE id = ?").run(cloudUpdatedAt, id);
+ return { success: true };
+ } catch (error) {
+ debugLogger.error("Error setting note cloud base", { error: error.message }, "database");
+ throw error;
+ }
+ }
+
markNoteSyncError(id) {
try {
if (!this.db) throw new Error("Database not initialized");
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index ccdd59c57..05646d264 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -1715,11 +1715,16 @@ class IPCHandlers {
}
return note;
});
- ipcMain.handle("db-mark-note-synced", (_, id, cloudId) =>
- this.databaseManager.markNoteSynced(id, cloudId)
+ ipcMain.handle("db-mark-note-synced", (_, id, cloudId, cloudUpdatedAt) =>
+ this.databaseManager.markNoteSynced(id, cloudId, cloudUpdatedAt)
);
- ipcMain.handle("db-mark-note-synced-if-unchanged", (_, id, cloudId, snapshotUpdatedAt) =>
- this.databaseManager.markNoteSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt)
+ ipcMain.handle(
+ "db-mark-note-synced-if-unchanged",
+ (_, id, cloudId, snapshotUpdatedAt, cloudUpdatedAt) =>
+ this.databaseManager.markNoteSyncedIfUnchanged(id, cloudId, snapshotUpdatedAt, cloudUpdatedAt)
+ );
+ ipcMain.handle("db-set-note-cloud-base", (_, id, cloudUpdatedAt) =>
+ this.databaseManager.setNoteCloudBase(id, cloudUpdatedAt)
);
ipcMain.handle("db-mark-note-sync-error", (_, id) =>
this.databaseManager.markNoteSyncError(id)
diff --git a/src/hooks/useContainerChat.ts b/src/hooks/useContainerChat.ts
index 2dca919b7..4c33bc30a 100644
--- a/src/hooks/useContainerChat.ts
+++ b/src/hooks/useContainerChat.ts
@@ -2,6 +2,7 @@ import { useState, useCallback, useEffect, useMemo } from "react";
import { useChatPersistence } from "../components/chat/useChatPersistence";
import { useChatStreaming, type ChatSearchScope } from "../components/chat/useChatStreaming";
import type { Message, AgentState } from "../components/chat/types";
+import { deriveConversationTitle } from "../lib/conversationTitle";
import type { SpaceItem, FolderItem, NoteItem } from "../types/electron";
const MAX_CONTEXT_NOTES = 12;
@@ -109,7 +110,7 @@ export function useContainerChat({
async (text: string) => {
let convId = conversationId;
if (!convId) {
- const title = folder?.name ?? space.name;
+ const title = deriveConversationTitle(text, folder?.name ?? space.name);
convId = await persistence.createConversation(title, null, {
spaceId: space.id,
folderId,
diff --git a/src/hooks/useNoteDragAndDrop.ts b/src/hooks/useNoteDragAndDrop.ts
index 989d7be92..182a50ef1 100644
--- a/src/hooks/useNoteDragAndDrop.ts
+++ b/src/hooks/useNoteDragAndDrop.ts
@@ -31,6 +31,12 @@ interface UseNoteDragAndDropOptions {
onCrossSpaceDrop: (note: DraggedNoteInfo, target: NoteMoveTarget, commit: () => void) => void;
/** Vetoes cross-space targets: when it returns false the row never accepts the drag. */
canCrossSpaceDrop?: (note: DraggedNoteInfo, target: NoteMoveTarget) => boolean;
+ /**
+ * Fired at most once per drag when the dragged note first hovers a target
+ * the cross-space veto rejected — the drop would otherwise die silently
+ * (no highlight, no dialog), which reads as a broken drag.
+ */
+ onCrossSpaceVeto?: (note: DraggedNoteInfo) => void;
/** Fired after hovering a target for 500ms mid-drag (auto-expand collapsed containers). */
onHoverTarget?: (key: string) => void;
}
@@ -47,6 +53,7 @@ export function useNoteDragAndDrop({
onMoveToTarget,
onCrossSpaceDrop,
canCrossSpaceDrop,
+ onCrossSpaceVeto,
onHoverTarget,
}: UseNoteDragAndDropOptions) {
const [dragState, setDragState] = useState<DragState>({
@@ -60,6 +67,7 @@ export function useNoteDragAndDrop({
const hoverKeyRef = useRef<string | null>(null);
const enterCounterRef = useRef<Map<string, number>>(new Map());
const draggedNoteRef = useRef<DraggedNoteInfo | null>(null);
+ const vetoNotifiedRef = useRef(false);
const clearHoverTimeout = useCallback(() => {
if (hoverTimeoutRef.current) clearTimeout(hoverTimeoutRef.current);
@@ -101,11 +109,13 @@ export function useNoteDragAndDrop({
requestAnimationFrame(() => ghost.remove());
draggedNoteRef.current = note;
+ vetoNotifiedRef.current = false;
setDragState((prev) => ({ ...prev, draggingNoteId: note.id }));
enterCounterRef.current.clear();
},
onDragEnd: () => {
draggedNoteRef.current = null;
+ vetoNotifiedRef.current = false;
clearHoverTimeout();
setDragState((prev) => ({
...prev,
@@ -136,6 +146,8 @@ export function useNoteDragAndDrop({
(targetInfo: DropTargetInfo) => {
const target: NoteMoveTarget = { spaceId: targetInfo.spaceId, folderId: targetInfo.folderId };
const key = targetKey(target);
+ const crossSpaceVetoed = (note: DraggedNoteInfo): boolean =>
+ note.spaceId !== target.spaceId && !!canCrossSpaceDrop && !canCrossSpaceDrop(note, target);
const canDrop = () => {
const note = draggedNoteRef.current;
if (!note) return false;
@@ -144,13 +156,7 @@ export function useNoteDragAndDrop({
? note.folderId === target.folderId
: note.folderId == null && note.spaceId === target.spaceId;
if (isSameContainer) return false;
- if (
- note.spaceId !== target.spaceId &&
- canCrossSpaceDrop &&
- !canCrossSpaceDrop(note, target)
- ) {
- return false;
- }
+ if (crossSpaceVetoed(note)) return false;
// The default Meetings folder of the note's own space stays a non-target.
const isOwnMeetings =
!!targetInfo.isDefaultFolder &&
@@ -167,7 +173,14 @@ export function useNoteDragAndDrop({
},
onDragEnter: (e: React.DragEvent) => {
e.preventDefault();
- if (!canDrop()) return;
+ if (!canDrop()) {
+ const note = draggedNoteRef.current;
+ if (note && crossSpaceVetoed(note) && !vetoNotifiedRef.current) {
+ vetoNotifiedRef.current = true;
+ onCrossSpaceVeto?.(note);
+ }
+ return;
+ }
const count = (enterCounterRef.current.get(key) ?? 0) + 1;
enterCounterRef.current.set(key, count);
if (count === 1) {
@@ -216,7 +229,7 @@ export function useNoteDragAndDrop({
},
};
},
- [onCrossSpaceDrop, canCrossSpaceDrop, onHoverTarget, commitDrop, clearHoverTimeout]
+ [onCrossSpaceDrop, canCrossSpaceDrop, onCrossSpaceVeto, onHoverTarget, commitDrop, clearHoverTimeout]
);
return { dragState, noteDragHandlers, dropTargetHandlers };
diff --git a/src/lib/conversationTitle.ts b/src/lib/conversationTitle.ts
new file mode 100644
index 000000000..354bd93cb
--- /dev/null
+++ b/src/lib/conversationTitle.ts
@@ -0,0 +1,10 @@
+const MAX_TITLE_LENGTH = 40;
+
+// Titles space/folder chats by their first user message so the conversation
+// picker doesn't list N entries all named after the container.
+export function deriveConversationTitle(text: string, fallback: string): string {
+ const collapsed = text.replace(/\s+/g, " ").trim();
+ if (!collapsed) return fallback;
+ if (collapsed.length <= MAX_TITLE_LENGTH) return collapsed;
+ return `${collapsed.slice(0, MAX_TITLE_LENGTH).trimEnd()}…`;
+}
diff --git a/src/services/NotesService.ts b/src/services/NotesService.ts
index a763f6271..64d391897 100644
--- a/src/services/NotesService.ts
+++ b/src/services/NotesService.ts
@@ -21,6 +21,10 @@ interface NoteInput {
folder_id?: string | null;
created_at?: string;
updated_at?: string;
+ // Optimistic-concurrency base on updates: the server updated_at this device
+ // last acked. The server 409s (note_version_conflict) when a newer write
+ // landed; omitted = legacy last-write-wins.
+ base_updated_at?: string;
}
export interface CloudNote {
@@ -62,8 +66,8 @@ async function create(note: NoteInput): Promise<CloudNote> {
async function batchCreate(
notes: NoteInput[]
-): Promise<{ created: { client_note_id: string; id: string }[] }> {
- return cloudPost<{ created: { client_note_id: string; id: string }[] }>(
+): Promise<{ created: { client_note_id: string; id: string; updated_at?: string }[] }> {
+ return cloudPost<{ created: { client_note_id: string; id: string; updated_at?: string }[] }>(
"/api/notes/batch-create",
{ notes }
);
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 3236c87c0..d591f3c78 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -33,7 +33,7 @@ export type AgentStreamChunk =
callId: string;
toolName: string;
displayText: string;
- metadata?: Record<string, unknown>;
+ metadata?: Record<string, unknown> | Array<Record<string, unknown>>;
}
| { type: "done"; finishReason?: string };
@@ -827,7 +827,7 @@ class ReasoningService extends BaseReasoningService {
executeToolCall?: (
name: string,
args: string
- ) => Promise<{ data: string; displayText: string; metadata?: Record<string, unknown> }>;
+ ) => Promise<{ data: string; displayText: string; metadata?: Record<string, unknown> | Array<Record<string, unknown>> }>;
}
): AsyncGenerator<AgentStreamChunk, void, unknown> {
const maxSteps = config.tools?.length ? ReasoningService.MAX_TOOL_STEPS : 1;
@@ -861,7 +861,11 @@ class ReasoningService extends BaseReasoningService {
}
for (const call of pendingToolCalls) {
- let toolResult: { data: string; displayText: string; metadata?: Record<string, unknown> };
+ let toolResult: {
+ data: string;
+ displayText: string;
+ metadata?: Record<string, unknown> | Array<Record<string, unknown>>;
+ };
try {
toolResult = await config.executeToolCall(call.name, call.arguments);
} catch (error) {
diff --git a/src/services/SyncService.ts b/src/services/SyncService.ts
index 29ee3673e..a93f206e9 100644
--- a/src/services/SyncService.ts
+++ b/src/services/SyncService.ts
@@ -22,9 +22,13 @@ import {
normalizeTimestamp,
} from "../helpers/cloudSyncGuards.js";
import {
+ keepPurgedSpaceEntry,
+ normalizePurgedSpaceEntries,
prunePurgedSpaceEntries,
resolvePullCursorAdvance,
revokedNoteForkUpdate,
+ type PurgedSpaceEntry,
+ type PurgedSpaceReason,
} from "./syncPassPolicy";
function isHttpStatus(err: unknown, status: number): boolean {
@@ -48,6 +52,17 @@ function isFolderNameTakenError(err: unknown): boolean {
return err instanceof CloudApiError && err.code === "folder_name_taken";
}
+// Typed 409 from a note PATCH whose base_updated_at is older than the stored
+// row — another device wrote first. The body carries the current cloud note.
+function isNoteVersionConflictError(err: unknown): boolean {
+ return err instanceof CloudApiError && err.code === "note_version_conflict";
+}
+
+function conflictCloudNote(err: unknown): CloudNote | null {
+ const details = (err as CloudApiError).details as { note?: CloudNote } | undefined;
+ return details?.note ?? null;
+}
+
// Extra fields pushed with note/folder payloads so the server files rows into
// the right space scope; `null` scope means the row must not push at all.
type PushScopeFields = { workspace_id?: string | null; space_id?: string | null };
@@ -83,9 +98,11 @@ const CAN_SYNC_KEYS = ["isSignedIn", "cloudBackupEnabled", "isSubscribed"];
// purge initiator records the cloud space id here, and pull/upsert paths park
// rows for recently purged spaces instead of resurrecting them as orphaned
// local rows nothing can ever clean up. Entries are pruned once a spaces pass
-// confirms the space is gone from /api/me/spaces, or after a TTL so a failed
-// delete cannot hide a still-live space forever. Never marked on TEAM delete:
-// a space still accessible via other teams survives the team's archival.
+// confirms the space is gone from /api/me/spaces, when a "revoked" entry's
+// space reappears there (member re-added — the guard must not lock them out,
+// D14), or after a TTL so a failed delete cannot hide a still-live space
+// forever. Never marked on TEAM delete: a space still accessible via other
+// teams survives the team's archival.
const PURGED_SPACE_GUARD_KEY = "purgedSpaceIds";
const PURGED_SPACE_GUARD_TTL_MS = 15 * 60 * 1000;
// Serializes the guard's read-modify-write across windows: a prune inside a
@@ -93,11 +110,15 @@ const PURGED_SPACE_GUARD_TTL_MS = 15 * 60 * 1000;
// entry.
const PURGED_SPACE_GUARD_LOCK = "openwhispr-purged-spaces";
-function readPurgedSpaceIds(): Record<string, number> {
+function readPurgedSpaceIds(): Record<string, PurgedSpaceEntry> {
try {
const raw = localStorage.getItem(PURGED_SPACE_GUARD_KEY);
- const parsed = raw ? (JSON.parse(raw) as Record<string, number>) : {};
- return prunePurgedSpaceEntries(parsed, Date.now(), PURGED_SPACE_GUARD_TTL_MS);
+ const parsed = raw ? (JSON.parse(raw) as Record<string, number | PurgedSpaceEntry>) : {};
+ return prunePurgedSpaceEntries(
+ normalizePurgedSpaceEntries(parsed),
+ Date.now(),
+ PURGED_SPACE_GUARD_TTL_MS
+ );
} catch {
return {};
}
@@ -105,11 +126,14 @@ function readPurgedSpaceIds(): Record<string, number> {
// Call BEFORE purgeSpace, from every purge path (sync revocation, sign-out,
// and the UI's delete-space flow).
-export async function markSpacePurged(cloudSpaceId: string): Promise<void> {
+export async function markSpacePurged(
+ cloudSpaceId: string,
+ reason: PurgedSpaceReason
+): Promise<void> {
await navigator.locks.request(PURGED_SPACE_GUARD_LOCK, () => {
localStorage.setItem(
PURGED_SPACE_GUARD_KEY,
- JSON.stringify({ ...readPurgedSpaceIds(), [cloudSpaceId]: Date.now() })
+ JSON.stringify({ ...readPurgedSpaceIds(), [cloudSpaceId]: { at: Date.now(), reason } })
);
});
}
@@ -117,7 +141,9 @@ export async function markSpacePurged(cloudSpaceId: string): Promise<void> {
async function prunePurgedSpaceIds(liveCloudSpaceIds: Set<string>): Promise<void> {
await navigator.locks.request(PURGED_SPACE_GUARD_LOCK, () => {
const kept = Object.fromEntries(
- Object.entries(readPurgedSpaceIds()).filter(([id]) => liveCloudSpaceIds.has(id))
+ Object.entries(readPurgedSpaceIds()).filter(([id, entry]) =>
+ keepPurgedSpaceEntry(entry, liveCloudSpaceIds.has(id))
+ )
);
localStorage.setItem(PURGED_SPACE_GUARD_KEY, JSON.stringify(kept));
});
@@ -216,7 +242,10 @@ class SyncService {
for (const space of spaces) {
if (space.kind !== "team") continue;
try {
- if (space.cloud_space_id) await markSpacePurged(space.cloud_space_id);
+ // "revoked", not "deleted": the whole guard key is removed once the
+ // sign-out purge completes, and if that removal ever fails a revoked
+ // entry self-heals on the next pass instead of locking the space out.
+ if (space.cloud_space_id) await markSpacePurged(space.cloud_space_id, "revoked");
await window.electronAPI.purgeSpace?.(space.id);
} catch (err) {
console.error(`Purging space ${space.id} on sign-out failed:`, err);
@@ -541,6 +570,11 @@ class SyncService {
private async pushNote(id: number): Promise<void> {
const note = await window.electronAPI.getNote?.(id);
if (!note) return;
+ if (readNoteConflictIds().has(note.client_note_id)) {
+ // An unresolved conflict: the editor's debounced push would auto-resolve
+ // it as local-wins (or 409-spam) before the user chose Keep or Refresh.
+ return;
+ }
const { localToCloud, blockedFolderIds } = await this.buildLocalToCloudFolderMap();
if (note.folder_id && blockedFolderIds.has(note.folder_id)) {
@@ -566,14 +600,18 @@ class SyncService {
try {
if (note.cloud_id) {
- await NotesService.update(note.cloud_id, this.notePushPayload(note, cloudFolderId, scope));
+ const cloud = await NotesService.update(
+ note.cloud_id,
+ this.notePushPayload(note, cloudFolderId, scope)
+ );
// Settle only if the row wasn't edited while the PATCH was in flight;
// a blind settle would leave the delivered snapshot pending and let a
// later pass re-PATCH it over a teammate's newer edit.
await window.electronAPI.markNoteSyncedIfUnchanged?.(
note.id,
note.cloud_id,
- note.updated_at
+ note.updated_at,
+ cloud.updated_at
);
} else {
const cloud = await NotesService.create({
@@ -581,9 +619,16 @@ class SyncService {
...this.notePushPayload(note, cloudFolderId, scope),
created_at: note.created_at,
});
- await window.electronAPI.markNoteSynced?.(note.id, cloud.id);
+ await window.electronAPI.markNoteSynced?.(note.id, cloud.id, cloud.updated_at);
}
} catch (err) {
+ if (isNoteVersionConflictError(err)) {
+ // Another device wrote first. The row stays pending and the banner
+ // asks the user to Refresh or Keep; no requestSyncAll echo.
+ const cloudNote = conflictCloudNote(err);
+ if (cloudNote) await this.surfaceNoteConflict(note.client_note_id, cloudNote);
+ return;
+ }
if (!isTeamAccessError(err)) throw err;
await this.handleRevokedNotePush(note, ctx);
return;
@@ -681,9 +726,9 @@ class SyncService {
if (space.kind !== "team" || !space.cloud_space_id || cloudIds.has(space.cloud_space_id)) {
continue;
}
- await markSpacePurged(space.cloud_space_id);
+ await markSpacePurged(space.cloud_space_id, "revoked");
const purged = await window.electronAPI.purgeSpace?.(space.id);
- this.dispatchSpaceRevoked(space.name);
+ this.dispatchSpaceRevoked(space.name, space.id);
// Never-synced notes survive the purge in Personal (plan §10.6) —
// surface them, never silently.
for (const title of purged?.relocatedTitles ?? []) {
@@ -778,7 +823,7 @@ class SyncService {
if (!ctx.privateSpace) {
if (note.cloud_id) {
await window.electronAPI.hardDeleteNote?.(note.id);
- this.dispatchSpaceRevoked(spaceName);
+ this.dispatchSpaceRevoked(spaceName, note.space_id);
}
return;
}
@@ -815,8 +860,10 @@ class SyncService {
void window.electronAPI.emitSyncEvent?.(name, payload)?.catch(console.error);
}
- private dispatchSpaceRevoked(spaceName: string | null): void {
- this.emitSyncUiEvent("space-revoked", { spaceName });
+ // spaceId is the LOCAL space id: the renderer's displaced-note memo (set
+ // when the space-purged broadcast cleared the open note) is keyed by it.
+ private dispatchSpaceRevoked(spaceName: string | null, spaceId: number | null = null): void {
+ this.emitSyncUiEvent("space-revoked", { spaceName, spaceId });
}
private dispatchNoteRelocated(title: string | null, spaceName: string | null | undefined): void {
@@ -1220,7 +1267,7 @@ class SyncService {
// would strand the edit locally and hand the next pull a stale-but-
// newer cloud copy to overwrite it with.
const cloudFolderId = note.folder_id ? (localToCloud.get(note.folder_id) ?? null) : null;
- await NotesService.update(note.cloud_id!, {
+ const cloud = await NotesService.update(note.cloud_id!, {
client_note_id: note.client_note_id,
...this.notePushPayload(note, cloudFolderId, scope),
});
@@ -1228,10 +1275,17 @@ class SyncService {
await window.electronAPI.markNoteSyncedIfUnchanged?.(
note.id,
note.cloud_id!,
- note.updated_at
+ note.updated_at,
+ cloud.updated_at
);
} catch (err) {
- if (isTeamAccessError(err)) {
+ if (isNoteVersionConflictError(err)) {
+ // Stays pending (not error): unpushed local work awaiting the
+ // user's Keep/Refresh choice; the registry gate above skips the
+ // row on later passes so the 409 doesn't repeat.
+ const cloudNote = conflictCloudNote(err);
+ if (cloudNote) await this.surfaceNoteConflict(note.client_note_id, cloudNote);
+ } else if (isTeamAccessError(err)) {
await this.handleRevokedNotePush(note, ctx);
} else {
await window.electronAPI.markNoteSyncError?.(note.id);
@@ -1260,9 +1314,11 @@ class SyncService {
...scope,
}))
);
- for (const { client_note_id, id: cloudId } of created) {
+ for (const { client_note_id, id: cloudId, updated_at } of created) {
const local = chunk.find(({ note }) => note.client_note_id === client_note_id);
- if (local) await window.electronAPI.markNoteSynced?.(local.note.id, cloudId);
+ if (local) {
+ await window.electronAPI.markNoteSynced?.(local.note.id, cloudId, updated_at ?? null);
+ }
}
} catch {
for (const { note } of chunk) {
diff --git a/src/services/spaceActions.ts b/src/services/spaceActions.ts
index b5f74d521..7b8195bc7 100644
--- a/src/services/spaceActions.ts
+++ b/src/services/spaceActions.ts
@@ -40,16 +40,27 @@ export async function createSpace(
): Promise<{ space: SpaceItem | null; failedMembers: number }> {
const teamIds = [...teams.existingTeamIds];
let failedMembers = 0;
+ let createdTeamId: string | null = null;
if (teams.newTeam) {
const team = await TeamsService.create(workspaceId, { name: teams.newTeam.name });
+ createdTeamId = team.id;
failedMembers = (await settleAddMembers(team.id, teams.newTeam.memberIds)).length;
teamIds.push(team.id);
}
- const cloudSpace = await SpacesService.create(workspaceId, {
- name: input.name,
- emoji: input.emoji,
- team_ids: teamIds,
- });
+ let cloudSpace;
+ try {
+ cloudSpace = await SpacesService.create(workspaceId, {
+ name: input.name,
+ emoji: input.emoji,
+ team_ids: teamIds,
+ });
+ } catch (err) {
+ // The space create failed after the inline team was created (plan limit,
+ // network) — best-effort delete so a retry doesn't duplicate the team.
+ // The team is server-only at this point; nothing local to clean up.
+ if (createdTeamId) await TeamsService.remove(createdTeamId).catch(() => {});
+ throw err;
+ }
const space =
(await window.electronAPI.upsertSpaceFromCloud?.(
cloudSpace as unknown as Record<string, unknown>
@@ -88,7 +99,7 @@ export async function deleteSpace(space: SpaceItem): Promise<{ success: boolean;
return { success: false, error: errorMessage(err) };
}
// Park the space id so an in-flight pull can't resurrect purged rows.
- await markSpacePurged(space.cloud_space_id);
+ await markSpacePurged(space.cloud_space_id, "deleted");
}
// Store cleanup rides on the space-purged broadcast.
return purgeSpace(space.id);
diff --git a/src/services/syncPassPolicy.ts b/src/services/syncPassPolicy.ts
index 79112df30..911d67ab6 100644
--- a/src/services/syncPassPolicy.ts
+++ b/src/services/syncPassPolicy.ts
@@ -33,14 +33,48 @@ export function resolvePullCursorAdvance(pass: {
return { advanceCursor: !pass.teamOnly, advanceTeamCursor: false };
}
+// Why a space was purged locally: "deleted" covers the delete race the guard
+// was built for (the server may not have processed the delete yet, so the
+// space can still appear live); "revoked" covers access loss, where the space
+// reappearing in /api/me/spaces means the member was re-added and the guard
+// must stand down instead of locking them out for the TTL (D14).
+export type PurgedSpaceReason = "revoked" | "deleted";
+
+export interface PurgedSpaceEntry {
+ at: number;
+ reason: PurgedSpaceReason;
+}
+
+// Entries written before the reason field existed are plain timestamps; read
+// them as "deleted" (the conservative guard) so an in-flight delete stays
+// covered — at worst a pre-upgrade revocation entry rides out its TTL once.
+export function normalizePurgedSpaceEntries(
+ raw: Record<string, number | PurgedSpaceEntry>
+): Record<string, PurgedSpaceEntry> {
+ return Object.fromEntries(
+ Object.entries(raw).map(([id, entry]) => [
+ id,
+ typeof entry === "number" ? { at: entry, reason: "deleted" as const } : entry,
+ ])
+ );
+}
+
// Entries older than the TTL are dropped so a failed space delete cannot hide
// a still-live space forever.
export function prunePurgedSpaceEntries(
- entries: Record<string, number>,
+ entries: Record<string, PurgedSpaceEntry>,
now: number,
ttlMs: number
-): Record<string, number> {
- return Object.fromEntries(Object.entries(entries).filter(([, at]) => now - at < ttlMs));
+): Record<string, PurgedSpaceEntry> {
+ return Object.fromEntries(Object.entries(entries).filter(([, { at }]) => now - at < ttlMs));
+}
+
+// Live-set sweep after a spaces pass. Gone from /api/me/spaces → the purge is
+// confirmed server-side, guard done (either reason). Still live + "deleted" →
+// the delete hasn't landed; keep guarding. Still live + "revoked" → the space
+// reappeared after a re-add: drop the entry so it can re-mirror.
+export function keepPurgedSpaceEntry(entry: PurgedSpaceEntry, isLive: boolean): boolean {
+ return isLive && entry.reason === "deleted";
}
export interface RevokedNoteFork {
diff --git a/src/stores/noteStore.ts b/src/stores/noteStore.ts
index 421d5aec6..994fd380c 100644
--- a/src/stores/noteStore.ts
+++ b/src/stores/noteStore.ts
@@ -544,6 +544,22 @@ export function removeNote(id: number): void {
applyContainers(result.notesByContainer, extra);
}
+// The note the user was reading when its space's purge cleared activeNoteId.
+// The space-revoked toast (raised afterwards, from whichever window ran the
+// sync pass) names it; consume-once and short-lived so a stale memo can't
+// attach to a later, unrelated revocation.
+let purgeDisplacedNote: { spaceId: number; title: string | null; at: number } | null = null;
+const PURGE_DISPLACED_NOTE_TTL_MS = 30_000;
+
+export function readPurgeDisplacedNote(spaceId: number): { title: string | null } | null {
+ const memo = purgeDisplacedNote;
+ if (!memo || memo.spaceId !== spaceId || Date.now() - memo.at > PURGE_DISPLACED_NOTE_TTL_MS) {
+ return null;
+ }
+ purgeDisplacedNote = null;
+ return { title: memo.title };
+}
+
function handleSpacePurged(spaceId: number): void {
const state = useNoteStore.getState();
const purgedCloudSpaceId = state.spaces.find((s) => s.id === spaceId)?.cloud_space_id ?? null;
@@ -603,6 +619,11 @@ function handleSpacePurged(spaceId: number): void {
const activeNote = state.activeNoteId != null ? findNoteInState(state, state.activeNoteId) : null;
if (activeNote?.space_id === spaceId) {
extra.activeNoteId = null;
+ // Only synced rows are deleted by the purge; dirty rows relocate to
+ // Personal and already announce themselves with a titled toast.
+ if (activeNote.sync_status === "synced" && activeNote.cloud_id) {
+ purgeDisplacedNote = { spaceId, title: activeNote.title, at: Date.now() };
+ }
}
let fallbackContext: ActiveContext | null = null;
diff --git a/src/types/electron.ts b/src/types/electron.ts
index b5b6c52d5..fada42546 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -65,6 +65,9 @@ export interface NoteItem {
share_token: string | null;
// Last cloud editor; only populated on cloud pull (local edits don't set it).
updated_by_user_id?: string | null;
+ // Server updated_at this device last acked (push response or pull); echoed
+ // as base_updated_at on the next PATCH. Null = pre-guard row, pushes LWW.
+ cloud_updated_at?: string | null;
created_at: string;
updated_at: string;
client_note_id: string;
@@ -2236,12 +2239,14 @@ declare global {
localFolderId: number | null,
localSpaceId?: number | null
) => Promise<NoteItem>;
- markNoteSynced?: (id: number, cloudId: string) => Promise<void>;
+ markNoteSynced?: (id: number, cloudId: string, cloudUpdatedAt?: string | null) => Promise<void>;
markNoteSyncedIfUnchanged?: (
id: number,
cloudId: string,
- snapshotUpdatedAt: string
+ snapshotUpdatedAt: string,
+ cloudUpdatedAt?: string | null
) => Promise<{ success: boolean; changes: number }>;
+ setNoteCloudBase?: (id: number, cloudUpdatedAt: string | null) => Promise<void>;
markNoteSyncError?: (id: number) => Promise<void>;
hardDeleteNote?: (id: number) => Promise<void>;
diff --git a/test/helpers/cloudSyncGuards.test.js b/test/helpers/cloudSyncGuards.test.js
index aee2b7408..eec342d65 100644
--- a/test/helpers/cloudSyncGuards.test.js
+++ b/test/helpers/cloudSyncGuards.test.js
@@ -103,3 +103,28 @@ test("the note update payload carries the pre-mapped cloud folder id", async ()
assert.equal(buildNoteUpdatePayload(localNote, null).folder_id, null);
assert.equal(buildNoteUpdatePayload(localNote, undefined).folder_id, null);
});
+
+// Optimistic-concurrency contract (G2): the PATCH echoes the server revision
+// this device last acked, never the local SQLite updated_at, so the server can
+// 409 a stale overwrite of a teammate's newer edit.
+
+test("the note update payload echoes cloud_updated_at as base_updated_at verbatim", async () => {
+ const { buildNoteUpdatePayload } = await load();
+ const payload = buildNoteUpdatePayload(
+ { ...localNote, cloud_updated_at: "2026-07-22T08:40:00.123Z" },
+ "cloud-folder-3"
+ );
+ assert.equal(payload.base_updated_at, "2026-07-22T08:40:00.123Z");
+ // The local timestamp still rides as updated_at, unchanged:
+ assert.equal(payload.updated_at, "2026-07-22 08:47:00");
+});
+
+test("pre-guard rows omit base_updated_at entirely (legacy last-write-wins)", async () => {
+ const { buildNoteUpdatePayload } = await load();
+ assert.equal("base_updated_at" in buildNoteUpdatePayload(localNote, null), false);
+ assert.equal(
+ "base_updated_at" in
+ buildNoteUpdatePayload({ ...localNote, cloud_updated_at: null }, null),
+ false
+ );
+});
diff --git a/test/helpers/noteCards.test.js b/test/helpers/noteCards.test.js
new file mode 100644
index 000000000..2d31dea26
--- /dev/null
+++ b/test/helpers/noteCards.test.js
@@ -0,0 +1,70 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { extractNoteCards } = require("../../src/components/chat/noteCards.ts");
+
+const completed = (name, metadata, result) => ({
+ id: "tc-1",
+ name,
+ arguments: "{}",
+ status: "completed",
+ result,
+ metadata,
+});
+
+test("note tools with single-object metadata still produce one card each", () => {
+ const cards = extractNoteCards([
+ completed("create_note", { id: 7, title: "Kickoff" }),
+ completed("get_note", { id: 9 }, 'Retrieved note: "Roadmap"'),
+ ]);
+ assert.deepEqual(cards, [
+ { noteId: 7, title: "Kickoff" },
+ { noteId: 9, title: "Roadmap" },
+ ]);
+});
+
+test("search_notes array metadata produces a card per hit, skipping null and non-numeric ids", () => {
+ const cards = extractNoteCards([
+ completed("search_notes", [
+ { id: 3, title: "Sales sync" },
+ { id: null, title: "Cloud-only hit" },
+ { id: "b1c2-uuid", title: "Cloud id hit" },
+ { id: 4, title: "" },
+ ]),
+ ]);
+ assert.deepEqual(cards, [
+ { noteId: 3, title: "Sales sync" },
+ { noteId: 4, title: "Note" },
+ ]);
+});
+
+test("search cards dedupe against note-tool cards and each other", () => {
+ const cards = extractNoteCards([
+ completed("update_note", { id: 3, title: "Sales sync" }),
+ completed("search_notes", [
+ { id: 3, title: "Sales sync" },
+ { id: 5, title: "Q3 plan" },
+ ]),
+ completed("search_notes", [{ id: 5, title: "Q3 plan" }]),
+ ]);
+ assert.deepEqual(cards, [
+ { noteId: 3, title: "Sales sync" },
+ { noteId: 5, title: "Q3 plan" },
+ ]);
+});
+
+test("search cards cap at 5 across the whole turn", () => {
+ const hits = Array.from({ length: 9 }, (_, i) => ({ id: i + 1, title: `Note ${i + 1}` }));
+ const cards = extractNoteCards([
+ completed("search_notes", hits.slice(0, 4)),
+ completed("search_notes", hits.slice(4)),
+ ]);
+ assert.equal(cards.length, 5);
+});
+
+test("incomplete or unknown tools produce nothing", () => {
+ const cards = extractNoteCards([
+ { ...completed("search_notes", [{ id: 1, title: "x" }]), status: "executing" },
+ completed("copy_to_clipboard", { id: 2 }),
+ ]);
+ assert.deepEqual(cards, []);
+});
diff --git a/test/lib/conversationTitle.test.js b/test/lib/conversationTitle.test.js
new file mode 100644
index 000000000..949d5b003
--- /dev/null
+++ b/test/lib/conversationTitle.test.js
@@ -0,0 +1,29 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { deriveConversationTitle } = require("../../src/lib/conversationTitle.ts");
+
+test("short messages become the title verbatim", () => {
+ assert.equal(deriveConversationTitle("Catch me up", "Growth"), "Catch me up");
+});
+
+test("long messages truncate to 40 chars with an ellipsis", () => {
+ const text = "What were the key decisions from the sales sync last Thursday?";
+ const title = deriveConversationTitle(text, "Growth");
+ assert.equal(title.endsWith("…"), true);
+ assert.equal(title.length <= 41, true);
+ assert.equal(title, "What were the key decisions from the sal…");
+});
+
+test("whitespace-only input falls back to the container name", () => {
+ assert.equal(deriveConversationTitle(" \n\t ", "Growth"), "Growth");
+ assert.equal(deriveConversationTitle("", "Growth"), "Growth");
+});
+
+test("internal newlines and runs of spaces collapse to single spaces", () => {
+ assert.equal(deriveConversationTitle("catch\nme up\t please", "Growth"), "catch me up please");
+});
+
+test("a message landing exactly on the limit is not truncated", () => {
+ const text = "x".repeat(40);
+ assert.equal(deriveConversationTitle(text, "Growth"), text);
+});
diff --git a/test/services/syncPassPolicy.test.js b/test/services/syncPassPolicy.test.js
index d70a1afeb..d4acea4bb 100644
--- a/test/services/syncPassPolicy.test.js
+++ b/test/services/syncPassPolicy.test.js
@@ -71,21 +71,42 @@ test("cursor policy: a degraded team-only pass advances nothing", async () => {
});
});
-// --- prunePurgedSpaceEntries ------------------------------------------------
+// --- purged-space guard -----------------------------------------------------
test("purge guard: entries expire strictly at the TTL", async () => {
const { prunePurgedSpaceEntries } = await load();
const now = 1_000_000_000;
const ttl = 900_000;
+ const entry = (at) => ({ at, reason: "deleted" });
const pruned = prunePurgedSpaceEntries(
- { fresh: now - 1, edge: now - ttl, stale: now - ttl - 1 },
+ { fresh: entry(now - 1), edge: entry(now - ttl), stale: entry(now - ttl - 1) },
now,
ttl
);
- assert.deepEqual(pruned, { fresh: now - 1 });
+ assert.deepEqual(pruned, { fresh: entry(now - 1) });
assert.deepEqual(prunePurgedSpaceEntries({}, now, ttl), {});
});
+test("purge guard: legacy plain-timestamp entries normalize to the deleted reason", async () => {
+ const { normalizePurgedSpaceEntries } = await load();
+ const shaped = { at: 123, reason: "revoked" };
+ assert.deepEqual(normalizePurgedSpaceEntries({ legacy: 456, shaped }), {
+ legacy: { at: 456, reason: "deleted" },
+ shaped,
+ });
+});
+
+// D14: a member removed then re-added must not stay locked out for the TTL.
+// Only a still-live "deleted" entry keeps guarding (the delete race the guard
+// was built for); a reappearing "revoked" space means re-added access.
+test("purge guard: live-set sweep keeps only still-live deleted entries", async () => {
+ const { keepPurgedSpaceEntry } = await load();
+ assert.equal(keepPurgedSpaceEntry({ at: 1, reason: "deleted" }, true), true);
+ assert.equal(keepPurgedSpaceEntry({ at: 1, reason: "revoked" }, true), false);
+ assert.equal(keepPurgedSpaceEntry({ at: 1, reason: "deleted" }, false), false);
+ assert.equal(keepPurgedSpaceEntry({ at: 1, reason: "revoked" }, false), false);
+});
+
// --- revokedNoteForkUpdate --------------------------------------------------
test("revoked fork: a push rejection moves, forks and clears the retraction", async () => {