Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 10 additions & 0 deletions changelogs/v2.5.18.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
## Fixes

- **The AI-change banner on notes is now opaque.** The "AI is editing this note…" / "N lines changed since you last viewed this note" banner pinned to the top of the note editor had a background of `color-mix(… var(--accent) 12%, transparent)` — ~88% see-through — so note content scrolled visibly behind it. The tint now sits on an opaque `var(--background)` base instead of `transparent`, masking the content underneath while keeping the exact same accent colour.

- **Chat threads now survive app restarts and updates.** Conversations were always written to SQLite, but on the desktop app they were only ever *read back* from Chromium localStorage — which an app update can clear or relocate, orphaning every thread and message in the database with no way to see them. Cairn now re-hydrates chat threads and messages from SQLite on launch (and when switching workspaces), so your conversations persist even if localStorage is wiped. The last-active thread is also remembered and re-selected on restart; if that pointer is lost, the app reuses your existing scoped thread instead of silently starting a blank one.

- **Clarifying questions no longer leak into the wrong chat.** When the AI asked you questions (the inline question form from `ask_questions`), switching to a different chat thread rendered that same form there too. The pending-question state lived in an unscoped hook `useState` and the `ChatPanel` never remounts on thread switch, so the form followed you around. Pending questions are now tagged with the thread they arrived on and only render while that thread is active — switch away and the form disappears; switch back and it returns.

- **Deleted notes and projects now go to the OS trash instead of being permanently erased.** When you delete a note or a project from the app (including via the in-app AI chat), Cairn now moves its `.md` file/folder to the system Trash (macOS) or Recycle Bin (Windows) via `shell.trashItem`, so you can restore it from Finder/Explorer if a delete was a mistake. If the OS trash is unavailable, it falls back to a permanent delete. Note: the standalone `cairn-mcp` binary (used by agents while Cairn is closed) still hard-deletes, since a headless process has no desktop trash.
- **Deleting a project no longer wipes another same-named project's notes.** Project note folders on disk are keyed by the project NAME slug (not the id), and project names aren't unique — so if two projects shared a name (e.g. a duplicate "Personal" created by a timed-out, retried request), deleting one ran `fs.rmSync` on the shared folder and destroyed the survivor's `.md` files while its database rows lived on. Project deletion (both the app's IPC handler and the MCP `delete_project` tool) now deletes the database rows first, then only removes the on-disk folder when no surviving project still occupies that slug. The same survivor guard was added to the post-merge source-folder cleanup, and the MCP delete path was reordered to delete the DB rows before touching disk (previously it removed the folder first).
12 changes: 9 additions & 3 deletions electron/ipc/db-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,11 @@ export function registerDbHandlers(ctx: DbContext): void {
// Delete from DB first so if it fails, the .md files are still intact for recovery.
q.deleteProject(ctx.db, id);
if (project) {
deleteProjectNotesDir(ctx.workspacePath, project.name);
// The notes folder is keyed by the project NAME slug, not the id, and
// names are not unique. Only remove the folder if no surviving project
// still shares that slug — otherwise we'd wipe a duplicate's .md files.
const survivorNames = q.getProjects(ctx.db).map((p) => p.name);
deleteProjectNotesDir(ctx.workspacePath, project.name, survivorNames);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}));

