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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions changelogs/v2.5.18.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
## 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).

- **Slash commands now send on Enter after tab-completing.** When you tab- or click-completed a slash command whose completion is itself a command (e.g. `/compact`), the input re-detected the leading `/` and immediately re-opened the command palette — so the next Enter re-opened the palette instead of sending. Completing a command now suppresses the trigger re-scan briefly and moves the cursor to the end, so the command is ready to send on the next Enter press.

- **Removed the redundant "Project context" panel from Settings → AI & Chat.** The MCP settings block contained a read-only "Project context" snippet generator (per-project system-prompt / Claude / Cursor config strings for wiring up external MCP clients) that duplicated the main MCP config blocks and confused its purpose. It wrote nothing and had no runtime effect, so it has been removed to simplify the page.

## Features

- **Custom slash commands.** You can now create your own slash commands from **Settings → Commands**. Each command has a name (used as `/name`), a description, the text it inserts into the input, and a scope that controls whether it appears in the AI chat panel, the coding-agent input, or both. Custom commands are workspace-global and persist in the local database. The new Commands settings page also documents every built-in command in one place — and a custom command with the same name as a built-in overrides it, so you can tweak what a built-in inserts.

- **Browse community slash commands.** From **Settings → Commands → Browse Community**, you can now install ready-made slash commands from the cairn-community registry with one click. The catalog is searchable and filterable by category, shows an "Update" action when an installed command has changed upstream, and installs commands workspace-globally so they're immediately usable by typing `/` in any chat or agent input. (The registry manifest gained a new `command` entry kind and a `commands[]` array in v2; older manifests still parse.)
70 changes: 70 additions & 0 deletions electron/db/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
toColumn,
toCard,
toTag,
toSlashCommand,
toChatThread,
toChatMessage,
toMcpNotification,
Expand Down Expand Up @@ -951,6 +952,75 @@ export function deleteTag(db: Database.Database, id: string) {
db.prepare("DELETE FROM tags WHERE id = ?").run(id);
}

// ── Slash commands ────────────────────────────

export function getSlashCommands(db: Database.Database, workspaceId?: string) {
const rows = workspaceId
? db.prepare("SELECT * FROM slash_commands WHERE workspace_id = ? ORDER BY name").all(workspaceId)
: db.prepare("SELECT * FROM slash_commands ORDER BY name").all();
return rows.map(toSlashCommand);
}

