Skip to content

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

feat(desktop): open a note in a new window (#730)

Dariusz Koryto2490a5ab181a
diff --git a/apps/desktop/src/main/desktop-menu.mjs b/apps/desktop/src/main/desktop-menu.mjs
index cffe500f..eed0e0fe 100644
--- a/apps/desktop/src/main/desktop-menu.mjs
+++ b/apps/desktop/src/main/desktop-menu.mjs
@@ -14,6 +14,7 @@ const menuCopy = {
minimize: "Minimize",
newMemo: "New Note",
newNotebook: "New Notebook",
+ openNoteWindow: "Open Note in New Window",
paste: "Paste",
pasteAsPlainText: "Paste as Plain Text",
quit: "Quit EdgeEver",
@@ -48,6 +49,7 @@ const menuCopy = {
minimize: "最小化",
newMemo: "新建笔记",
newNotebook: "新建笔记本",
+ openNoteWindow: "在新窗口打开笔记",
paste: "粘贴",
pasteAsPlainText: "粘贴为纯文本",
quit: "退出 EdgeEver",
@@ -82,6 +84,7 @@ const menuCopy = {
minimize: "Minimalizuj",
newMemo: "Nowa notatka",
newNotebook: "Nowy notatnik",
+ openNoteWindow: "Otwórz notatkę w nowym oknie",
paste: "Wklej",
pasteAsPlainText: "Wklej jako zwykły tekst",
quit: "Zakończ EdgeEver",
diff --git a/apps/desktop/src/main/index.mjs b/apps/desktop/src/main/index.mjs
index 4f4a41e4..bea021af 100644
--- a/apps/desktop/src/main/index.mjs
+++ b/apps/desktop/src/main/index.mjs
@@ -66,6 +66,7 @@ import { createAiDirectRuntime } from "./ai-direct.mjs";
import { createAcpPathStore, validateTrustedAcpPath } from "./acp-path-store.mjs";
import { createAcpHostRuntime, registerAcpIpc } from "./acp-host.mjs";
import { shouldQuitAfterAllWindowsClosed } from "./window-lifecycle.mjs";
+import { createNoteWindowController, isValidNoteWindowMemoId, noteWindowUrl } from "./note-windows.mjs";
import {
commandLineOpensContent,
createLoginItemController,
@@ -89,6 +90,7 @@ import {
const { autoUpdater } = electronUpdater;
const headingShortcutGuard = createHeadingShortcutGuard();
+const noteWindowHeadingShortcutGuards = new WeakMap();
const linuxUpdateTestMode = process.platform === "linux"
&& process.env.GITHUB_ACTIONS === "true"
@@ -949,6 +951,13 @@ const buildApplicationMenu = () => {
{ label: copy.newMemo, accelerator: "CmdOrCtrl+N", click: () => sendDesktopCommand("new-memo") },
{ label: copy.newNotebook, accelerator: "CmdOrCtrl+Shift+N", click: () => sendDesktopCommand("new-notebook") },
{ type: "separator" },
+ {
+ label: copy.openNoteWindow,
+ accelerator: "CmdOrCtrl+Shift+O",
+ // A note window already shows its note on its own.
+ click: () => { if (!noteWindows.isNoteWindowContents(BrowserWindow.getFocusedWindow()?.webContents)) sendDesktopCommand("open-memo-window"); },
+ },
+ { type: "separator" },
{ label: copy.close, role: "close" },
],
},
@@ -1723,6 +1732,75 @@ const createWindow = async ({ show = true } = {}) => {
buildApplicationMenu();
};
+const createNoteWindow = (memoId) => {
+ const bounds = mainWindow && !mainWindow.isDestroyed() ? mainWindow.getBounds() : null;
+ const offset = 32 * (noteWindows.list().length + 1);
+ const window = new BrowserWindow({
+ width: 860,
+ height: 760,
+ ...(bounds ? { x: bounds.x + offset, y: bounds.y + offset } : {}),
+ minWidth: 480,
+ minHeight: 400,
+ show: false,
+ webPreferences: {
+ preload: join(currentDirectory, "../preload/index.cjs"),
+ contextIsolation: true,
+ nodeIntegration: false,
+ sandbox: true,
+ },
+ });
+ window.once("ready-to-show", () => showWindow(window));
+ attachEditContextMenu(window.webContents);
+ const windowHeadingShortcutGuard = createHeadingShortcutGuard();
+ windowHeadingShortcutGuard.attach(window.webContents);
+ noteWindowHeadingShortcutGuards.set(window.webContents, windowHeadingShortcutGuard);
+ const rendererEntryUrl = desktopRendererEntryUrl();
+ window.webContents.on("will-navigate", (event, url) => {
+ if (!isAllowedAppNavigation(url, rendererEntryUrl)) event.preventDefault();
+ else if (isResourceDownloadUrl(url)) window.webContents.downloadURL(url);
+ });
+ window.webContents.on("will-redirect", (event, url) => {
+ if (!isAllowedAppNavigation(url, rendererEntryUrl)) event.preventDefault();
+ });
+ window.webContents.setWindowOpenHandler(({ url }) => {
+ if (url.startsWith("https://") || url.startsWith("http://")) void shell.openExternal(url);
+ return { action: "deny" };
+ });
+ // A window that cannot show its note is closed so the note returns to the
+ // main window; ERR_ABORTED (-3) only means a navigation was superseded.
+ window.webContents.on("did-fail-load", (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
+ void writeDiagnostic("note-window.load-failed", { errorCode, errorDescription, validatedURL, isMainFrame });
+ if (isMainFrame && errorCode !== -3) noteWindows.fail(window.webContents, "load-failed");
+ });
+ window.webContents.on("render-process-gone", (_event, details) => {
+ void writeDiagnostic("note-window.renderer-gone", details);
+ if (details?.reason !== "clean-exit") noteWindows.fail(window.webContents, "renderer-gone");
+ });
+ void window.loadURL(noteWindowUrl(rendererEntryUrl, memoId)).catch((error) => {
+ void writeDiagnostic("note-window.navigation-rejected", { message: String(error?.message || error).slice(0, 2000) });
+ if (!window.isDestroyed()) noteWindows.fail(window.webContents, "load-failed");
+ });
+ return window;
+};
+
+const noteWindows = createNoteWindowController({
+ createWindow: createNoteWindow,
+ showWindow,
+ onChange: (memoIds) => {
+ if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send("desktop:note-windows-changed", memoIds);
+ },
+ onFailed: (memoId, reason, { handedOff }) => {
+ void writeDiagnostic("note-window.failed", { reason, handedOff });
+ if (handedOff) sendDesktopCommand(`note-window-failed:${memoId}`);
+ },
+});
+
+// Note windows run the same app code as the main window and may use its
+// renderer features; account, instance and global settings stay main-only.
+const isAppRendererSender = (event) => (
+ event.sender === mainWindow?.webContents || noteWindows.isNoteWindowContents(event.sender)
+) && event.senderFrame === event.sender.mainFrame;
+
const confirmMacInstallation = async () => {
if (!app.isPackaged || process.platform !== "darwin" || existsSync(installationMarkerPath())) return;
@@ -1915,6 +1993,8 @@ const startApplication = async () => {
await refreshBackupContext(); void backupManager.tick();
return { ready: true, scope: nextScopeKey };
}
+ // Let open note windows save into the current account before it changes.
+ await noteWindows.closeAll();
if (backupManager.context?.baseUrl !== configuredApiBaseUrl || backupManager.context?.accountId !== normalizedAccountId) await backupManager.setContext(null);
await stopSidecar();
const nextSidecar = await startSidecar(normalizedAccountId);
@@ -1924,8 +2004,12 @@ const startApplication = async () => {
return { ready: true, scope: nextScopeKey };
});
ipcMain.on("desktop:rich-text-heading-shortcut", (event, active) => {
- if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) return;
- headingShortcutGuard.setActive(active);
+ // sendSync blocks the renderer until a value is returned, so always answer.
+ if (!isAppRendererSender(event)) {
+ event.returnValue = false;
+ return;
+ }
+ (noteWindowHeadingShortcutGuards.get(event.sender) ?? headingShortcutGuard).setActive(active);
event.returnValue = true;
});
ipcMain.on("desktop:renderer-ready", (event) => {
@@ -1943,7 +2027,7 @@ const startApplication = async () => {
});
ipcMain.on("desktop:api-base-url-sync", (event) => { event.returnValue = configuredApiBaseUrl; });
ipcMain.on("desktop:session-token-sync", (event) => {
- event.returnValue = event.sender === mainWindow?.webContents && event.senderFrame === event.sender.mainFrame
+ event.returnValue = isAppRendererSender(event)
? credentialForUrl(desktopSessionToken, desktopSessionTokenOrigin, configuredApiBaseUrl) : "";
});
ipcMain.on("desktop:recovered-after-abnormal-exit-sync", (event) => { event.returnValue = recoveredAfterAbnormalExit; });
@@ -1967,13 +2051,14 @@ const startApplication = async () => {
});
ipcMain.handle("desktop:clear-session-token", async (event) => {
if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame || instanceChangePending) throw new Error("Session update forbidden");
+ await noteWindows.closeAll();
scheduledTaskScheduler.clear();
await backupManager.setContext(null);
await saveDesktopSessionToken("");
return { stored: false };
});
ipcMain.handle("desktop:picgo-test", (event, input) => {
- if (event.sender !== mainWindow?.webContents) throw new Error("PicGo requests must come from the main window");
+ if (!isAppRendererSender(event)) throw new Error("PicGo requests must come from the main window");
const target = input && typeof input === "object" ? input : { endpoint: input, serverKey: "" };
return testPicGoConnection(target.endpoint, { serverKey: target.serverKey });
});
@@ -1991,8 +2076,9 @@ const startApplication = async () => {
},
});
ipcMain.handle("desktop:picgo-upload", (event, input) => {
- if (event.sender !== mainWindow?.webContents) throw new Error("PicGo requests must come from the main window");
- return queuePicGoUpload(input, () => event.sender === mainWindow?.webContents && !event.sender.isDestroyed());
+ if (!isAppRendererSender(event)) throw new Error("PicGo requests must come from the main window");
+ const sender = event.sender;
+ return queuePicGoUpload(input, () => !sender.isDestroyed() && (sender === mainWindow?.webContents || noteWindows.isNoteWindowContents(sender)));
});
ipcMain.handle("desktop:public-network-fetch", async (event, requestId, input) => {
if (event.sender !== mainWindow?.webContents) throw new Error("Public network requests must come from the main window");
@@ -2002,7 +2088,7 @@ const startApplication = async () => {
if (event.sender === mainWindow?.webContents && typeof requestId === "string") pluginPublicNetwork.cancel(requestId);
});
ipcMain.handle("desktop:ai-direct-open", async (event, requestId, input) => {
- if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) throw new Error("AI provider requests must come from the main window");
+ if (!isAppRendererSender(event)) throw new Error("AI provider requests must come from the main window");
const sender = event.sender;
return aiDirect.open(requestId, input, {
onData: (bytes) => {
@@ -2023,7 +2109,7 @@ const startApplication = async () => {
});
});
ipcMain.on("desktop:ai-direct-cancel", (event, requestId) => {
- if (event.sender === mainWindow?.webContents && event.senderFrame === event.sender.mainFrame && typeof requestId === "string") aiDirect.cancel(requestId);
+ if (isAppRendererSender(event) && typeof requestId === "string") aiDirect.cancel(requestId);
});
const acpRuntime = registerAcpIpc(ipcMain, createAcpHostRuntime({
executablePath: backgroundNodeExecutable(process.execPath),
@@ -2074,10 +2160,54 @@ const startApplication = async () => {
return { scheduled: scheduledTaskScheduler.entries.size };
});
ipcMain.handle("desktop:record-renderer-error", async (event, details) => {
- if (event.sender !== mainWindow?.webContents) throw new Error("Renderer diagnostics must come from the main window");
+ if (!isAppRendererSender(event)) throw new Error("Renderer diagnostics must come from the main window");
await writeDiagnostic("renderer.react-error", normalizeDesktopDiagnostic(details));
return { recorded: true };
});
+ ipcMain.handle("desktop:note-windows", (event) => (
+ event.sender === mainWindow?.webContents ? noteWindows.list() : []
+ ));
+ ipcMain.handle("desktop:open-note-window", async (event, memoId) => {
+ if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) throw new Error("Note windows must be opened from the main window");
+ if (!isValidNoteWindowMemoId(memoId)) throw new Error("Invalid note id");
+ const result = noteWindows.open(memoId);
+ // The handoff succeeds only once the new window shows the note.
+ if (!await noteWindows.waitUntilReady(memoId)) {
+ // The renderer tells "this note cannot be shown" apart from other failures.
+ throw new Error(`note-window-failed:${noteWindows.failureReason(memoId) ?? "closed"}`);
+ }
+ return result;
+ });
+ ipcMain.handle("desktop:focus-note-window", (event, memoId) => (
+ event.sender === mainWindow?.webContents && isValidNoteWindowMemoId(memoId) ? noteWindows.focus(memoId) : false
+ ));
+ ipcMain.on("desktop:note-window-ready", (event) => {
+ if (isAppRendererSender(event)) noteWindows.markReady(event.sender);
+ });
+ ipcMain.on("desktop:note-window-load-failed", (event) => {
+ if (isAppRendererSender(event)) noteWindows.fail(event.sender, "note-unavailable");
+ });
+ // The main window owns sync; it forwards results for a note to that note's window.
+ ipcMain.on("desktop:note-window-sync", (event, memoId, update) => {
+ if (event.sender !== mainWindow?.webContents || event.senderFrame !== event.sender.mainFrame) return;
+ if (isValidNoteWindowMemoId(memoId) && update && typeof update === "object") noteWindows.sendTo(memoId, "desktop:note-window-sync", update);
+ });
+ ipcMain.on("desktop:note-window-listening", (event) => {
+ if (isAppRendererSender(event)) noteWindows.markListening(event.sender);
+ });
+ ipcMain.on("desktop:note-window-close-result", (event, allowed) => {
+ if (isAppRendererSender(event)) noteWindows.resolveClose(event.sender, allowed === true);
+ });
+ ipcMain.on("desktop:note-window-saved", (event) => {
+ const memoId = isAppRendererSender(event) ? noteWindows.memoIdForContents(event.sender) : null;
+ if (memoId) sendDesktopCommand(`note-window-saved:${memoId}`);
+ });
+ ipcMain.handle("desktop:open-memo-in-main-window", (event, memoId) => {
+ if (!isAppRendererSender(event) || !noteWindows.isNoteWindowContents(event.sender) || !isValidNoteWindowMemoId(memoId)) return false;
+ showWindow(mainWindow);
+ sendDesktopCommand(`open-memo:${memoId}`);
+ return true;
+ });
ipcMain.handle("desktop:open-renderer-issue", async (event, details) => {
if (event.sender !== mainWindow?.webContents) throw new Error("Renderer issue reports must come from the main window");
await openDesktopDiagnosticIssue(details);
@@ -2088,6 +2218,7 @@ const startApplication = async () => {
if (process.platform !== "darwin" || !app.isPackaged) throw new Error("Local data reset is only available in the packaged macOS app");
if (requestedUserDataDirectory) throw new Error("Local data reset is unavailable with a custom user-data directory");
if (localDataResetScheduled) return { scheduled: true };
+ await noteWindows.closeAll();
try {
await scheduleMacLocalDataReset({
@@ -2171,9 +2302,12 @@ const startApplication = async () => {
buttons: chinese ? ["取消", "切换实例"] : ["Cancel", "Switch instance"], defaultId: 0, cancelId: 0,
});
if (answer.response !== 1) throw new Error("Instance change cancelled");
+ await noteWindows.closeAll();
await backupManager.setContext(null);
await saveDesktopSessionToken("");
}
+ // Note windows save into the current instance before it changes.
+ await noteWindows.closeAll();
scheduledTaskScheduler.clear();
await backupManager.setContext(null);
const temporaryInstancePath = `${instanceUrlPath()}.tmp`;
@@ -2458,6 +2592,7 @@ app.on("before-quit", (event) => {
tray?.destroy();
if (backupCheckTimer) clearInterval(backupCheckTimer);
void (async () => {
+ await noteWindows.closeAll();
await backupManager?.close();
await releaseDesktopAcpSessions().catch(() => {});
await stopSidecar();
diff --git a/apps/desktop/src/main/note-windows.mjs b/apps/desktop/src/main/note-windows.mjs
new file mode 100644
index 00000000..3f95c214
--- /dev/null
+++ b/apps/desktop/src/main/note-windows.mjs
@@ -0,0 +1,224 @@
+export const NOTE_WINDOW_QUERY_PARAM = "noteWindow";
+export const NOTE_WINDOW_CLOSE_REQUEST_CHANNEL = "desktop:note-window-close-request";
+
+const MEMO_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
+
+export const isValidNoteWindowMemoId = (value) => typeof value === "string" && MEMO_ID_PATTERN.test(value);
+
+export const noteWindowUrl = (entryUrl, memoId) => {
+ const url = new URL(entryUrl);
+ url.searchParams.set(NOTE_WINDOW_QUERY_PARAM, memoId);
+ return url.href;
+};
+
+/**
+ * Tracks the separate note windows. A note is shown in at most one of them,
+ * and a window closes only after its renderer confirms that pending edits were
+ * saved, so closing never silently drops typing. A new window counts as open
+ * only once its renderer reports that the note is shown; a window that fails
+ * to load or crashes is closed so the note returns to the main window.
+ */
+export const createNoteWindowController = ({
+ createWindow,
+ showWindow,
+ onChange = () => {},
+ onFailed = () => {},
+ forcedCloseTimeoutMs = 5_000,
+ readyTimeoutMs = 30_000,
+ now = () => Date.now(),
+ setTimer = setTimeout,
+ clearTimer = clearTimeout,
+}) => {
+ const entries = new Map();
+ const failureReasons = new Map();
+
+ const list = () => [...entries.keys()];
+ const live = (entry) => entry && !entry.window.isDestroyed();
+ const entryForContents = (contents) => {
+ for (const entry of entries.values()) {
+ if (live(entry) && entry.window.webContents === contents) return entry;
+ }
+ return null;
+ };
+
+ const settleClose = (entry, closed) => {
+ const request = entry.closeRequest;
+ if (!request) return;
+ entry.closeRequest = null;
+ if (request.timer) clearTimer(request.timer);
+ for (const resolve of request.waiters) resolve(closed);
+ };
+
+ const allowClose = (entry) => {
+ entry.closeAllowed = true;
+ if (live(entry)) entry.window.close();
+ };
+
+ const settleReady = (entry, ready) => {
+ if (entry.readyTimer) clearTimer(entry.readyTimer);
+ entry.readyTimer = null;
+ for (const resolve of entry.readyWaiters.splice(0)) resolve(ready);
+ };
+
+ const failEntry = (entry, reason) => {
+ // A window already being closed on purpose (by the user, on quit) aborts
+ // its own load; that is not a failure to report.
+ if (!live(entry) || entry.failed || entry.closeAllowed) return;
+ entry.failed = true;
+ failureReasons.set(entry.memoId, reason);
+ const handedOff = entry.ready;
+ settleReady(entry, false);
+ entry.closeAllowed = true;
+ // Destroy rather than close: a hung renderer may never finish closing,
+ // and the note must not stay owned by a dead window.
+ entry.window.destroy();
+ // Before the handoff completed, the caller waiting for readiness tells
+ // the user; afterwards nobody is waiting, so the main window must.
+ onFailed(entry.memoId, reason, { handedOff });
+ };
+
+ const requestClose = (entry, { forced = false } = {}) => {
+ if (!live(entry)) return Promise.resolve(true);
+ // A crashed renderer, or one that has not shown the note yet, cannot
+ // answer and has nothing unsaved beyond the local draft store.
+ if (!entry.listening || entry.window.webContents.isCrashed?.()) {
+ allowClose(entry);
+ return Promise.resolve(true);
+ }
+ if (entry.closeRequest) {
+ // Closing again after an unanswered request means the renderer is stuck.
+ if (!forced && now() - entry.closeRequest.startedAt >= forcedCloseTimeoutMs) {
+ allowClose(entry);
+ return Promise.resolve(true);
+ }
+ if (forced && !entry.closeRequest.timer) {
+ entry.closeRequest.timer = setTimer(() => allowClose(entry), forcedCloseTimeoutMs);
+ }
+ return new Promise((resolve) => entry.closeRequest.waiters.push(resolve));
+ }
+ return new Promise((resolve) => {
+ entry.closeRequest = {
+ startedAt: now(),
+ waiters: [resolve],
+ timer: forced ? setTimer(() => allowClose(entry), forcedCloseTimeoutMs) : null,
+ };
+ entry.window.webContents.send(NOTE_WINDOW_CLOSE_REQUEST_CHANNEL);
+ });
+ };
+
+ const open = (memoId) => {
+ if (!isValidNoteWindowMemoId(memoId)) throw new Error("Invalid note id");
+ const existing = entries.get(memoId);
+ // A failed window that is still going away is replaced, not reused.
+ if (live(existing) && !existing.failed) {
+ showWindow(existing.window);
+ return { opened: false };
+ }
+ failureReasons.delete(memoId);
+ const window = createWindow(memoId);
+ const entry = {
+ memoId, window, closeAllowed: false, closeRequest: null, listening: false,
+ ready: false, readyWaiters: [], readyTimer: null, failed: false,
+ };
+ entries.set(memoId, entry);
+ window.on("close", (event) => {
+ if (entry.closeAllowed) return;
+ event.preventDefault();
+ void requestClose(entry);
+ });
+ window.on("closed", () => {
+ settleClose(entry, true);
+ settleReady(entry, false);
+ if (entries.get(memoId) !== entry) return;
+ entries.delete(memoId);
+ onChange(list());
+ });
+ onChange(list());
+ return { opened: true };
+ };
+
+ const focus = (memoId) => {
+ const entry = entries.get(memoId);
+ if (!live(entry)) return false;
+ showWindow(entry.window);
+ return true;
+ };
+
+ /** Why the window for this note failed, if it did. */
+ const failureReason = (memoId) => failureReasons.get(memoId) ?? null;
+
+ /** Resolves true once the window shows its note, false if it closes or fails first. */
+ const waitUntilReady = (memoId) => {
+ const entry = entries.get(memoId);
+ if (!live(entry)) return Promise.resolve(false);
+ if (entry.ready) return Promise.resolve(true);
+ return new Promise((resolve) => {
+ entry.readyWaiters.push(resolve);
+ entry.readyTimer ??= setTimer(() => failEntry(entry, "timeout"), readyTimeoutMs);
+ });
+ };
+
+ /** The renderer shows its note and owns it from now on. */
+ const markReady = (contents) => {
+ const entry = entryForContents(contents);
+ if (!entry || entry.failed) return false;
+ entry.ready = true;
+ settleReady(entry, true);
+ return true;
+ };
+
+ /** The window could not load or show its note, or its renderer is gone. */
+ const fail = (contents, reason) => {
+ const entry = entryForContents(contents);
+ if (entry) failEntry(entry, reason);
+ return Boolean(entry);
+ };
+
+ /** Deliver a main-window update to the window showing this note. */
+ const sendTo = (memoId, channel, payload) => {
+ const entry = entries.get(memoId);
+ if (!live(entry) || entry.failed) return false;
+ entry.window.webContents.send(channel, payload);
+ return true;
+ };
+
+ /** The renderer is ready to answer close requests. */
+ const markListening = (contents) => {
+ const entry = entryForContents(contents);
+ if (entry) entry.listening = true;
+ return Boolean(entry);
+ };
+
+ /** The renderer answers a close request after trying to save. */
+ const resolveClose = (contents, allowed) => {
+ const entry = entryForContents(contents);
+ if (!entry?.closeRequest) return false;
+ if (allowed === true) {
+ allowClose(entry);
+ return true;
+ }
+ if (entry.closeRequest.timer) return false;
+ settleClose(entry, false);
+ return true;
+ };
+
+ /** Close every note window, waiting for saves up to the forced timeout. */
+ const closeAll = () => Promise.all([...entries.values()].map((entry) => requestClose(entry, { forced: true })));
+
+ return {
+ closeAll,
+ fail,
+ failureReason,
+ focus,
+ has: (memoId) => live(entries.get(memoId)),
+ isNoteWindowContents: (contents) => Boolean(entryForContents(contents)),
+ list,
+ markListening,
+ markReady,
+ memoIdForContents: (contents) => entryForContents(contents)?.memoId ?? null,
+ open,
+ resolveClose,
+ sendTo,
+ waitUntilReady,
+ };
+};
diff --git a/apps/desktop/src/main/note-windows.test.mjs b/apps/desktop/src/main/note-windows.test.mjs
new file mode 100644
index 00000000..f9cc33d7
--- /dev/null
+++ b/apps/desktop/src/main/note-windows.test.mjs
@@ -0,0 +1,269 @@
+import { describe, expect, test } from "bun:test";
+import { EventEmitter } from "node:events";
+import {
+ NOTE_WINDOW_CLOSE_REQUEST_CHANNEL,
+ createNoteWindowController,
+ isValidNoteWindowMemoId,
+ noteWindowUrl,
+} from "./note-windows.mjs";
+
+class FakeWindow extends EventEmitter {
+ constructor(memoId) {
+ super();
+ this.memoId = memoId;
+ this.destroyed = false;
+ this.crashed = false;
+ this.sent = [];
+ this.webContents = {
+ send: (channel) => this.sent.push(channel),
+ isCrashed: () => this.crashed,
+ };
+ }
+ isDestroyed() { return this.destroyed; }
+ // Mirrors BrowserWindow.destroy(): no "close" event, only "closed".
+ destroy() {
+ if (this.destroyed) return;
+ this.destroyed = true;
+ this.emit("closed");
+ }
+ // Mirrors BrowserWindow.close(): "close" can be prevented, then "closed" fires.
+ close() {
+ if (this.destroyed) return;
+ let prevented = false;
+ this.emit("close", { preventDefault: () => { prevented = true; } });
+ if (prevented) return;
+ this.destroyed = true;
+ this.emit("closed");
+ }
+}
+
+const setup = ({ listening = true, ...options } = {}) => {
+ const windows = [];
+ const shown = [];
+ const changes = [];
+ const timers = [];
+ const failures = [];
+ let clock = 0;
+ const controller = createNoteWindowController({
+ createWindow: (memoId) => { const window = new FakeWindow(memoId); windows.push(window); return window; },
+ showWindow: (window) => shown.push(window.memoId),
+ onChange: (ids) => changes.push(ids),
+ onFailed: (memoId, reason, { handedOff }) => failures.push([memoId, reason, handedOff]),
+ now: () => clock,
+ setTimer: (callback, delay) => { const timer = { callback, delay, cleared: false }; timers.push(timer); return timer; },
+ clearTimer: (timer) => { timer.cleared = true; },
+ ...options,
+ });
+ // Windows in these tests have loaded and listen for close requests.
+ const open = controller.open;
+ if (listening) controller.open = (memoId) => {
+ const result = open(memoId);
+ const window = windows.find((candidate) => candidate.memoId === memoId && !candidate.isDestroyed());
+ if (window) controller.markListening(window.webContents);
+ return result;
+ };
+ return {
+ controller, windows, shown, changes, timers, failures,
+ advance: (ms) => { clock += ms; },
+ fireTimers: () => { for (const timer of timers.splice(0)) if (!timer.cleared) timer.callback(); },
+ };
+};
+
+describe("note window registry", () => {
+ test("validates note ids and builds the window URL on the app entry", () => {
+ expect(isValidNoteWindowMemoId("memo_01HZ-abc")).toBe(true);
+ for (const value of ["", "../x", "a b", "a/b", "x".repeat(129), null, 42]) expect(isValidNoteWindowMemoId(value)).toBe(false);
+ expect(noteWindowUrl("edgeever-app://app/index.html", "memo_1")).toBe("edgeever-app://app/index.html?noteWindow=memo_1");
+ expect(noteWindowUrl("http://127.0.0.1:5173", "memo_1")).toBe("http://127.0.0.1:5173/?noteWindow=memo_1");
+ });
+
+ test("opens one window per note; opening again focuses it instead of creating another", () => {
+ const { controller, windows, shown, changes } = setup();
+ expect(controller.open("memo_a")).toEqual({ opened: true });
+ expect(controller.open("memo_a")).toEqual({ opened: false });
+ expect(controller.open("memo_a")).toEqual({ opened: false });
+ expect(windows).toHaveLength(1);
+ expect(shown).toEqual(["memo_a", "memo_a"]);
+ expect(controller.open("memo_b")).toEqual({ opened: true });
+ expect(controller.list()).toEqual(["memo_a", "memo_b"]);
+ expect(changes.at(-1)).toEqual(["memo_a", "memo_b"]);
+ expect(controller.focus("memo_b")).toBe(true);
+ expect(controller.focus("memo_c")).toBe(false);
+ expect(() => controller.open("../etc")).toThrow("Invalid note id");
+ });
+
+ test("closing asks the renderer first and closes only after it confirms", () => {
+ const { controller, windows, changes } = setup();
+ controller.open("memo_a");
+ const [window] = windows;
+ window.close();
+ expect(window.isDestroyed()).toBe(false);
+ expect(window.sent).toEqual([NOTE_WINDOW_CLOSE_REQUEST_CHANNEL]);
+ // A second close while the renderer is still saving does not send twice.
+ window.close();
+ expect(window.sent).toHaveLength(1);
+ expect(controller.resolveClose(window.webContents, true)).toBe(true);
+ expect(window.isDestroyed()).toBe(true);
+ expect(controller.list()).toEqual([]);
+ expect(changes.at(-1)).toEqual([]);
+ // The note can be opened again once its window is gone.
+ expect(controller.open("memo_a")).toEqual({ opened: true });
+ });
+
+ test("a failed save keeps the window open and a later close asks again", () => {
+ const { controller, windows } = setup();
+ controller.open("memo_a");
+ const [window] = windows;
+ window.close();
+ expect(controller.resolveClose(window.webContents, false)).toBe(true);
+ expect(window.isDestroyed()).toBe(false);
+ expect(controller.has("memo_a")).toBe(true);
+ window.close();
+ expect(window.sent).toEqual([NOTE_WINDOW_CLOSE_REQUEST_CHANNEL, NOTE_WINDOW_CLOSE_REQUEST_CHANNEL]);
+ });
+
+ test("closing again after an unanswered request lets a stuck renderer go", () => {
+ const { controller, windows, advance } = setup();
+ controller.open("memo_a");
+ const [window] = windows;
+ window.close();
+ advance(1_000);
+ window.close();
+ expect(window.isDestroyed()).toBe(false);
+ advance(5_000);
+ window.close();
+ expect(window.isDestroyed()).toBe(true);
+ });
+
+ test("a window closed before its note loaded closes without waiting", () => {
+ const { controller, windows } = setup({ listening: false });
+ controller.open("memo_a");
+ windows[0].close();
+ expect(windows[0].isDestroyed()).toBe(true);
+ expect(windows[0].sent).toEqual([]);
+ expect(controller.list()).toEqual([]);
+ });
+
+ test("a crashed renderer closes without waiting", () => {
+ const { controller, windows } = setup();
+ controller.open("memo_a");
+ windows[0].crashed = true;
+ windows[0].close();
+ expect(windows[0].isDestroyed()).toBe(true);
+ expect(windows[0].sent).toEqual([]);
+ });
+
+ test("closeAll waits for confirmations and forces the rest after the timeout", async () => {
+ const { controller, windows, fireTimers } = setup();
+ controller.open("memo_a");
+ controller.open("memo_b");
+ const done = controller.closeAll();
+ expect(windows.map((window) => window.sent)).toEqual([[NOTE_WINDOW_CLOSE_REQUEST_CHANNEL], [NOTE_WINDOW_CLOSE_REQUEST_CHANNEL]]);
+ controller.resolveClose(windows[0].webContents, true);
+ // A refusal cannot hold back quitting or an account switch.
+ expect(controller.resolveClose(windows[1].webContents, false)).toBe(false);
+ expect(windows[1].isDestroyed()).toBe(false);
+ fireTimers();
+ expect(await done).toEqual([true, true]);
+ expect(controller.list()).toEqual([]);
+ });
+
+ test("identifies note window senders and ignores other web contents", () => {
+ const { controller, windows } = setup();
+ controller.open("memo_a");
+ expect(controller.isNoteWindowContents(windows[0].webContents)).toBe(true);
+ expect(controller.memoIdForContents(windows[0].webContents)).toBe("memo_a");
+ expect(controller.isNoteWindowContents({})).toBe(false);
+ expect(controller.resolveClose({}, true)).toBe(false);
+ windows[0].crashed = true;
+ windows[0].close();
+ expect(controller.isNoteWindowContents(windows[0].webContents)).toBe(false);
+ });
+
+ test("a new window counts as open only after its renderer shows the note", async () => {
+ const { controller, windows, failures } = setup();
+ controller.open("memo_a");
+ // The note already belongs to the window while it loads.
+ expect(controller.list()).toEqual(["memo_a"]);
+ const ready = controller.waitUntilReady("memo_a");
+ expect(controller.markReady(windows[0].webContents)).toBe(true);
+ expect(await ready).toBe(true);
+ expect(await controller.waitUntilReady("memo_a")).toBe(true);
+ expect(failures).toEqual([]);
+ });
+
+ test("a window that fails to load is closed and gives the note back", async () => {
+ const { controller, windows, changes, failures } = setup();
+ controller.open("memo_a");
+ const ready = controller.waitUntilReady("memo_a");
+ expect(controller.fail(windows[0].webContents, "load-failed")).toBe(true);
+ expect(await ready).toBe(false);
+ expect(windows[0].isDestroyed()).toBe(true);
+ expect(windows[0].sent).toEqual([]);
+ expect(controller.list()).toEqual([]);
+ expect(changes.at(-1)).toEqual([]);
+ // Recorded for diagnostics; the waiting caller tells the user.
+ expect(failures).toEqual([["memo_a", "load-failed", false]]);
+ expect(controller.failureReason("memo_a")).toBe("load-failed");
+ expect(controller.markReady(windows[0].webContents)).toBe(false);
+ expect(controller.open("memo_a")).toEqual({ opened: true });
+ expect(controller.failureReason("memo_a")).toBeNull();
+ });
+
+ test("a failed window that is still going away is replaced, not reused", () => {
+ const { controller, windows, shown } = setup();
+ controller.open("memo_a");
+ // A renderer that never lets go: destroy() is the only way out.
+ windows[0].destroy = function destroy() { this.stuck = true; };
+ controller.fail(windows[0].webContents, "timeout");
+ expect(windows[0].stuck).toBe(true);
+ expect(controller.open("memo_a")).toEqual({ opened: true });
+ expect(windows).toHaveLength(2);
+ expect(shown).toEqual([]);
+ expect(controller.isNoteWindowContents(windows[1].webContents)).toBe(true);
+ });
+
+ test("a window that never shows its note is closed after the timeout", async () => {
+ const { controller, windows, timers, fireTimers } = setup();
+ controller.open("memo_a");
+ const ready = controller.waitUntilReady("memo_a");
+ expect(timers.at(-1).delay).toBe(30_000);
+ fireTimers();
+ expect(await ready).toBe(false);
+ expect(windows[0].isDestroyed()).toBe(true);
+ expect(controller.list()).toEqual([]);
+ });
+
+ test("closing a window before it is ready ends the wait", async () => {
+ const { controller, windows } = setup({ listening: false });
+ controller.open("memo_a");
+ const ready = controller.waitUntilReady("memo_a");
+ windows[0].close();
+ expect(await ready).toBe(false);
+ expect(await controller.waitUntilReady("memo_a")).toBe(false);
+ });
+
+ test("a load aborted because the user closed the window is not a failure", async () => {
+ const { controller, windows, failures } = setup({ listening: false });
+ controller.open("memo_a");
+ const ready = controller.waitUntilReady("memo_a");
+ // Electron rejects the pending loadURL while the window closes.
+ windows[0].on("close", () => controller.fail(windows[0].webContents, "load-failed"));
+ windows[0].close();
+ expect(await ready).toBe(false);
+ expect(failures).toEqual([]);
+ expect(controller.failureReason("memo_a")).toBeNull();
+ });
+
+ test("a renderer crash after the handoff closes the window and tells the main window", () => {
+ const { controller, windows, failures } = setup();
+ controller.open("memo_a");
+ controller.markReady(windows[0].webContents);
+ windows[0].crashed = true;
+ expect(controller.fail(windows[0].webContents, "crashed")).toBe(true);
+ expect(windows[0].isDestroyed()).toBe(true);
+ expect(controller.list()).toEqual([]);
+ expect(failures).toEqual([["memo_a", "crashed", true]]);
+ expect(controller.fail(windows[0].webContents, "crashed")).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/preload/index.cjs b/apps/desktop/src/preload/index.cjs
index 693c78f8..1b356971 100644
--- a/apps/desktop/src/preload/index.cjs
+++ b/apps/desktop/src/preload/index.cjs
@@ -120,6 +120,31 @@ contextBridge.exposeInMainWorld("edgeeverDesktop", Object.freeze({
ipcRenderer.on("desktop:command", listener);
return () => ipcRenderer.removeListener("desktop:command", listener);
},
+ noteWindows: () => ipcRenderer.invoke("desktop:note-windows"),
+ openNoteWindow: (memoId) => ipcRenderer.invoke("desktop:open-note-window", memoId),
+ focusNoteWindow: (memoId) => ipcRenderer.invoke("desktop:focus-note-window", memoId),
+ onNoteWindowsChanged: (callback) => {
+ const listener = (_event, memoIds) => callback(Array.isArray(memoIds) ? memoIds : []);
+ ipcRenderer.on("desktop:note-windows-changed", listener);
+ return () => ipcRenderer.removeListener("desktop:note-windows-changed", listener);
+ },
+ onNoteWindowCloseRequest: (callback) => {
+ const listener = () => callback();
+ ipcRenderer.on("desktop:note-window-close-request", listener);
+ ipcRenderer.send("desktop:note-window-listening");
+ return () => ipcRenderer.removeListener("desktop:note-window-close-request", listener);
+ },
+ resolveNoteWindowClose: (allowed) => ipcRenderer.send("desktop:note-window-close-result", allowed === true),
+ notifyNoteWindowSaved: () => ipcRenderer.send("desktop:note-window-saved"),
+ notifyNoteWindowReady: () => ipcRenderer.send("desktop:note-window-ready"),
+ notifyNoteWindowLoadFailed: () => ipcRenderer.send("desktop:note-window-load-failed"),
+ sendNoteWindowSync: (memoId, update) => ipcRenderer.send("desktop:note-window-sync", memoId, update),
+ onNoteWindowSync: (callback) => {
+ const listener = (_event, update) => callback(update);
+ ipcRenderer.on("desktop:note-window-sync", listener);
+ return () => ipcRenderer.removeListener("desktop:note-window-sync", listener);
+ },
+ openMemoInMainWindow: (memoId) => ipcRenderer.invoke("desktop:open-memo-in-main-window", memoId),
setRichTextHeadingShortcutActive: (active) => {
ipcRenderer.sendSync("desktop:rich-text-heading-shortcut", active === true);
},
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index aa0b4686..99d87ce2 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -19,6 +19,7 @@ import { classifyLoginError, getLoginProblemMessageKey } from "@/lib/login-error
import { EVERNOTE_MIGRATION_PATH } from "@/lib/routes";
import { isBrowserOffline } from "@/lib/network-status";
import { syncPublishedNoteBodyFont } from "@/lib/published-note-body-font";
+import { getNoteWindowMemoId } from "@/lib/desktop-note-windows";
import type { AuthSession } from "@edgeever/shared";
const EvernoteImportGuidePane = lazy(() =>
@@ -29,6 +30,7 @@ const WorkspaceApp = lazy(() => import("@/components/WorkspaceApp").then((module
const PublicNotebookSharePage = lazy(() => import("@/components/PublicNotebookSharePage").then(module => ({ default: module.PublicNotebookSharePage })));
const PublicSharePage = lazy(() => import("@/components/PublicSharePage").then((module) => ({ default: module.PublicSharePage })));
const PublicTableFormPage = lazy(() => import("@/components/PublicTableFormPage").then((module) => ({ default: module.PublicTableFormPage })));
+const NoteWindowApp = lazy(() => import("@/components/NoteWindowApp").then((module) => ({ default: module.NoteWindowApp })));
const NotebookSiteManagementPage = lazy(() => import("@/components/NotebookSiteManagementPage").then((module) => ({ default: module.NotebookSiteManagementPage })));
const AuthLoadingScreen = ({ title = "EdgeEver", detail }: { title?: string; detail?: string }) => (
@@ -224,11 +226,23 @@ const AuthenticatedWorkspace = ({ siteManagement = false }: { siteManagement?: b
};
export const App = () => {
+ const [noteWindowMemoId] = useState(() => getNoteWindowMemoId());
useEffect(() => {
const bridge = window.edgeeverDesktop;
const baseUrl = getConfiguredDesktopApiBaseUrl();
- if (bridge?.isAvailable && baseUrl) void bridge.setApiBaseUrl(baseUrl);
- }, []);
+ // The main window owns the instance; a note window only edits its note.
+ if (bridge?.isAvailable && baseUrl && !noteWindowMemoId) void bridge.setApiBaseUrl(baseUrl);
+ }, [noteWindowMemoId]);
+
+ if (noteWindowMemoId) {
+ return (
+ <TooltipProvider delayDuration={0} skipDelayDuration={0}>
+ <Suspense fallback={<AuthLoadingScreen />}>
+ <NoteWindowApp memoId={noteWindowMemoId} />
+ </Suspense>
+ </TooltipProvider>
+ );
+ }
return (
<TooltipProvider delayDuration={0} skipDelayDuration={0}>
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsx
index 02b56e7b..91e791a0 100644
--- a/apps/web/src/components/EditorPane.tsx
+++ b/apps/web/src/components/EditorPane.tsx
@@ -28,6 +28,7 @@ import {
Share2,
Globe,
Copy,
+ AppWindow,
CopyPlus,
Lock,
LockOpen,
@@ -348,6 +349,10 @@ type EditorPaneProps = {
onMobileDefaultEditConsumed: () => void;
onSaveAsTemplate: (memo: MemoDetail, name: string) => Promise<void>;
onDuplicateMemo?: (memo: MemoDetail) => void;
+ /** Desktop only: move this note to its own window. */
+ onOpenInNewWindow?: (memoId: string) => void;
+ /** Receives a function that saves pending edits and reports whether nothing is left unsaved. */
+ onRegisterPendingSave?: (save: (() => Promise<boolean>) | null) => void;
searchFocusToken: number;
replaceFocusToken: number;
aiAssistantOpenToken: number;
@@ -427,6 +432,8 @@ const RichEditorPane = ({
onMobileDefaultEditConsumed,
onSaveAsTemplate,
onDuplicateMemo,
+ onOpenInNewWindow,
+ onRegisterPendingSave,
onCreatePoster,
searchFocusToken,
replaceFocusToken,
@@ -3185,6 +3192,41 @@ const RichEditorPane = ({
const mutateSave = saveMutation.mutate;
const mutateSaveAsync = saveMutation.mutateAsync;
const saveMutationPending = saveMutation.isPending;
+ const saveMutationPendingRef = useRef(saveMutationPending);
+ saveMutationPendingRef.current = saveMutationPending;
+
+ // Used before the note moves to another window or its window closes: wait
+ // for a save in flight, then save what is left. A conflict or storage error
+ // reports false so the caller keeps the note where it is.
+ const savePendingEdits = async () => {
+ if (!memoRef.current || memoRef.current.isDeleted) return true;
+ persistCurrentDraft();
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ for (let waited = 0; saveMutationPendingRef.current && waited < 15_000; waited += 50) {
+ await new Promise((resolve) => window.setTimeout(resolve, 50));
+ }
+ if (saveMutationPendingRef.current) return false;
+ if (!hasUnsavedChangesRef.current) return true;
+ try {
+ // Storage that stops answering must surface as a failed handover, not a hang.
+ const saved = await Promise.race([
+ mutateSaveAsync().then(() => true),
+ new Promise<false>((resolve) => window.setTimeout(() => resolve(false), 15_000)),
+ ]);
+ if (!saved) return false;
+ } catch {
+ return !hasUnsavedChangesRef.current;
+ }
+ }
+ return !hasUnsavedChangesRef.current;
+ };
+ const savePendingEditsRef = useRef(savePendingEdits);
+ savePendingEditsRef.current = savePendingEdits;
+ useEffect(() => {
+ if (!onRegisterPendingSave) return;
+ onRegisterPendingSave(() => savePendingEditsRef.current());
+ return () => onRegisterPendingSave(null);
+ }, [onRegisterPendingSave]);
const editorShortcutBlocked = Boolean(
historyOpen ||
@@ -4328,6 +4370,17 @@ const RichEditorPane = ({
{t("editor.duplicate")}
</DropdownMenuItem>
)}
+ {onOpenInNewWindow && (
+ <DropdownMenuItem
+ className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
+ // A note created offline gets its permanent ID on first sync.
+ disabled={isLocalMemoId(memo.id)}
+ onClick={() => onOpenInNewWindow(memo.id)}
+ >
+ <AppWindow className="h-4 w-4 text-slate-500" />
+ {t(isLocalMemoId(memo.id) ? "editor.openInNewWindowAfterSync" : "editor.openInNewWindow")}
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
className="flex h-9 w-full items-center gap-2 px-3 text-left text-xs text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"
onClick={handleExportMarkdown}
diff --git a/apps/web/src/components/NoteInSeparateWindowPane.tsx b/apps/web/src/components/NoteInSeparateWindowPane.tsx
new file mode 100644
index 00000000..3c03043d
--- /dev/null
+++ b/apps/web/src/components/NoteInSeparateWindowPane.tsx
@@ -0,0 +1,21 @@
+import { AppWindow } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { getMemoDisplayTitle } from "@edgeever/shared";
+import { Button } from "@/components/ui/button";
+
+/** Shown in the main window while the selected note is open in its own window. */
+export const NoteInSeparateWindowPane = ({ title, onShowWindow }: { title: string | null; onShowWindow: () => void }) => {
+ const { t } = useTranslation();
+ return (
+ <div className="flex h-full min-h-0 items-center justify-center bg-transparent px-6">
+ <div className="flex max-w-sm flex-col items-center gap-3 text-center" data-testid="note-in-separate-window">
+ <AppWindow className="h-8 w-8 text-slate-400" aria-hidden="true" />
+ <p className="text-sm font-medium text-slate-700">{getMemoDisplayTitle(title, t("common.untitledMemo"))}</p>
+ <p className="text-sm leading-6 text-slate-500">{t("editor.noteInSeparateWindow")}</p>
+ <Button variant="outline" size="sm" onClick={onShowWindow}>
+ {t("editor.showNoteWindow")}
+ </Button>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/src/components/NoteWindowApp.tsx b/apps/web/src/components/NoteWindowApp.tsx
new file mode 100644
index 00000000..a89163ab
--- /dev/null
+++ b/apps/web/src/components/NoteWindowApp.tsx
@@ -0,0 +1,238 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useTranslation } from "react-i18next";
+import { getMemoDisplayTitle, hasTableDocumentMarker, parseDiagramDocument, type MemoDetail } from "@edgeever/shared";
+import { EditorPane } from "@/components/EditorPane";
+import { EditorPaneErrorBoundary } from "@/components/EditorPaneErrorBoundary";
+import { Button } from "@/components/ui/button";
+import { api, getCachedDesktopSession } from "@/lib/api";
+import { getPersistentDataScopeOrigin } from "@/lib/app-page-path";
+import { getShortcutActionForEvent, readImageCompressionPreference, readShortcutSettingsPreference } from "@/lib/app-helpers";
+import { noteWindowSyncCompletedDetail } from "@/lib/desktop-note-windows";
+import { createLocalDataScope, putLocalMemo } from "@/lib/local-mirror";
+import { updateMemoSummaryInLists } from "@/lib/memo-list-cache";
+import { EdgeEverPluginHost } from "@/lib/plugins/plugin-host";
+import { createRepository } from "@/lib/repository";
+import { cacheMemoDetail, memoDetailQueryKey, memoToSummary } from "@/lib/workspace-memo-cache";
+import { useNoteProse } from "@/hooks/useNoteProse";
+
+const noop = () => undefined;
+
+/**
+ * A desktop window that shows a single note. Loading, sync and plugins stay in
+ * the main window; this window only edits the note, saves through the same
+ * repository, and hands everything else back to the main window. The main
+ * window forwards each sync result here so this editor tracks acknowledgements,
+ * remote changes and conflicts like the main editor does.
+ */
+export const NoteWindowApp = ({ memoId }: { memoId: string }) => {
+ const { t } = useTranslation();
+ const queryClient = useQueryClient();
+ const bridge = window.edgeeverDesktop;
+ const sessionQuery = useQuery({
+ queryKey: ["auth", "session"],
+ queryFn: async () => {
+ try {
+ return await api.getSession();
+ } catch (error) {
+ const cached = getCachedDesktopSession();
+ if (cached?.authenticated) return cached;
+ throw error;
+ }
+ },
+ initialData: () => getCachedDesktopSession() ?? undefined,
+ retry: false,
+ });
+ const userId = sessionQuery.data?.authenticated ? sessionQuery.data.user?.id ?? null : null;
+ const localDataScope = useMemo(
+ () => createLocalDataScope(getPersistentDataScopeOrigin(window.location.origin), userId),
+ [userId],
+ );
+ const repository = useMemo(() => createRepository(localDataScope), [localDataScope]);
+ // Plugins are never activated here, so no plugin code runs twice.
+ const pluginHost = useMemo(() => new EdgeEverPluginHost({
+ repository,
+ scope: localDataScope,
+ aiAdapter: api.pluginAi,
+ onWorkspaceChanged: async () => undefined,
+ }), [localDataScope, repository]);
+ const memoQuery = useQuery({
+ networkMode: "offlineFirst",
+ queryKey: memoDetailQueryKey(memoId, "notebook"),
+ queryFn: () => repository.getMemo(memoId),
+ enabled: Boolean(sessionQuery.data),
+ retry: false,
+ });
+ const notebooksQuery = useQuery({
+ queryKey: ["notebooks"],
+ queryFn: () => repository.listNotebooks(),
+ networkMode: "offlineFirst",
+ enabled: Boolean(sessionQuery.data),
+ });
+ const { noteProse } = useNoteProse();
+ const [shortcutSettings] = useState(readShortcutSettingsPreference);
+ const [imageCompressionEnabled] = useState(readImageCompressionPreference);
+ const [focusMode, setFocusMode] = useState(false);
+ const [tokens, setTokens] = useState({ search: 0, replace: 0, ai: 0, saveAndSync: 0, readingProtection: 0, editorMode: 0, outline: 0 });
+ const [closeError, setCloseError] = useState(false);
+ const pendingSaveRef = useRef<(() => Promise<boolean>) | null>(null);
+ const closeFailedRef = useRef(false);
+ const deletedRef = useRef(false);
+ const memo = memoQuery.data?.memo ?? null;
+ const unsupported = Boolean(memo && (memo.isDeleted || parseDiagramDocument(memo.contentMarkdown) || hasTableDocumentMarker(memo.contentMarkdown)));
+ // A failed reload after a sync keeps the note it already shows; only a
+ // note that never loaded, or is gone or unsupported, leaves the editor.
+ const unavailable = (sessionQuery.isError && !sessionQuery.data) || (memoQuery.isError && !memo) || unsupported;
+
+ // The main window counts the move as done only once this window shows the
+ // note. If it cannot, the main process closes this window and the main
+ // window shows the note again.
+ const handoffReportedRef = useRef(false);
+ useEffect(() => {
+ if (handoffReportedRef.current || (!unavailable && !memo)) return;
+ handoffReportedRef.current = true;
+ if (unavailable) bridge?.notifyNoteWindowLoadFailed?.();
+ else bridge?.notifyNoteWindowReady?.();
+ }, [bridge, memo, unavailable]);
+
+ useEffect(() => bridge?.onNoteWindowSync?.((update) => {
+ // Same order as the main window: advance the editor's sync state, then
+ // reload the note so remote changes reach it.
+ window.dispatchEvent(new CustomEvent("edgeever:sync-completed", { detail: noteWindowSyncCompletedDetail(memoId, update) }));
+ void Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["memo", memoId] }),
+ queryClient.invalidateQueries({ queryKey: ["notebooks"] }),
+ ]);
+ }), [bridge, memoId, queryClient]);
+
+ useEffect(() => {
+ document.title = memo ? `${getMemoDisplayTitle(memo.title, t("common.untitledMemo"))} · EdgeEver` : "EdgeEver";
+ }, [memo, t]);
+
+ const registerPendingSave = useCallback((save: (() => Promise<boolean>) | null) => {
+ pendingSaveRef.current = save;
+ }, []);
+
+ // Closing the window waits for pending edits. If they cannot be saved, the
+ // window stays open with an explanation; closing again closes it, and the
+ // edits stay in this device's local draft for the main window to recover.
+ useEffect(() => bridge?.onNoteWindowCloseRequest?.(() => {
+ void (async () => {
+ if (deletedRef.current || closeFailedRef.current) {
+ bridge.resolveNoteWindowClose?.(true);
+ return;
+ }
+ const saved = pendingSaveRef.current ? await pendingSaveRef.current().catch(() => false) : true;
+ if (!saved) {
+ closeFailedRef.current = true;
+ setCloseError(true);
+ }
+ bridge.resolveNoteWindowClose?.(saved);
+ })();
+ }), [bridge]);
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const action = getShortcutActionForEvent(event, shortcutSettings);
+ const key = action === "focusSearch" ? "search"
+ : action === "focusReplace" ? "replace"
+ : action === "openAiAssistant" ? "ai"
+ : action === "saveAndSync" ? "saveAndSync"
+ : action === "toggleReadingProtection" ? "readingProtection"
+ : action === "toggleEditorMode" ? "editorMode"
+ : action === "toggleOutline" ? "outline"
+ : null;
+ if (!key) return;
+ event.preventDefault();
+ setTokens((current) => ({ ...current, [key]: current[key] + 1 }));
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [shortcutSettings]);
+
+ const handleSaved = useCallback(async (saved: MemoDetail) => {
+ await putLocalMemo(localDataScope, saved);
+ cacheMemoDetail(queryClient, saved, "notebook");
+ updateMemoSummaryInLists(queryClient, memoToSummary(saved));
+ closeFailedRef.current = false;
+ setCloseError(false);
+ bridge?.notifyNoteWindowSaved?.();
+ }, [bridge, localDataScope, queryClient]);
+
+ const openInMainWindow = useCallback((targetMemoId: string) => {
+ void bridge?.openMemoInMainWindow?.(targetMemoId);
+ }, [bridge]);
+
+ const handleDeleted = useCallback(async (deletedMemoId: string) => {
+ await repository.deleteMemo(deletedMemoId);
+ deletedRef.current = true;
+ bridge?.notifyNoteWindowSaved?.();
+ window.close();
+ }, [bridge, repository]);
+
+ if (unavailable) {
+ return (
+ <main className="flex h-[100dvh] items-center justify-center bg-background px-6 text-center">
+ <div className="flex max-w-sm flex-col items-center gap-3">
+ <p className="text-sm leading-6 text-slate-600">{t("editor.noteWindowUnavailable")}</p>
+ <Button variant="outline" size="sm" onClick={() => {
+ deletedRef.current = true;
+ window.close();
+ }}>
+ {t("editor.closeNoteWindow")}
+ </Button>
+ </div>
+ </main>
+ );
+ }
+
+ return (
+ <main className="flex h-[100dvh] min-h-0 flex-col bg-background">
+ {closeError && (
+ <div role="alert" className="border-b border-rose-200 bg-rose-50 px-4 py-2 text-xs leading-5 text-rose-800">
+ {t("editor.noteWindowCloseSaveFailed")}
+ </div>
+ )}
+ <div className="min-h-0 flex-1">
+ <EditorPaneErrorBoundary resetKey={memoId} onBackToList={noop}>
+ <EditorPane
+ key={memoId}
+ memo={memo}
+ repository={repository}
+ pluginHost={pluginHost}
+ desktopFocusMode={focusMode}
+ onToggleDesktopFocusMode={() => setFocusMode((value) => !value)}
+ noteProse={noteProse}
+ mobileDefaultEditMemoId={null}
+ isTrashView={false}
+ notebooks={notebooksQuery.data?.notebooks ?? []}
+ isLoading={memoQuery.isLoading || sessionQuery.isLoading}
+ imageCompressionEnabled={imageCompressionEnabled}
+ shortcutSettings={shortcutSettings}
+ searchFocusToken={tokens.search}
+ replaceFocusToken={tokens.replace}
+ aiAssistantOpenToken={tokens.ai}
+ saveAndSyncToken={tokens.saveAndSync}
+ readingProtectionToggleToken={tokens.readingProtection}
+ editorModeToggleToken={tokens.editorMode}
+ outlineToggleToken={tokens.outline}
+ onSyncRequested={async () => bridge?.notifyNoteWindowSaved?.()}
+ onOpenMemo={openInMainWindow}
+ onOpenCompanionNote={openInMainWindow}
+ onOpenExecutionCenter={noop}
+ onBackToList={noop}
+ onSaved={handleSaved}
+ onDeleted={handleDeleted}
+ onPermanentDeleted={handleDeleted}
+ onRestored={async () => undefined}
+ onMobileDefaultEditConsumed={noop}
+ onSaveAsTemplate={async (source, name) => {
+ await repository.createTemplate({ name, memoId: source.id });
+ }}
+ onRegisterPendingSave={registerPendingSave}
+ />
+ </EditorPaneErrorBoundary>
+ </div>
+ </main>
+ );
+};
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index c69d102c..6e0eef59 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -138,6 +138,8 @@ import {
writeDesktopWorkspaceRestoreState,
} from "@/lib/desktop-workspace-restore";
import { EditorPaneErrorBoundary, EditorRecoveryPane } from "./EditorPaneErrorBoundary";
+import { NoteInSeparateWindowPane } from "./NoteInSeparateWindowPane";
+import { canOpenNoteWindows, noteWindowSyncUpdate, useDetachedMemoIds, type NoteWindowSyncCompletedDetail } from "@/lib/desktop-note-windows";
import { isMarkdownFile, readMarkdownFile } from "@/lib/markdown-file-import";
import { compressImageForUpload } from "@/lib/image-compression";
import { createScreenshotMemo, screenshotFileFromImportPayload, screenshotImportDedupeKey, screenshotImportGate } from "@/lib/screenshot-import";
@@ -260,6 +262,16 @@ export const WorkspaceApp = ({
const [notebookNameDialog, setNotebookNameDialog] = useState<NotebookNameDialogState | null>(null);
const [notebookDeleteConfirmation, setNotebookDeleteConfirmation] = useState<Notebook | null>(null);
const [appNoticeDialog, setAppNoticeDialog] = useState<AppNoticeDialogState | null>(null);
+ const [detachedMemoIds, setDetachedMemoIds] = useDetachedMemoIds();
+ const pendingEditorSaveRef = useRef<(() => Promise<boolean>) | null>(null);
+ const registerPendingEditorSave = useCallback((save: (() => Promise<boolean>) | null) => {
+ pendingEditorSaveRef.current = save;
+ }, []);
+ const focusDetachedMemo = useCallback((memoId: string) => {
+ if (!detachedMemoIds.has(memoId)) return false;
+ void window.edgeeverDesktop?.focusNoteWindow?.(memoId);
+ return true;
+ }, [detachedMemoIds]);
const [wechatImportFailureId, setWeChatImportFailureId] = useState<string | null>(null);
const [wechatImportsInProgress, setWeChatImportsInProgress] = useState(0);
const [sharedFileImportsInProgress, setSharedFileImportsInProgress] = useState(0);
@@ -1536,6 +1548,96 @@ export const WorkspaceApp = ({
const selectedMemo = memoQuery.data?.memo ?? cachedSelectedMemo;
const selectedDiagram = parseDiagramDocument(selectedMemo?.contentMarkdown);
const selectedTableNote = hasTableDocumentMarker(selectedMemo?.contentMarkdown);
+ const selectedMemoDetached = Boolean(selectedMemo && detachedMemoIds.has(selectedMemo.id));
+ const noteWindowsAvailable = canOpenNoteWindows();
+
+ const returnDetachedMemo = useCallback((memoId: string) => {
+ setDetachedMemoIds((current) => {
+ if (!current.has(memoId)) return current;
+ const next = new Set(current);
+ next.delete(memoId);
+ return next;
+ });
+ void queryClient.invalidateQueries({ queryKey: ["memo", memoId] });
+ }, [queryClient, setDetachedMemoIds]);
+
+ // Sync runs only here. Pass each result on to the note windows so their
+ // editors see acknowledgements, remote changes and conflicts as this one does.
+ const detachedMemoIdsRef = useRef(detachedMemoIds);
+ detachedMemoIdsRef.current = detachedMemoIds;
+ const forwardSyncToNoteWindows = useCallback((detail: NoteWindowSyncCompletedDetail | null) => {
+ const bridge = window.edgeeverDesktop;
+ if (!bridge?.sendNoteWindowSync) return;
+ for (const memoId of detachedMemoIdsRef.current) bridge.sendNoteWindowSync(memoId, noteWindowSyncUpdate(detail, memoId));
+ }, []);
+ useEffect(() => {
+ if (!noteWindowsAvailable) return;
+ const handleSyncCompleted = (event: Event) => forwardSyncToNoteWindows((event as CustomEvent<NoteWindowSyncCompletedDetail>).detail ?? null);
+ window.addEventListener("edgeever:sync-completed", handleSyncCompleted);
+ return () => window.removeEventListener("edgeever:sync-completed", handleSyncCompleted);
+ }, [forwardSyncToNoteWindows, noteWindowsAvailable]);
+
+ // Moving a note hands its pending edits over first: the editor saves, and
+ // only then does the note leave this window. A failed save keeps it here.
+ const handleOpenMemoInNewWindow = useCallback(async (memoId: string) => {
+ const bridge = window.edgeeverDesktop;
+ if (!bridge?.openNoteWindow) return;
+ if (focusDetachedMemo(memoId)) return;
+ if (selectedMemo?.id === memoId && pendingEditorSaveRef.current && !await pendingEditorSaveRef.current()) {
+ setAppNoticeDialog({ title: t("editor.openInNewWindow"), description: t("editor.openInNewWindowSaveFailed") });
+ return;
+ }
+ // The main process reports which notes have windows, so this window
+ // follows its list instead of guessing from the call's result.
+ try {
+ await bridge.openNoteWindow(memoId);
+ } catch (error) {
+ // The window could not show the note and was closed: the note and its
+ // editor come back here, reloaded from what was saved before the move.
+ console.error("Failed to open the note window", error);
+ returnDetachedMemo(memoId);
+ const message = String(error instanceof Error ? error.message : error);
+ // Closed before it was ready, by the user or on quit: nothing to report.
+ if (message.includes("note-window-failed:closed")) return;
+ setAppNoticeDialog({
+ title: t("editor.openInNewWindow"),
+ description: message.includes("note-window-failed:note-unavailable") ? t("editor.noteWindowUnavailable") : t("editor.openInNewWindowFailed"),
+ });
+ }
+ }, [focusDetachedMemo, returnDetachedMemo, selectedMemo?.id, t]);
+
+ const previousSelectedMemoIdRef = useRef(selectedMemoId);
+ useEffect(() => {
+ if (previousSelectedMemoIdRef.current === selectedMemoId) return;
+ previousSelectedMemoIdRef.current = selectedMemoId;
+ // Selecting a moved note (for example with the previous/next shortcuts)
+ // brings its window forward instead of showing it here as well.
+ if (selectedMemoId && document.hasFocus()) focusDetachedMemo(selectedMemoId);
+ }, [focusDetachedMemo, selectedMemoId]);
+
+ const noteWindowCommandRef = useRef<(command: string) => boolean>(() => false);
+ noteWindowCommandRef.current = (command) => {
+ if (command === "open-memo-window") {
+ if (selectedMemo && !selectedDiagram && !selectedTableNote && noteWindowsAvailable) void handleOpenMemoInNewWindow(selectedMemo.id);
+ return true;
+ }
+ if (command.startsWith("note-window-saved:")) {
+ const memoId = command.slice("note-window-saved:".length);
+ void Promise.all([
+ queryClient.invalidateQueries({ queryKey: ["memo", memoId] }),
+ queryClient.invalidateQueries({ queryKey: ["memos"] }),
+ queryClient.invalidateQueries({ queryKey: ["notebooks"], refetchType: "inactive" }),
+ ]);
+ void runQueuedSync();
+ return true;
+ }
+ if (command.startsWith("note-window-failed:")) {
+ returnDetachedMemo(command.slice("note-window-failed:".length));
+ setAppNoticeDialog({ title: t("editor.openInNewWindow"), description: t("editor.noteWindowStopped") });
+ return true;
+ }
+ return false;
+ };
const selectedPosterNote = hasPosterDocumentMarker(selectedMemo?.contentMarkdown);
const selectedInfographicNote = Boolean(parseInfographicDocument(selectedMemo?.contentMarkdown));
const desktopNotebookSidebarCollapsed = Boolean(isDesktop && notebookSidebarCollapsed);
@@ -2475,6 +2577,7 @@ export const WorkspaceApp = ({
}, [clearMemoSelection, clearPendingMemoSelection, handleMobileSearch, navigateWorkspaceHome, setSelectedNotebookId]);
const handleOpenQuickSwitcherMemo = useCallback((memo: MemoSummary) => {
+ focusDetachedMemo(memo.id);
pendingQuickSwitcherMemoIdRef.current = memo.id;
setQuickSwitcherOpen(false);
setQuickSwitcherQuery("");
@@ -2490,9 +2593,10 @@ export const WorkspaceApp = ({
setCreatedMemoEditId(null);
setSelectedMemoId(memo.id);
setActivePane("editor");
- }, [clearMemoSelection, clearPendingCreatedMemo, navigateWorkspaceHome, setSelectedMemoId, setSelectedNotebookId]);
+ }, [clearMemoSelection, clearPendingCreatedMemo, focusDetachedMemo, navigateWorkspaceHome, setSelectedMemoId, setSelectedNotebookId]);
const handleOpenPluginNote = useCallback((memoId: string, notebookId: string, options?: { search?: string }) => {
+ focusDetachedMemo(memoId);
setRequestedPluginPanel(null);
navigateWorkspaceHome();
setMemoView("notebook");
@@ -2514,7 +2618,7 @@ export const WorkspaceApp = ({
} else {
setPluginNavigationRequest(null);
}
- }, [clearMemoSelection, clearPendingCreatedMemo, navigateWorkspaceHome, setSelectedMemoId, setSelectedNotebookId]);
+ }, [clearMemoSelection, clearPendingCreatedMemo, focusDetachedMemo, navigateWorkspaceHome, setSelectedMemoId, setSelectedNotebookId]);
const handleOpenLinkedMemo = useMemoLinkNavigation({
repository,
@@ -2685,6 +2789,7 @@ export const WorkspaceApp = ({
const bridge = window.edgeeverDesktop;
if (!bridge?.isAvailable) return;
const removeCommandListener = bridge.onCommand((command) => {
+ if (noteWindowCommandRef.current(command)) return;
if (command === "new-memo") handleCreateMemo();
if (command === "new-notebook") handleCreateNotebook();
if (command === "focus-search") handleGlobalSearch();
@@ -3317,7 +3422,14 @@ export const WorkspaceApp = ({
isOnline={isOnline}
isSyncingQueuedChanges={isSyncingQueuedChanges}
onSyncQueuedChanges={() => void runQueuedSync()}
- onDiscardConflicts={() => void discardConflictsNow()}
+ onDiscardConflicts={() => {
+ // Only a discard that ran changes what note windows show.
+ if (!isOnline) return;
+ void discardConflictsNow().then(
+ () => forwardSyncToNoteWindows(null),
+ (error) => console.error("Failed to discard sync conflicts", error),
+ );
+ }}
onOpenAssets={handleOpenAssets}
onOpenTags={handleOpenTags}
onOpenTemplates={handleOpenTemplates}
@@ -3434,6 +3546,7 @@ export const WorkspaceApp = ({
onBackFromTrash={handleSelectAllMemos}
onClearTag={handleSelectAllMemos}
onOpenMemo={(memoId) => {
+ focusDetachedMemo(memoId);
clearPendingMemoSelection();
if (shouldNavigateHomeWhenOpeningMemo(memoView)) {
navigateWorkspaceHome();
@@ -3600,6 +3713,11 @@ export const WorkspaceApp = ({
<div className="flex h-full min-w-0 flex-col bg-transparent">
{memoSelectionActionBar}
</div>
+ ) : selectedMemo && selectedMemoDetached ? (
+ <NoteInSeparateWindowPane
+ title={selectedMemo.title}
+ onShowWindow={() => focusDetachedMemo(selectedMemo.id)}
+ />
) : (
<EditorPaneErrorBoundary
resetKey={selectedMemo?.id ?? selectedMemoId}
@@ -3852,6 +3970,8 @@ export const WorkspaceApp = ({
onMobileDefaultEditConsumed={handleMobileDefaultEditConsumed}
onSaveAsTemplate={handleSaveAsTemplate}
onDuplicateMemo={handleDuplicateMemo}
+ onOpenInNewWindow={noteWindowsAvailable && memoView !== "trash" ? handleOpenMemoInNewWindow : undefined}
+ onRegisterPendingSave={registerPendingEditorSave}
/>
)}
</EditorPaneErrorBoundary>
diff --git a/apps/web/src/lib/desktop-note-windows.test.mjs b/apps/web/src/lib/desktop-note-windows.test.mjs
new file mode 100644
index 00000000..9d764274
--- /dev/null
+++ b/apps/web/src/lib/desktop-note-windows.test.mjs
@@ -0,0 +1,45 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { getNoteWindowMemoId, noteWindowSyncCompletedDetail, noteWindowSyncUpdate } from "./desktop-note-windows.ts";
+
+const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+afterEach(() => {
+ if (originalWindow) Object.defineProperty(globalThis, "window", originalWindow);
+ else delete globalThis.window;
+});
+
+const memo = (id, revision) => ({ id, revision, title: id, contentMarkdown: "", isDeleted: false });
+
+describe("desktop note windows", () => {
+ test("only a desktop renderer with a valid note id is a note window", () => {
+ delete globalThis.window;
+ expect(getNoteWindowMemoId("?noteWindow=memo_1")).toBeNull();
+ globalThis.window = { edgeeverDesktop: { isAvailable: true }, location: { search: "" } };
+ expect(getNoteWindowMemoId("?noteWindow=memo_1")).toBe("memo_1");
+ expect(getNoteWindowMemoId("?noteWindow=../x")).toBeNull();
+ expect(getNoteWindowMemoId("")).toBeNull();
+ globalThis.window = { location: { search: "" } };
+ expect(getNoteWindowMemoId("?noteWindow=memo_1")).toBeNull();
+ });
+
+ test("a sync result passes each note window its counts and its own acknowledged note", () => {
+ const detail = { failed: 1, conflicted: 2, syncedMemos: new Map([["memo_a", memo("memo_a", 4)], ["memo_b", memo("memo_b", 9)]]) };
+ expect(noteWindowSyncUpdate(detail, "memo_a")).toEqual({ failed: 1, conflicted: 2, memo: memo("memo_a", 4) });
+ expect(noteWindowSyncUpdate(detail, "memo_c")).toEqual({ failed: 1, conflicted: 2, memo: null });
+ // Discarding conflicts has no sync result; the window still reloads its note.
+ expect(noteWindowSyncUpdate(null, "memo_a")).toEqual({ failed: 0, conflicted: 0, memo: null });
+ });
+
+ test("the note window rebuilds the event detail its editor reads", () => {
+ const rebuilt = noteWindowSyncCompletedDetail("memo_a", { failed: 0, conflicted: 1, memo: memo("memo_a", 5) });
+ expect(rebuilt.failed).toBe(0);
+ expect(rebuilt.conflicted).toBe(1);
+ expect(rebuilt.syncedMemos.get("memo_a")).toEqual(memo("memo_a", 5));
+ // A note that is not this window's is ignored.
+ expect(noteWindowSyncCompletedDetail("memo_a", { failed: 0, conflicted: 0, memo: memo("memo_b", 1) }).syncedMemos.size).toBe(0);
+ });
+
+ test("the update survives the structured clone used by Electron IPC", () => {
+ const update = noteWindowSyncUpdate({ failed: 0, conflicted: 0, syncedMemos: new Map([["memo_a", memo("memo_a", 2)]]) }, "memo_a");
+ expect(structuredClone(update)).toEqual(update);
+ });
+});
diff --git a/apps/web/src/lib/desktop-note-windows.ts b/apps/web/src/lib/desktop-note-windows.ts
new file mode 100644
index 00000000..c19b0f3a
--- /dev/null
+++ b/apps/web/src/lib/desktop-note-windows.ts
@@ -0,0 +1,67 @@
+import { useEffect, useState } from "react";
+import type { MemoDetail } from "@edgeever/shared";
+
+export const NOTE_WINDOW_QUERY_PARAM = "noteWindow";
+const MEMO_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
+
+/** The note shown by this renderer when it is a desktop note window. */
+export const getNoteWindowMemoId = (search = typeof window === "undefined" ? "" : window.location.search) => {
+ if (typeof window === "undefined" || !window.edgeeverDesktop?.isAvailable) return null;
+ const memoId = new URLSearchParams(search).get(NOTE_WINDOW_QUERY_PARAM);
+ return memoId && MEMO_ID_PATTERN.test(memoId) ? memoId : null;
+};
+
+export const canOpenNoteWindows = () =>
+ typeof window !== "undefined" && Boolean(window.edgeeverDesktop?.openNoteWindow) && !getNoteWindowMemoId();
+
+/** Notes currently shown in their own desktop windows, as reported by the main process. */
+export const useDetachedMemoIds = () => {
+ const [memoIds, setMemoIds] = useState<ReadonlySet<string>>(() => new Set());
+
+ useEffect(() => {
+ const bridge = window.edgeeverDesktop;
+ if (!bridge?.noteWindows || !bridge.onNoteWindowsChanged || getNoteWindowMemoId()) return;
+ let active = true;
+ const unsubscribe = bridge.onNoteWindowsChanged((ids) => setMemoIds(new Set(ids)));
+ void bridge.noteWindows().then((ids) => {
+ if (active) setMemoIds(new Set(ids));
+ }, () => undefined);
+ return () => {
+ active = false;
+ unsubscribe();
+ };
+ }, []);
+
+ return [memoIds, setMemoIds] as const;
+};
+
+/** The `edgeever:sync-completed` event detail that EditorPane reads. */
+export type NoteWindowSyncCompletedDetail = {
+ failed?: number;
+ conflicted?: number;
+ syncedMemos?: ReadonlyMap<string, MemoDetail>;
+};
+
+/**
+ * Sync runs in the main window. This picks the part of a sync result that the
+ * window showing `memoId` needs: failure and conflict counts, and the note as
+ * acknowledged when this sync included it.
+ */
+export const noteWindowSyncUpdate = (
+ detail: NoteWindowSyncCompletedDetail | null | undefined,
+ memoId: string,
+): DesktopNoteWindowSyncUpdate => ({
+ failed: detail?.failed ?? 0,
+ conflicted: detail?.conflicted ?? 0,
+ memo: detail?.syncedMemos?.get(memoId) ?? null,
+});
+
+/** Rebuilds, inside the note window, the sync event its editor listens for. */
+export const noteWindowSyncCompletedDetail = (
+ memoId: string,
+ update: DesktopNoteWindowSyncUpdate,
+): NoteWindowSyncCompletedDetail => ({
+ failed: update.failed,
+ conflicted: update.conflicted,
+ syncedMemos: new Map(update.memo?.id === memoId ? [[memoId, update.memo]] : []),
+});
diff --git a/apps/web/src/vite-env.d.ts b/apps/web/src/vite-env.d.ts
index 2a9ba658..70f12946 100644
--- a/apps/web/src/vite-env.d.ts
+++ b/apps/web/src/vite-env.d.ts
@@ -38,6 +38,14 @@ interface DesktopLoginItemState {
error?: "invalid" | "saveFailed";
}
+/** A main-window sync result for the note shown in a note window. */
+interface DesktopNoteWindowSyncUpdate {
+ failed: number;
+ conflicted: number;
+ /** The note as acknowledged by this sync, when it was part of it. */
+ memo: import("@edgeever/shared").MemoDetail | null;
+}
+
interface EdgeEverDesktopBridge {
backup<A extends keyof import("@edgeever/shared").DesktopBackupActions>(action: A, input?: import("@edgeever/shared").DesktopBackupActions[A]["input"]): Promise<import("@edgeever/shared").DesktopBackupActions[A]["output"]>;
onBackupStatus(callback: (status: import("@edgeever/shared").DesktopBackupStatus | null) => void): () => void;
@@ -120,6 +128,18 @@ interface EdgeEverDesktopBridge {
readResource(id: string): Promise<{ type: string; bytes: Uint8Array }>;
removeStagedResource(id: string): Promise<void>;
onCommand(callback: (command: string) => void): () => void;
+ noteWindows?(): Promise<string[]>;
+ openNoteWindow?(memoId: string): Promise<{ opened: boolean }>;
+ focusNoteWindow?(memoId: string): Promise<boolean>;
+ onNoteWindowsChanged?(callback: (memoIds: string[]) => void): () => void;
+ onNoteWindowCloseRequest?(callback: () => void): () => void;
+ resolveNoteWindowClose?(allowed: boolean): void;
+ notifyNoteWindowSaved?(): void;
+ notifyNoteWindowReady?(): void;
+ notifyNoteWindowLoadFailed?(): void;
+ sendNoteWindowSync?(memoId: string, update: DesktopNoteWindowSyncUpdate): void;
+ onNoteWindowSync?(callback: (update: DesktopNoteWindowSyncUpdate) => void): () => void;
+ openMemoInMainWindow?(memoId: string): Promise<boolean>;
setRichTextHeadingShortcutActive?(active: boolean): void;
onHeadingShortcut?(callback: (level: number) => void): () => void;
onHibernatePrepare?(callback: () => void | Promise<void>): () => void;
diff --git a/docs/changes/2026-10-29-desktop-note-window.md b/docs/changes/2026-10-29-desktop-note-window.md
new file mode 100644
index 00000000..1b1565e2
--- /dev/null
+++ b/docs/changes/2026-10-29-desktop-note-window.md
@@ -0,0 +1,25 @@
+# Open a note in a new window (desktop)
+
+[简体中文](2026-10-29-desktop-note-window.zh-CN.md)
+
+## Problem and outcome
+
+Implements [Issue #67](https://github.com/tianma-if/edgeever/issues/67). Desktop users could only edit one note at a time in the main window. A note can now be moved to its own window from the note's "More" menu or with File → Open Note in New Window (`Cmd/Ctrl+Shift+O`), so it can sit next to the main window or on another screen.
+
+## Behavior
+
+| ID | Behavior | Acceptance |
+| --- | --- | --- |
+| W01 | A note is shown in at most one window. Moving it to a new window first saves pending edits in the main editor; the main window then shows a placeholder with a "Show window" button instead of a second editor. | Electron scenario A1: text typed in the main window appears in the new window, and the main window has no editor for that note. |
+| W02 | Opening the same note again from the menu item, the shortcut, the note list, quick switcher, plugin links or the placeholder focuses the existing window instead of creating another one. | Unit test "opens one window per note"; Electron scenario A2. |
+| W03 | Closing the note window saves pending edits first. The note then opens in the main window again with the saved content. | Unit test "closing asks the renderer first"; Electron scenarios B1, B2. |
+| W04 | If saving fails before the move (for example local storage does not answer within 15 s), the note stays in the main window with its content and a message. If saving fails when the window closes, the window stays open with a message; closing it again closes it and the local draft is recovered in the main window. A renderer that stops answering is closed on the second close after 5 s. | Unit tests for failed save and stuck renderer; Electron scenarios D1 (storage paused) and E1. |
+| W05 | Quitting, switching account or instance, clearing the session or clearing local data asks every note window to save first and closes it after at most 5 s. Note windows are not restored after a restart. | Unit test "closeAll"; Electron scenario F1 (quit, relaunch, content kept). |
+| W06 | Note windows are editor-only: links to other notes open them in the main window, deleting the note closes its window, and several notes can each have their own window. They cannot open further windows, switch account, change the instance or start plugins. | Electron scenarios A3, C1, C2, G1. |
+| W07 | Only notes that already exist in storage can be moved; a note that has not been created yet shows "Open in new window after sync". Diagrams, tables, trash and the web app do not offer the action. | Manual check of the menu states. |
+| W08 | A move counts as done only once the new window shows the note. If the window fails to load, cannot show the note, crashes, or does not report back within 30 s, it is destroyed, the main window shows the note in its editor again and explains what happened ("can't be shown in a separate window" for a missing or unsupported note, "couldn't open" otherwise). A note window that crashes after the move also gives the note back with a message. Failure reasons are written to desktop diagnostics. | Unit tests for readiness, load failure, timeout, closing while loading, crash after the move and replacing a window that is still going away; Electron scenarios H1 (load blocked), H2 (renderer crash), H3 (missing note). |
+| W09 | Sync still runs only in the main window. Each sync result, and a conflict discard, is passed on to the window of the note it concerns: its editor advances its sync state and reloads the note, so changes from other devices and conflicts reach it the same way they reach the main editor. A failed reload keeps the note the window already shows. | Unit tests for picking and rebuilding the per-note sync update; Electron scenarios I1 (edit on another device appears after sync) and I2 (conflicting edit: same result as the main window, local edit kept as a conflict in the sync queue). H1, H2, I1 and I2 fail without this change. |
+
+## Risk and rollback
+
+The change is desktop-only and adds no data, API or migration change. Main-process IPC that used to accept only the main window now also accepts note windows for the session token, image upload, AI direct requests and renderer error reports; account, instance, data reset and window commands still require the main window. A synchronous IPC handler (`desktop:rich-text-heading-shortcut`) previously returned nothing for other windows, which froze them; it now always answers, and each note window has its own heading-shortcut guard. Sync forwarding goes from the main window through the main process to one note window; only the main window may send it and only a note window may report that it is ready. A sync result that arrives while a note window is still loading is not replayed; the window reads the note from storage when it loads. Electron scenarios were run against the local dev server on macOS only; Windows and Linux are covered by CI unit tests and builds, not by interactive runs. Rollback is a revert; no stored state refers to note windows.
diff --git a/docs/changes/2026-10-29-desktop-note-window.zh-CN.md b/docs/changes/2026-10-29-desktop-note-window.zh-CN.md
new file mode 100644
index 00000000..cd4f3e8b
--- /dev/null
+++ b/docs/changes/2026-10-29-desktop-note-window.zh-CN.md
@@ -0,0 +1,25 @@
+# 在新窗口打开笔记(桌面端)
+
+[English](2026-10-29-desktop-note-window.md)
+
+## 问题与结果
+
+实现 [Issue #67](https://github.com/tianma-if/edgeever/issues/67)。此前桌面端只能在主窗口中逐条编辑笔记。现在可以通过笔记的“更多”菜单,或“文件 → 在新窗口打开笔记”(`Cmd/Ctrl+Shift+O`)把笔记移到独立窗口,与主窗口并排或放到另一块屏幕上。
+
+## 行为
+
+| ID | 行为 | 验收 |
+| --- | --- | --- |
+| W01 | 一条笔记最多只在一个窗口中显示。移到新窗口前先保存主编辑器中的待保存修改;之后主窗口显示带“显示窗口”按钮的占位界面,而不是第二个编辑器。 | Electron 场景 A1:在主窗口输入的文字出现在新窗口中,主窗口不再有该笔记的编辑器。 |
+| W02 | 通过菜单项、快捷键、笔记列表、快速切换、插件链接或占位界面再次打开同一笔记时,聚焦已有窗口,不会再创建一个。 | 单元测试“opens one window per note”;Electron 场景 A2。 |
+| W03 | 关闭笔记窗口时先保存待保存修改,随后笔记以已保存内容重新在主窗口中打开。 | 单元测试“closing asks the renderer first”;Electron 场景 B1、B2。 |
+| W04 | 移动前保存失败(例如本地存储 15 秒内无响应)时,笔记连同内容留在主窗口并给出提示。关闭窗口时保存失败,窗口保持打开并提示;再次关闭即关闭窗口,本地草稿会在主窗口中恢复。渲染进程无响应时,5 秒后的第二次关闭会直接关闭窗口。 | 失败保存与渲染进程卡死的单元测试;Electron 场景 D1(暂停存储)与 E1。 |
+| W05 | 退出应用、切换账号或实例、清除会话或清除本地数据时,先请求每个笔记窗口保存,最多 5 秒后关闭。重启后不恢复笔记窗口。 | 单元测试“closeAll”;Electron 场景 F1(退出、重新启动、内容保留)。 |
+| W06 | 笔记窗口只包含编辑器:指向其他笔记的链接在主窗口中打开,删除笔记会关闭其窗口,多条笔记可以各自拥有窗口。笔记窗口不能再打开窗口、切换账号、修改实例或启动插件。 | Electron 场景 A3、C1、C2、G1。 |
+| W07 | 只有已存入存储的笔记可以移动;尚未创建完成的笔记显示“同步后在新窗口打开”。图表、表格、回收站和 Web 端不提供该操作。 | 手动检查菜单状态。 |
+| W08 | 只有新窗口已显示笔记时,移动才算完成。若窗口加载失败、无法显示该笔记、崩溃或 30 秒内未回报,就会被销毁,主窗口重新在编辑器中显示笔记并说明原因(笔记不存在或不支持时提示“无法在独立窗口中显示”,其他情况提示“无法打开”)。移动完成后笔记窗口崩溃,同样会把笔记交回主窗口并给出提示。失败原因写入桌面端诊断日志。 | 就绪、加载失败、超时、加载中关闭、移动后崩溃及替换正在关闭的窗口的单元测试;Electron 场景 H1(阻止加载)、H2(渲染进程崩溃)、H3(笔记不存在)。 |
+| W09 | 同步仍只在主窗口中运行。每次同步结果以及放弃冲突的操作都会转发给相关笔记所在的窗口:其编辑器更新同步状态并重新读取笔记,因此其他设备的修改和冲突会以与主编辑器相同的方式到达。重新读取失败时,窗口保留当前显示的笔记。 | 选取与重建单条笔记同步更新的单元测试;Electron 场景 I1(其他设备的修改在同步后出现)和 I2(冲突修改:结果与主窗口相同,本地修改作为冲突保留在同步队列中)。没有本次改动时 H1、H2、I1、I2 均失败。 |
+
+## 风险与回滚
+
+本次改动仅涉及桌面端,没有数据、API 或迁移变化。原先只接受主窗口的主进程 IPC 中,会话令牌、图片上传、AI 直连请求和渲染错误上报现在也接受笔记窗口;账号、实例、数据重置和窗口命令仍只接受主窗口。同步 IPC 处理函数 `desktop:rich-text-heading-shortcut` 以前对其他窗口不返回值,会让窗口卡死;现在总会返回,且每个笔记窗口有独立的标题快捷键守卫。同步转发经由主进程从主窗口发送到单个笔记窗口;只有主窗口可以发送,只有笔记窗口可以回报就绪。笔记窗口仍在加载时到达的同步结果不会重放,窗口加载时会从存储读取笔记。Electron 场景仅在 macOS 上对本地开发服务运行;Windows 与 Linux 由 CI 单元测试和构建覆盖,未做交互验证。回滚方式为 revert;没有持久化状态引用笔记窗口。
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index 98eda27d..1d32708b 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -2610,6 +2610,16 @@ export const enUS = {
noteIdCopyFailed: "Could not copy the note ID.",
exportMarkdown: "Export Markdown",
duplicate: "Duplicate note",
+ openInNewWindow: "Open in new window",
+ openInNewWindowAfterSync: "Open in new window after sync",
+ openInNewWindowSaveFailed: "The note couldn't be saved, so it stays in this window. Resolve the save problem and try again.",
+ openInNewWindowFailed: "Couldn't open the note in a new window. It stays in this window.",
+ noteInSeparateWindow: "This note is open in a separate window. Edit it there; it returns here when that window closes.",
+ showNoteWindow: "Show window",
+ noteWindowUnavailable: "This note can't be shown in a separate window. It may have been deleted, or it is a note type that opens only in the main window.",
+ closeNoteWindow: "Close window",
+ noteWindowCloseSaveFailed: "Your latest edits couldn't be saved. Fix the problem, or close the window again to close it anyway; the edits stay on this device and are offered again when you open the note.",
+ noteWindowStopped: "The note's window closed unexpectedly, so the note is back in this window. Check its latest changes; edits that were not saved yet are offered again from this device's draft.",
duplicateTitle: "{{title}} (copy)",
duplicateFailedTitle: "Couldn't duplicate this note",
duplicateFailed: "The copy was not created. Try again in a moment.",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 604e0af8..dd566b75 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -2599,6 +2599,16 @@ export const ja = {
noteIdCopyFailed: "ノート ID をコピーできませんでした。",
exportMarkdown: "Markdown をエクスポート",
duplicate: "ノートを複製",
+ openInNewWindow: "新しいウィンドウで開く",
+ openInNewWindowAfterSync: "同期後に新しいウィンドウで開けます",
+ openInNewWindowSaveFailed: "ノートを保存できなかったため、このウィンドウに残ります。保存の問題を解決してからもう一度お試しください。",
+ openInNewWindowFailed: "ノートを新しいウィンドウで開けませんでした。このウィンドウに残ります。",
+ noteInSeparateWindow: "このノートは別のウィンドウで開いています。そちらで編集してください。ウィンドウを閉じるとここに戻ります。",
+ showNoteWindow: "ウィンドウを表示",
+ noteWindowUnavailable: "このノートは別のウィンドウで表示できません。削除されたか、メインウィンドウでのみ開ける種類のノートです。",
+ closeNoteWindow: "ウィンドウを閉じる",
+ noteWindowCloseSaveFailed: "最新の編集を保存できませんでした。問題を解決するか、もう一度閉じると強制的に閉じます。編集はこのデバイスに残り、次にノートを開いたときに復元を提案します。",
+ noteWindowStopped: "ノートのウィンドウが予期せず閉じたため、ノートはこのウィンドウに戻りました。最新の変更を確認してください。未保存の編集はこのデバイスの下書きから再度表示されます。",
duplicateTitle: "{{title}}(コピー)",
duplicateFailedTitle: "このノートを複製できませんでした",
duplicateFailed: "コピーは作成されませんでした。しばらくしてから再試行してください。",
diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.ts
index 87f5d0dc..586f5eb1 100644
--- a/packages/shared/src/i18n/pl.ts
+++ b/packages/shared/src/i18n/pl.ts
@@ -2599,6 +2599,16 @@ export const pl = {
noteIdCopyFailed: "Nie udało się skopiować ID notatki.",
exportMarkdown: "Eksportuj Markdown",
duplicate: "Duplikuj notatkę",
+ openInNewWindow: "Otwórz w nowym oknie",
+ openInNewWindowAfterSync: "Otwórz w nowym oknie po synchronizacji",
+ openInNewWindowSaveFailed: "Nie udało się zapisać notatki, więc zostaje w tym oknie. Rozwiąż problem z zapisem i spróbuj ponownie.",
+ openInNewWindowFailed: "Nie udało się otworzyć notatki w nowym oknie. Zostaje w tym oknie.",
+ noteInSeparateWindow: "Ta notatka jest otwarta w osobnym oknie. Edytuj ją tam; wróci tutaj po zamknięciu tamtego okna.",
+ showNoteWindow: "Pokaż okno",
+ noteWindowUnavailable: "Tej notatki nie można pokazać w osobnym oknie. Mogła zostać usunięta albo jest typem notatki, który otwiera się tylko w oknie głównym.",
+ closeNoteWindow: "Zamknij okno",
+ noteWindowCloseSaveFailed: "Nie udało się zapisać ostatnich zmian. Rozwiąż problem albo zamknij okno ponownie, aby je mimo to zamknąć; zmiany zostaną na tym urządzeniu i zostaną zaproponowane przy ponownym otwarciu notatki.",
+ noteWindowStopped: "Okno notatki nieoczekiwanie się zamknęło, więc notatka wróciła do tego okna. Sprawdź ostatnie zmiany; niezapisane edycje zostaną ponownie zaproponowane z wersji roboczej na tym urządzeniu.",
duplicateTitle: "{{title}} (kopia)",
duplicateFailedTitle: "Nie udało się zduplikować notatki",
duplicateFailed: "Kopia nie została utworzona. Spróbuj ponownie za chwilę.",
diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.ts
index 15ef96f8..3f1f4d62 100644
--- a/packages/shared/src/i18n/ru.ts
+++ b/packages/shared/src/i18n/ru.ts
@@ -2610,6 +2610,16 @@ export const ru = {
noteIdCopyFailed: "Не удалось скопировать ID заметки.",
exportMarkdown: "Экспорт Markdown",
duplicate: "Дублировать заметку",
+ openInNewWindow: "Открыть в новом окне",
+ openInNewWindowAfterSync: "Открыть в новом окне после синхронизации",
+ openInNewWindowSaveFailed: "Не удалось сохранить заметку, поэтому она остаётся в этом окне. Устраните проблему с сохранением и повторите попытку.",
+ openInNewWindowFailed: "Не удалось открыть заметку в новом окне. Она остаётся в этом окне.",
+ noteInSeparateWindow: "Эта заметка открыта в отдельном окне. Редактируйте её там; после закрытия того окна она вернётся сюда.",
+ showNoteWindow: "Показать окно",
+ noteWindowUnavailable: "Эту заметку нельзя показать в отдельном окне. Возможно, она удалена или относится к типу, который открывается только в главном окне.",
+ closeNoteWindow: "Закрыть окно",
+ noteWindowCloseSaveFailed: "Не удалось сохранить последние изменения. Устраните проблему или закройте окно ещё раз, чтобы закрыть его принудительно; изменения останутся на этом устройстве и будут предложены при следующем открытии заметки.",
+ noteWindowStopped: "Окно заметки неожиданно закрылось, и заметка вернулась в это окно. Проверьте последние изменения; несохранённые правки будут снова предложены из черновика на этом устройстве.",
duplicateTitle: "{{title}} (копия)",
duplicateFailedTitle: "Не удалось дублировать заметку",
duplicateFailed: "Копия не создана. Повторите чуть позже.",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 4bce96c7..f1a523b9 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -2610,6 +2610,16 @@ export const zhCN = {
noteIdCopyFailed: "复制笔记 ID 失败。",
exportMarkdown: "导出 Markdown",
duplicate: "创建副本",
+ openInNewWindow: "在新窗口打开",
+ openInNewWindowAfterSync: "同步后可在新窗口打开",
+ openInNewWindowSaveFailed: "笔记未能保存,因此仍留在当前窗口。请处理保存问题后重试。",
+ openInNewWindowFailed: "无法在新窗口打开笔记,笔记仍留在当前窗口。",
+ noteInSeparateWindow: "这条笔记已在独立窗口中打开,请在该窗口中编辑;关闭该窗口后会回到这里。",
+ showNoteWindow: "显示窗口",
+ noteWindowUnavailable: "这条笔记无法在独立窗口中显示。它可能已被删除,或属于只能在主窗口打开的笔记类型。",
+ closeNoteWindow: "关闭窗口",
+ noteWindowCloseSaveFailed: "最新修改未能保存。请处理问题,或再次关闭窗口以强制关闭;修改会保留在本设备上,再次打开笔记时会提示恢复。",
+ noteWindowStopped: "笔记窗口意外关闭,笔记已回到当前窗口。请检查最近的修改;尚未保存的内容会从本设备的草稿中重新提供。",
duplicateTitle: "{{title}}(副本)",
duplicateFailedTitle: "没能创建这条笔记的副本",
duplicateFailed: "副本未创建,请稍后重试。",