Expand Down Expand Up @@ -204,9 +208,11 @@ export function registerDbHandlers(ctx: DbContext): void {
}
}
// Remove the source project's on-disk folder (now that its notes have
// been rewritten under the target). Best-effort.
// been rewritten under the target). Best-effort, and only when no
// surviving project still shares the source name's slug.
try {
deleteProjectNotesDir(ctx.workspacePath, result.sourceName);
const survivorNames = q.getProjects(ctx.db).map((p) => p.name);
deleteProjectNotesDir(ctx.workspacePath, result.sourceName, survivorNames);
} catch (e) {
console.warn("[merge] failed to remove source project folder:", e instanceof Error ? e.message : e);
}
Expand Down
12 changes: 11 additions & 1 deletion electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { registerGitHandlers } from "./ipc/git";
import { registerPiAgentHandler } from "./ipc/pi-agent";
import { readWorkspaceConfig, getDbPathForWorkspace } from "./workspace-config";
import { startFileWatcher, suppressNextChange } from "./file-watcher";
import { syncNotesFromDisk, writeNoteFile, deleteNoteFile } from "./notes-files";
import { syncNotesFromDisk, writeNoteFile, deleteNoteFile, setPathRemover } from "./notes-files";
import { markMcpNotificationsRead, getNoteByIdIncludingTombstoned, findNestedConflictCopies } from "./db/queries";
import { getProjectName } from "./ipc/result-helpers";
import { setupProtocol, registerAssetProtocol, setAssetWorkspacePath } from "./lib/protocol";
Expand Down Expand Up @@ -221,6 +221,16 @@ app.whenReady().then(async () => {
const outDir = path.join(__dirname, "../out");
setupProtocol(outDir);

// Route deleted note files/folders to the OS trash (Finder/Explorer) so a
// user can restore them, instead of a permanent fs delete. shell.trashItem is
// async + main-process-only; we fire-and-forget (the DB row is already gone)
// and fall back to a hard delete if trashing fails (e.g. no desktop trash).
setPathRemover((targetPath) => {
shell.trashItem(targetPath).catch(() => {
try { fs.rmSync(targetPath, { recursive: true, force: true }); } catch { /* ignore */ }
});
});

const userDataPath = app.getPath("userData");

// ── Resolve workspace path ────────────────────────────────────────────
Expand Down
16 changes: 7 additions & 9 deletions electron/mcp/tools/projects.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import path from "path";
import fs from "fs";
import Database from "better-sqlite3";
import * as q from "../../db/queries";
import { newId } from "../../db/utils";
import { DEFAULT_COLUMNS } from "../../db/defaults";
import { Snapshot, insertNotification } from "../db";
import { toSlug } from "../../shared/text-utils";
import { renameProjectNotesDir } from "../../shared/notes-io";
import { renameProjectNotesDir, deleteProjectNotesDir } from "../../shared/notes-io";

export function upsert_project(db: Database.Database, snap: Snapshot, workspacePath: string, args: Record<string, any>) {
if (args.projectId) {
Expand Down Expand Up @@ -62,12 +59,13 @@ export function upsert_project(db: Database.Database, snap: Snapshot, workspaceP
export function delete_project(db: Database.Database, snap: Snapshot, workspacePath: string, args: Record<string, any>) {
const project = snap.projects.find((p) => p.id === args.projectId);
if (!project) return { error: "Project not found" };
// Delete notes dir
const notesDir = path.join(workspacePath, toSlug(project.name));
if (fs.existsSync(notesDir)) {
try { fs.rmSync(notesDir, { recursive: true, force: true }); } catch { /* ignore */ }
}
// Delete the DB rows first, then remove the notes folder — but only if no
// surviving project still shares this name's slug. The folder is keyed by
// the project NAME slug (not the id) and names are not unique, so blindly
// deleting it would destroy a same-named duplicate's .md files (data loss).
q.deleteProject(db, args.projectId as string);
const survivorNames = q.getProjects(db).map((p) => p.name);
deleteProjectNotesDir(workspacePath, project.name, survivorNames);
insertNotification(db, "delete_project", "Project deleted", `"${project.name}" was deleted`);
return { deleted: true, id: args.projectId, name: project.name };
}
4 changes: 3 additions & 1 deletion electron/notes-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
renameProjectNotesDir,
parseNoteFile,
pruneEmptyDirsUpTo,
setPathRemover,
CAIRN_FRONTMATTER_KEYS
} from "./shared/notes-io";

Expand All @@ -38,7 +39,8 @@ export {
deleteProjectNotesDir,
renameProjectNotesDir,
parseNoteFile,
pruneEmptyDirsUpTo
pruneEmptyDirsUpTo,
setPathRemover
};


Expand Down
116 changes: 115 additions & 1 deletion electron/shared/notes-io.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import fs from "fs";
import path from "path";
import os from "os";
import { writeNoteFile, type NoteFileData } from "./notes-io";
import { writeNoteFile, deleteProjectNotesDir, deleteNoteFile, setPathRemover, type NoteFileData, type PathRemover } from "./notes-io";

let tmpDir: string;

Expand Down Expand Up @@ -171,3 +171,117 @@ describe("writeNoteFile write strategy", () => {
}
});
});

/**
* Regression tests for the project-delete data-loss bug.
*
* Project note folders on disk are keyed by the project NAME slug, not the id,
* and project names are NOT unique. So two projects sharing a name (e.g. a
* duplicate "Personal" created by a timed-out+retried request) share one
* folder. Deleting one used to `fs.rmSync` the shared folder unconditionally,
* destroying the survivor's .md files. deleteProjectNotesDir must skip the
* delete when a surviving project still occupies the same slug.
*/
describe("deleteProjectNotesDir slug-collision guard", () => {
it("removes the folder when no other project shares the slug", () => {
const dir = path.join(tmpDir, "Personal");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "note.md"), "keep me");

deleteProjectNotesDir(tmpDir, "Personal", []);

expect(fs.existsSync(dir)).toBe(false);
});

it("does NOT remove the folder when a surviving project shares the slug", () => {
const dir = path.join(tmpDir, "Personal");
fs.mkdirSync(dir, { recursive: true });
const fp = path.join(dir, "note.md");
fs.writeFileSync(fp, "another project's data");

// A same-named duplicate still exists → the shared folder must be preserved.
deleteProjectNotesDir(tmpDir, "Personal", ["Personal"]);

expect(fs.existsSync(fp)).toBe(true);
expect(fs.readFileSync(fp, "utf-8")).toBe("another project's data");
});

it("guards on the slug, not the exact name (spacing variants collide)", () => {
// "My Project" (double space) and "My Project" both slugify to "My Project".
const dir = path.join(tmpDir, "My Project");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "note.md"), "data");

deleteProjectNotesDir(tmpDir, "My Project", ["My Project"]);

expect(fs.existsSync(dir)).toBe(true);
});