export function createSlashCommand(db: Database.Database, c: {
id: string;
workspaceId: string;
name: string;
description?: string;
insertText?: string;
scope?: string;
source?: string;
communityId?: string;
}) {
const now = ts();
db.prepare(`
INSERT INTO slash_commands
(id, workspace_id, name, description, insert_text, scope, source, community_id, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
c.id,
c.workspaceId,
c.name,
c.description ?? "",
c.insertText ?? "",
c.scope ?? "both",
c.source ?? "custom",
c.communityId ?? null,
now,
now
);
return toSlashCommand(db.prepare("SELECT * FROM slash_commands WHERE id = ?").get(c.id));
}

export function updateSlashCommand(db: Database.Database, id: string, patch: {
name?: string;
description?: string;
insertText?: string;
scope?: string;
}) {
const now = ts();
db.prepare(`
UPDATE slash_commands SET
name = COALESCE(?, name),
description = COALESCE(?, description),
insert_text = COALESCE(?, insert_text),
scope = COALESCE(?, scope),
updated_at = ?
WHERE id = ?
`).run(
patch.name ?? null,
patch.description ?? null,
patch.insertText ?? null,
patch.scope ?? null,
now,
id
);
return toSlashCommand(db.prepare("SELECT * FROM slash_commands WHERE id = ?").get(id));
}

export function deleteSlashCommand(db: Database.Database, id: string) {
db.prepare("DELETE FROM slash_commands WHERE id = ?").run(id);
}

// ── Chat ──────────────────────────────────────

export function getChatThreads(db: Database.Database, workspaceId: string) {
Expand Down
25 changes: 25 additions & 0 deletions electron/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,31 @@ const MIGRATIONS: Migration[] = [
db.exec("ALTER TABLE custom_services ADD COLUMN oauth_config TEXT");
}
},

// v31: User-defined & community slash commands. Workspace-global custom
// commands that surface in the chat / agent input palettes. Built-in commands
// stay as code constants; only custom + community-installed commands persist
// here. `scope` picks which pane(s) show the command; `source` records
// provenance ('custom' | 'community'); `community_id` links an installed
// command back to its cairn-community manifest entry. Device-local (not synced)
// — commands are a workspace-authoring convenience, not user data.
(db) => {
db.exec(`
CREATE TABLE IF NOT EXISTS slash_commands (
id TEXT PRIMARY KEY,
workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
insert_text TEXT NOT NULL DEFAULT '',
scope TEXT NOT NULL DEFAULT 'both', -- 'chat' | 'agent' | 'both'
source TEXT NOT NULL DEFAULT 'custom', -- 'custom' | 'community'
community_id TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_slash_commands_workspace ON slash_commands(workspace_id);
`);
},
];

export function applySchema(db: Database.Database): void {
Expand Down
31 changes: 26 additions & 5 deletions electron/ipc/db-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import path from "path";
import { registerIpcHandle, registerIpcOn } from "./registry";
import { handle, getProjectName, type DbContext } from "./result-helpers";
import * as q from "../db/queries";
import { writeNoteFile, deleteNoteFile, deleteProjectNotesDir, renameProjectNotesDir, reconcileProjectFolders, stripMarkdown, findNoteFilePath } from "../notes-files";
import { writeNoteFile, deleteNoteFile, hardDeleteNoteFile, deleteProjectNotesDir, renameProjectNotesDir, reconcileProjectFolders, stripMarkdown, findNoteFilePath } from "../notes-files";
import { suppressNextChange } from "../file-watcher";
import { executeTool as executeMcpTool } from "../mcp/tools";
import { executeReadTool } from "../lib/read-tools";
Expand Down Expand Up @@ -168,7 +168,14 @@ 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.
// Scope survivors to this project's workspace: folders live under this
// workspace's tree, so a same-named project in ANOTHER workspace is not a
// real survivor and must not block the delete.
const survivorNames = q.getProjects(ctx.db, project.workspaceId).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 +211,13 @@ 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 shares the source name's slug — scoped to the
// target's workspace (both folders live under this workspace's tree).
try {
deleteProjectNotesDir(ctx.workspacePath, result.sourceName);
const mergeWsId = q.getProjectById(ctx.db, targetId)?.workspaceId;
const survivorNames = q.getProjects(ctx.db, mergeWsId).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 Expand Up @@ -398,8 +409,12 @@ export function registerDbHandlers(ctx: DbContext): void {
// New file is in place; deleting the stale old copy is best-effort
// (a failure here only leaves a duplicate that the watcher would
// re-import into the old project — non-fatal, and the DB move stands).
// Use a synchronous HARD delete (not the OS-trash remover): this is a
// move-internal duplicate, not a user delete, so it must not land in
// the Trash and must be gone before we return, or an async trasher
// would race the file-watcher re-importing it into the old project.
try {
deleteNoteFile(ctx.workspacePath, oldProjectName, id);
hardDeleteNoteFile(ctx.workspacePath, oldProjectName, id);
} catch (e) {
console.warn("[notes] failed to remove old-project file after move:", e instanceof Error ? e.message : e);
}
Expand Down Expand Up @@ -636,4 +651,10 @@ export function registerDbHandlers(ctx: DbContext): void {
registerIpcHandle("db:tag:create", (_e, args: Parameters<typeof q.createTag>[1]) => handle(() => q.createTag(ctx.db, args)));
registerIpcHandle("db:tag:update", (_e, { id, patch }) => handle(() => q.updateTag(ctx.db, id, patch)));
registerIpcHandle("db:tag:delete", (_e, { id }) => handle(() => q.deleteTag(ctx.db, id)));

// ── Slash commands ─────────────────────────────────
registerIpcHandle("db:command:list", (_e, { workspaceId }) => handle(() => q.getSlashCommands(ctx.db, workspaceId)));
registerIpcHandle("db:command:create", (_e, args: Parameters<typeof q.createSlashCommand>[1]) => handle(() => q.createSlashCommand(ctx.db, args)));
registerIpcHandle("db:command:update", (_e, { id, patch }) => handle(() => q.updateSlashCommand(ctx.db, id, patch)));
registerIpcHandle("db:command:delete", (_e, { id }) => handle(() => q.deleteSlashCommand(ctx.db, id)));
}
47 changes: 47 additions & 0 deletions electron/lib/community-registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ const VALID = {
},
},
],
commands: [
{
id: "command-standup",
author: "cairn",
version: "1.0.0",
category: "Automation",
tags: ["standup"],
blurb: "Standup update.",
definition: {
name: "standup",
description: "Standup",
insertText: "Summarise recent activity.",
scope: "chat",
},
},
],
};

function fetchResponse(opts: {
Expand Down Expand Up @@ -91,6 +107,37 @@ describe("parseManifest", () => {
expect(m.services[0].definition.name).toBe("Weather");
});

it("parses community slash commands (manifest v2)", () => {
const m = parseManifest(VALID);
expect(m.commands).toHaveLength(1);
expect(m.commands[0].definition.name).toBe("standup");
expect(m.commands[0].definition.scope).toBe("chat");
});

it("tolerates a manifest with no commands key (pre-v2)", () => {
const { commands, ...noCommands } = VALID;
void commands;
const m = parseManifest(noCommands);
expect(m.commands).toEqual([]);
});

it("drops a command with an invalid name or scope", () => {
const bad = {
...VALID,
commands: [
{ id: "x", author: "a", version: "1.0.0", tags: [], blurb: "b",
definition: { name: "Bad Name", insertText: "hi", scope: "chat" } },
{ id: "y", author: "a", version: "1.0.0", tags: [], blurb: "b",
definition: { name: "ok", insertText: "hi", scope: "nope" } },
{ id: "z", author: "a", version: "1.0.0", tags: [], blurb: "b",
definition: { name: "good", insertText: "hi", scope: "both" } },
],
};
const m = parseManifest(bad);
expect(m.commands).toHaveLength(1);
expect(m.commands[0].definition.name).toBe("good");
});

it("drops an entry with a non-https baseUrl (never trusts an insecure URL)", () => {
const bad = structuredClone(VALID);
bad.mcpServers[0].definition.baseUrl = "http://insecure.example.com/mcp";
Expand Down
2 changes: 1 addition & 1 deletion electron/lib/community-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ export async function fetchManifest(opts?: { force?: boolean }): Promise<Registr
};
}
return {
manifest: { version: 1, updatedAt: "", mcpServers: [], services: [] },
manifest: { version: 1, updatedAt: "", mcpServers: [], services: [], commands: [] },
fromCache: false,
error: err instanceof Error ? err.message : String(err),
};
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
19 changes: 10 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,16 @@ 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);
// Scope survivors to this project's workspace — a same-named project in
// another workspace lives in a different folder tree and must not block this
// delete.
const survivorNames = q.getProjects(db, project.workspaceId).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 };
}
Loading