Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(ai): auto-apply note writes and follow the latest Agent reply

tianma-ifdd3237d79417
diff --git a/apps/api/src/companion-agent-tools.ts b/apps/api/src/companion-agent-tools.ts
index e32d4a9a..6b0b3cb4 100644
--- a/apps/api/src/companion-agent-tools.ts
+++ b/apps/api/src/companion-agent-tools.ts
@@ -6,6 +6,10 @@ import type { CompanionScope } from "./companion-service";
import { COMPANION_MCP_TOOLS, validateCompanionTool } from "./companion-tool-catalog";
import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companion-tool-actions";
import { executeWorkspaceTool } from "./mcp-tool-executor";
+import { getMemoDetail } from "./memo-service";
+import { AppError } from "./app-error";
+
+const AUTO_APPLY_WRITES = new Set(["create_memo", "update_memo", "trash_memos"]);
export function createCompanionTools(args: { db: DatabaseAdapter; scope: CompanionScope; input: CompanionTurnInput;
context?: AppContext; signal: AbortSignal; assertActive: () => Promise<void>; sources: CompanionSource[] }): ToolSet {
@@ -49,9 +53,10 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
};
return Object.fromEntries(catalog.map(definition => {
const readOnly = definition.annotations.readOnlyHint;
+ const autoApply = AUTO_APPLY_WRITES.has(definition.name);
return [definition.name, tool({
- description: `${definition.description}${toolHints[definition.name] ?? ""}${readOnly ? "" : " This only proposes changes; the user must confirm the card. Supply a short _reason."}`,
- inputSchema: jsonSchema<Record<string, unknown>>((readOnly ? definition.inputSchema : {
+ description: `${definition.description}${toolHints[definition.name] ?? ""}${readOnly || autoApply ? autoApply ? " This executes immediately. New notes are created in the named notebook. Trashed notes go to the recycle bin; edits keep revision history." : "" : " This only proposes changes; the user must confirm the card. Supply a short _reason."}`,
+ inputSchema: jsonSchema<Record<string, unknown>>((readOnly || autoApply ? definition.inputSchema : {
...definition.inputSchema, properties: { ...definition.inputSchema.properties, _reason: { type: "string", minLength: 1, maxLength: 400 } },
required: [...(definition.inputSchema.required ?? []), "_reason"],
}) as Parameters<typeof jsonSchema>[0]),
@@ -64,8 +69,14 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
const current = await companionWorkspaceCursor(args.db, args.scope.workspaceId);
cursor ??= current;
if (cursor !== current) return { error: "Notes changed during this request. Start a fresh request." };
- if (!readOnly && parameters_.dryRun !== true) return proposeCompanionToolAction(args.db, args.scope, args.input.id,
+ if (!readOnly && !autoApply && parameters_.dryRun !== true) return proposeCompanionToolAction(args.db, args.scope, args.input.id,
definition.name, parameters_, typeof _reason === "string" ? _reason : definition.title, cursor, inspected);
+ if (autoApply && parameters_.dryRun !== true && definition.name === "update_memo") {
+ const memo = await getMemoDetail(args.db, args.scope.workspaceId, String(parameters_.memoId));
+ if (!memo || inspected.get(memo.id) !== memo.revision) {
+ throw new AppError("companion_action_unread", "Read the complete source notes before changing their content.", 400);
+ }
+ }
if (definition.name === "get_memo" && inspected.has(String(parameters_.memoId))) {
// The original full result remains in this run's model messages. Only
// reuse it after authorization/context/cursor checks, never across runs.
@@ -78,6 +89,10 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani
parameters_.includeContent = false;
}
const result = await executeWorkspaceTool(args.context!, args.context!.get("auth"), definition.name, parameters_);
+ if (autoApply && parameters_.dryRun !== true) {
+ cursor = await companionWorkspaceCursor(args.db, args.scope.workspaceId);
+ return { applied: true, ...(typeof result === "object" && result ? result as object : { result }) };
+ }
if (current !== await companionWorkspaceCursor(args.db, args.scope.workspaceId)) return { error: "Notes changed during this read. Start a fresh request." };
if (definition.name === "get_memo") {
const memo = (result as { memo: MemoDetail }).memo;
diff --git a/apps/api/src/companion-runtime.ts b/apps/api/src/companion-runtime.ts
index e2f6a300..7403d343 100644
--- a/apps/api/src/companion-runtime.ts
+++ b/apps/api/src/companion-runtime.ts
@@ -13,10 +13,10 @@ Be warm, direct, honest, and concise. Connect ideas without inventing personal h
Respect the user's autonomy. Do not manipulate intimacy or claim consciousness or exclusivity.
Only claim to remember information present in supplied context. Distinguish explicit statements from guesses.
The user controls long-term memory through the UI. You cannot save, edit, or forget memories yourself.
-Only report a note operation as completed when a persisted receipt says applied. A proposal is not completion.
+Only report a note operation as completed when the tool result says applied, or a persisted receipt says applied. A proposal is not completion.
Never claim a reminder was scheduled or an external action completed.
You can use EdgeEver's shared tools to read, create, update, import, merge, move, tag, trash and restore notes, restore revisions, and organize notebooks.
-Every write tool only PROPOSES its exact arguments. Read tools and explicit dry runs execute immediately.
+create_memo, update_memo, and trash_memos execute immediately. Trashed notes go to the recycle bin; content edits keep revision history. Other write tools only PROPOSE their exact arguments. Read tools and explicit dry runs execute immediately.
Proposals do not change notes. Only the user can approve them in the suggestion card; chat text is not approval.
Read every source note first. Do not propose merging merely because notes share a broad topic: look for one coherent idea or user's explicit selection.
Merging preserves source bodies/attachments and existing tags, moves sources to trash and revokes their public shares. A destination notebook may be specified.
diff --git a/apps/api/src/companion-tool-actions.test.mjs b/apps/api/src/companion-tool-actions.test.mjs
index 682bf9dd..0b463a8a 100644
--- a/apps/api/src/companion-tool-actions.test.mjs
+++ b/apps/api/src/companion-tool-actions.test.mjs
@@ -135,6 +135,21 @@ describe("shared companion MCP adapter", () => {
expect(await tools.get_memo.execute({ memoId: f.notes[0].id })).toMatchObject({ content: "One original content" });
expect(f.sqlite.query("SELECT COUNT(*) AS n FROM companion_actions").get().n).toBe(0);
});
+ test("create_memo, update_memo and trash_memos execute immediately", async () => {
+ const f = await setup();
+ const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });
+ const created = await tools.create_memo.execute({ notebookId: "ideas", title: "New", contentMarkdown: "Exact new body" });
+ expect(created).toMatchObject({ applied: true });
+ const createdId = created.memo?.id ?? created.id;
+ expect(createdId).toBeTruthy();
+ expect(await getMemoDetail(f.db, scope.workspaceId, createdId)).toMatchObject({ title: "New", contentMarkdown: "Exact new body" });
+ await tools.get_memo.execute({ memoId: f.notes[0].id });
+ expect(await tools.update_memo.execute({ memoId: f.notes[0].id, title: "Changed", contentMarkdown: "Exact replacement" })).toMatchObject({ applied: true });
+ expect(await getMemoDetail(f.db, scope.workspaceId, f.notes[0].id)).toMatchObject({ title: "Changed", contentMarkdown: "Exact replacement" });
+ expect(await tools.trash_memos.execute({ memoIds: [f.notes[0].id] })).toMatchObject({ applied: true });
+ expect((await getMemoDetail(f.db, scope.workspaceId, f.notes[0].id, true)).isDeleted).toBe(true);
+ expect(f.sqlite.query("SELECT COUNT(*) AS n FROM companion_actions").get().n).toBe(0);
+ });
test("repeated complete reads return a reference without consuming the note budget again", async () => {
const f = await setup();
for (const note of f.notes) await updateMemoRecord(f.db, scope.workspaceId, note.id, { contentMarkdown: "x".repeat(6000) }, actor, "owner");
diff --git a/apps/web/src/components/CompanionChat.tsx b/apps/web/src/components/CompanionChat.tsx
index 8dadeb4a..c10d620a 100644
--- a/apps/web/src/components/CompanionChat.tsx
+++ b/apps/web/src/components/CompanionChat.tsx
@@ -1,6 +1,6 @@
-import { useEffect, useRef, useState, type FormEvent } from "react";
+import { useEffect, useLayoutEffect, useRef, useState, type FormEvent } from "react";
import { useTranslation } from "react-i18next";
-import { MessageCircle } from "lucide-react";
+import { Loader2, MessageCircle } from "lucide-react";
import type { CompanionAction, CompanionTurn, CompanionTurnInput } from "@edgeever/shared";
import { Button } from "@/components/ui/button";
import { api, ApiRequestError } from "@/lib/api";
@@ -44,6 +44,8 @@ export function CompanionChat({
const active = useRef<{ id: string; controller: AbortController } | null>(null);
const alive = useRef(true);
const locked = useRef(false);
+ const scroller = useRef<HTMLDivElement>(null);
+ const pinToBottom = useRef(true);
const explainError = (cause: unknown) => {
const code = cause instanceof ApiRequestError ? cause.code : "";
@@ -92,6 +94,7 @@ export function CompanionChat({
event.preventDefault();
const text = message.trim();
if (!text || locked.current) return;
+ pinToBottom.current = true;
void perform(async () => {
const id = crypto.randomUUID();
const controller = new AbortController();
@@ -141,6 +144,7 @@ export function CompanionChat({
setTurns(previous => previous.filter(item => item.id !== id));
setMessage(text);
}
+ await onNotesChanged().catch(() => {});
}
}
});
@@ -166,6 +170,12 @@ export function CompanionChat({
const threadTurns = turns.filter(turn => turn.threadId === threadId).reverse();
const previousThread = threads.find(thread => thread.threadId !== threadId);
+ useLayoutEffect(() => {
+ const node = scroller.current;
+ if (!node || !pinToBottom.current) return;
+ node.scrollTop = node.scrollHeight;
+ }, [turns, threadId, actions]);
+
if (!available) {
return <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 overflow-y-auto p-4 text-center">
<MessageCircle aria-hidden="true" className="h-9 w-9 text-emerald-600" />
@@ -176,17 +186,31 @@ export function CompanionChat({
return <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden">
{error ? <p role="alert" className="text-sm text-rose-700">{error}</p> : null}
{loading ? <p role="status">{t("common.loading")}</p> : null}
- <div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
+ <div
+ ref={scroller}
+ className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1"
+ onScroll={event => {
+ const node = event.currentTarget;
+ pinToBottom.current = node.scrollHeight - node.scrollTop - node.clientHeight < 48;
+ }}
+ >
{!loading && !threadTurns.length && previousThread ? <div className="flex items-center gap-2">
<p className="min-w-0 flex-1 truncate text-xs text-slate-500">{previousThread.message}</p>
- <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setThreadId(previousThread.threadId)}>
+ <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => { pinToBottom.current = true; setThreadId(previousThread.threadId); }}>
{t("aiAssistant.modes.resumeLast")}
</Button>
</div> : null}
{threadTurns.map(turn => <article key={turn.id} className="space-y-2 rounded-lg border p-3 text-sm">
<p className="whitespace-pre-wrap break-words font-medium">{turn.message}</p>
{turn.response ? <CompanionNoteText text={turn.response} sources={turn.sources} onOpenNote={onOpenNote} /> : null}
- {turn.status !== "completed" ? <p className="text-xs text-slate-500">{t(`companion.status.${turn.status}`)}</p> : null}
+ {turn.status === "running" ? (
+ <p role="status" className="flex items-center gap-2 text-xs text-slate-500">
+ <Loader2 className="h-4 w-4 animate-spin text-emerald-600" aria-hidden="true" />
+ <span className="sr-only">{t("companion.status.running")}</span>
+ </p>
+ ) : turn.status !== "completed" ? (
+ <p className="text-xs text-slate-500">{t(`companion.status.${turn.status}`)}</p>
+ ) : null}
{actions.filter(action => action.turnId === turn.id).map(action => <CompanionActionCard key={action.id} action={action}
busy={busy || Boolean(running)} onApply={applyAction} onDismiss={item => void perform(() => api.dismissCompanionAction(item.id))} onOpenNote={onOpenNote} />)}
</article>)}