it("is a no-op when the folder does not exist", () => {
expect(() => deleteProjectNotesDir(tmpDir, "Nonexistent", [])).not.toThrow();
});
});

/**
* The Electron main process routes deletes to the OS trash via setPathRemover
* (shell.trashItem) so notes/projects are restorable. The MCP process (no
* Electron shell) keeps the default hard fs delete. These tests verify the
* injection point without depending on a real desktop trash.
*/
describe("setPathRemover — pluggable trash vs hard delete", () => {
afterEach(() => setPathRemover()); // always reset to the fs default

it("routes note-file deletes through the injected remover", () => {
writeNoteFile(tmpDir, BASE);
const fp = path.join(tmpDir, "My Project", "My Note.md");
expect(fs.existsSync(fp)).toBe(true);

const trashed: string[] = [];
const remover: PathRemover = (target) => { trashed.push(target); };
setPathRemover(remover);

deleteNoteFile(tmpDir, BASE.projectName!, BASE.id);

// The injected remover was called with the note's path; because our fake
// remover doesn't actually delete, the file is still on disk (proving the
// hard fs.unlinkSync no longer runs directly).
expect(trashed).toEqual([fp]);
expect(fs.existsSync(fp)).toBe(true);
});

it("routes project-folder deletes through the injected remover", () => {
const dir = path.join(tmpDir, "My Project");
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "note.md"), "data");

const trashed: string[] = [];
setPathRemover((target) => { trashed.push(target); });

deleteProjectNotesDir(tmpDir, "My Project", []);

expect(trashed).toEqual([dir]);
expect(fs.existsSync(dir)).toBe(true); // fake remover didn't delete
});

it("falls back to a hard delete when the remover throws", () => {
writeNoteFile(tmpDir, BASE);
const fp = path.join(tmpDir, "My Project", "My Note.md");

setPathRemover(() => { throw new Error("trash unavailable"); });

deleteNoteFile(tmpDir, BASE.projectName!, BASE.id);

// Fallback fs delete ran → file is gone despite the trasher failing.
expect(fs.existsSync(fp)).toBe(false);
});

it("hard-deletes by default (MCP process, no shell injected)", () => {
writeNoteFile(tmpDir, BASE);
const fp = path.join(tmpDir, "My Project", "My Note.md");

// No setPathRemover call → default hardRemove.
deleteNoteFile(tmpDir, BASE.projectName!, BASE.id);

expect(fs.existsSync(fp)).toBe(false);
});
});
61 changes: 57 additions & 4 deletions electron/shared/notes-io.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,50 @@ import fs from "fs";
import matter from "gray-matter";
import { toSlug } from "./text-utils";

// ── Pluggable path removal (OS trash vs hard delete) ──────────────────────
//
// User-initiated note/project deletes should go to the OS trash/recycle bin so
// they can be restored from Finder/Explorer. Electron exposes `shell.trashItem`
// for this, but it is a main-process-only, async API — and this module is also
// bundled into the standalone MCP process, which has no Electron `shell`.
//
// So we keep the sync fs removal as the default, and let the Electron main
// process inject a trasher via `setPathRemover`. Callers stay synchronous; an
// async trasher is fire-and-forget (the DB row is already deleted by the time
// we get here, so the file-watcher can't misread the removal as data loss).
export type PathRemover = (targetPath: string, opts: { recursive: boolean }) => void;

const hardRemove: PathRemover = (targetPath, opts) => {
if (opts.recursive) {
fs.rmSync(targetPath, { recursive: true, force: true });
} else {
fs.unlinkSync(targetPath);
}
};

let pathRemover: PathRemover = hardRemove;

/**
* Override how deleted note files/folders are removed from disk. The Electron
* main process injects an OS-trash implementation (shell.trashItem) so deletes
* are recoverable. Pass no argument to reset to a hard fs delete (used by the
* MCP process, which has no Electron shell).
*/
export function setPathRemover(remover?: PathRemover): void {
pathRemover = remover ?? hardRemove;
}

/** Remove a file or folder using the active remover; falls back to a hard
* delete if the remover throws (e.g. trashItem unavailable on a headless box). */
function removePath(targetPath: string, opts: { recursive: boolean }): void {
if (!fs.existsSync(targetPath)) return;
try {
pathRemover(targetPath, opts);
} catch {
try { hardRemove(targetPath, opts); } catch { /* ignore */ }
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

// ── Cairn-owned frontmatter keys ──────────────
// Only these keys are managed by Cairn. All other frontmatter fields
// (Obsidian tags, aliases, cssclass, date, publish, etc.) are preserved
Expand Down Expand Up @@ -395,7 +439,7 @@ export function deleteNoteFile(
): void {
const fp = findNoteFilePath(workspacePath, projectName, noteId);
if (fp) {
try { fs.unlinkSync(fp); } catch { /* ignore */ }
removePath(fp, { recursive: false });
// Deleting the last note in a subfolder empties it — prune the vacated
// folder(s), stopping at the project root.
pruneEmptyDirsUpTo(path.dirname(fp), projectNotesDir(workspacePath, projectName));
Expand All @@ -405,15 +449,24 @@ export function deleteNoteFile(
/**
* Delete the entire project notes folder (and all .md files inside it).
* Called when a project is deleted.
*
* IMPORTANT: the on-disk folder is keyed by the project NAME slug, not the
* project id, and project names are not unique. If another project still
* shares this slug, deleting the folder would destroy that surviving
* project's .md files (data loss). Pass `otherProjectNames` — the names of
* every project that still exists AFTER this one is removed from the DB — so
* we can skip the delete when a sibling still occupies the same folder.
*/
export function deleteProjectNotesDir(
workspacePath: string,
projectName: string,
otherProjectNames: string[] = [],
): void {
const slug = toSlug(projectName);
// Guard: never remove a folder that a surviving same-slug project depends on.
if (otherProjectNames.some((n) => toSlug(n) === slug)) return;
const dir = projectNotesDir(workspacePath, projectName);
if (fs.existsSync(dir)) {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
}
removePath(dir, { recursive: true });
}

/**
Expand Down
4 changes: 2 additions & 2 deletions src/components/notes/note-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -867,7 +867,7 @@ export function NoteEditor({ note, onBack }: NoteEditorProps) {
<div
className="absolute top-0 inset-x-0 z-10 flex items-center gap-2 px-4 py-1.5 text-xs"
style={{
background: "color-mix(in srgb, var(--accent) 12%, transparent)",
background: "color-mix(in srgb, var(--accent) 12%, var(--background))",
borderBottom: "1px solid color-mix(in srgb, var(--accent) 30%, transparent)",
color: "var(--accent)",
}}
Expand All @@ -885,7 +885,7 @@ export function NoteEditor({ note, onBack }: NoteEditorProps) {
<div
className="absolute top-0 inset-x-0 z-10 flex items-center gap-2 px-4 py-1.5 text-xs animate-fade-in"
style={{
background: "color-mix(in srgb, var(--accent) 12%, transparent)",
background: "color-mix(in srgb, var(--accent) 12%, var(--background))",
borderBottom: "1px solid color-mix(in srgb, var(--accent) 30%, transparent)",
color: "var(--accent)",
}}
Expand Down
Loading