Skip to content

Build your personal knowledge base with Trilium Notes

fix(link): open a folder link with the user's file manager (closes #9977)

Elian Doran41e7f21b1649
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index cd9cdb5e8c..8420ff0b8d 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -515,8 +515,9 @@ export function goToLinkExt(evt: MouseEvent | JQuery.ClickEvent | JQuery.MouseDo
};
if (hrefLink.toLowerCase().startsWith("file:")) {
- // shell.openExternal mishandles Unicode file:// URLs on Windows;
- // convert to a filesystem path and use shell.openPath instead.
+ // The main process resolves the URL to a path and picks the dispatch
+ // that works per platform; shell.openExternal alone mishandles Unicode
+ // file:// URLs on Windows.
window.electronApi.shell.openFileUrl(hrefLink).then((err: string) => {
if (err) reportLinkError(new Error(err));
}).catch(reportLinkError);
diff --git a/apps/desktop/src/services/shell.ts b/apps/desktop/src/services/shell.ts
index c2e8ef2965..b68d64273f 100644
--- a/apps/desktop/src/services/shell.ts
+++ b/apps/desktop/src/services/shell.ts
@@ -275,6 +275,13 @@ export function setupShellHandlers() {
electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {
try {
const filePath = validateOpenFileUrl(fileUrl);
+
+ if (shouldOpenViaProtocolHandler(filePath)) {
+ return electron.shell.openExternal(url.pathToFileURL(filePath).href)
+ .then(() => "")
+ .catch((e) => coreUtils.safeExtractMessageAndStackFromError(e));
+ }
+
return electron.shell.openPath(filePath);
} catch (e) {
getLog().error(`open-file-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);
@@ -349,6 +356,32 @@ export function setupShellHandlers() {
});
}
+/**
+ * True when Windows must dispatch a directory through the `file:` protocol handler rather
+ * than `shell.openPath`.
+ *
+ * `shell.openPath` sends a directory to Chromium's `OpenFolderViaShell`, which hardcodes the
+ * `explore` verb — Explorer's own. A third-party file manager registers the default verb
+ * instead, so `explore` never reaches it and the folder always opens in Explorer.
+ * `shell.openExternal` invokes `open` on the URL, letting the shell resolve the handler the
+ * user actually configured. Files already take the default verb, so they keep `openPath`.
+ *
+ * Non-ASCII paths keep `openPath` too: `openExternal` percent-encodes the URL as UTF-8 and
+ * Windows decodes those escapes with the ANSI codepage, so the path arrives mangled. Such a
+ * directory opens in Explorer, which is what it did before this branch existed.
+ */
+function shouldOpenViaProtocolHandler(filePath: string): boolean {
+ if (process.platform !== "win32" || /[\u0080-\uffff]/.test(filePath)) {
+ return false;
+ }
+
+ try {
+ return fs.statSync(filePath).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
/**
* The directory backups currently go to, which the user may have moved outside the data directory.
* Read from the backup service rather than accepted from the renderer, so it stays the app's own
diff --git a/apps/desktop/src/services/shell_handlers.spec.ts b/apps/desktop/src/services/shell_handlers.spec.ts
index efcdc4b595..90caed809b 100644
--- a/apps/desktop/src/services/shell_handlers.spec.ts
+++ b/apps/desktop/src/services/shell_handlers.spec.ts
@@ -1,5 +1,6 @@
import fs from "fs";
import path from "path";
+import { pathToFileURL } from "url";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
type Handler = (event: unknown, ...args: unknown[]) => unknown;
@@ -7,7 +8,7 @@ type Handler = (event: unknown, ...args: unknown[]) => unknown;
const h = vi.hoisted(() => ({
on: new Map<string, Handler>(),
handle: new Map<string, Handler>(),
- openExternal: vi.fn(),
+ openExternal: vi.fn(() => Promise.resolve()),
openPath: vi.fn(() => Promise.resolve("")),
showItemInFolder: vi.fn(),
execFile: vi.fn()
@@ -41,6 +42,8 @@ const DATA_DIR = dataDirs.TRILIUM_DATA_DIR;
const TMP_DIR = dataDirs.TMP_DIR;
let tmpFile: string;
let dataFile: string;
+let tmpDir: string;
+let unicodeDir: string;
function setPlatform(platform: NodeJS.Platform) {
Object.defineProperty(process, "platform", { value: platform, configurable: true });
@@ -54,12 +57,18 @@ beforeAll(() => {
dataFile = path.join(DATA_DIR, "shell-handlers-data.txt");
fs.writeFileSync(tmpFile, "");
fs.writeFileSync(dataFile, "");
+ tmpDir = path.join(TMP_DIR, "shell-handlers-test-dir");
+ unicodeDir = path.join(TMP_DIR, "shell-handlers-资料");
+ fs.mkdirSync(tmpDir, { recursive: true });
+ fs.mkdirSync(unicodeDir, { recursive: true });
setupShellHandlers();
});
afterAll(() => {
fs.rmSync(tmpFile, { force: true });
fs.rmSync(dataFile, { force: true });
+ fs.rmSync(tmpDir, { force: true, recursive: true });
+ fs.rmSync(unicodeDir, { force: true, recursive: true });
setPlatform(realPlatform);
});
@@ -130,6 +139,36 @@ describe("setupShellHandlers", () => {
expect(result).toBeTruthy();
expect(h.openPath).not.toHaveBeenCalled();
});
+
+ it("opens a directory through the file: protocol handler on Windows", async () => {
+ setPlatform("win32");
+ const result = await fireHandle("open-file-url", pathToFileURL(tmpDir).href);
+ expect(h.openExternal).toHaveBeenCalledWith(pathToFileURL(tmpDir).href);
+ expect(h.openPath).not.toHaveBeenCalled();
+ expect(result).toBe("");
+ });
+
+ it("reports a failure of the protocol handler back to the renderer", async () => {
+ setPlatform("win32");
+ h.openExternal.mockRejectedValueOnce(new Error("no handler"));
+ const result = await fireHandle("open-file-url", pathToFileURL(tmpDir).href);
+ expect(result).toContain("no handler");
+ });
+
+ it("keeps openPath for a file, and for a directory whose name is not ASCII", () => {
+ setPlatform("win32");
+ fireHandle("open-file-url", pathToFileURL(tmpFile).href);
+ fireHandle("open-file-url", pathToFileURL(unicodeDir).href);
+ expect(h.openPath).toHaveBeenCalledTimes(2);
+ expect(h.openExternal).not.toHaveBeenCalled();
+ });
+
+ it("keeps openPath for a directory outside Windows", () => {
+ setPlatform("linux");
+ fireHandle("open-file-url", pathToFileURL(tmpDir).href);
+ expect(h.openPath).toHaveBeenCalledWith(path.resolve(tmpDir));
+ expect(h.openExternal).not.toHaveBeenCalled();
+ });
});
describe("download-url", () => {
diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.ts
index 8ae8864f7d..2238437104 100644
--- a/packages/commons/src/lib/electron_api_interface.ts
+++ b/packages/commons/src/lib/electron_api_interface.ts
@@ -291,9 +291,11 @@ export interface ElectronShellApi {
/**
* Opens a `file://` URL with its default OS handler. Exists as a separate
- * channel from {@link openExternal} because Electron's `shell.openExternal`
- * mishandles Unicode characters in `file:` URLs on Windows; converting to
- * a filesystem path and calling `shell.openPath` works correctly.
+ * channel from {@link openExternal} because neither Electron API opens every
+ * target correctly on Windows: `shell.openExternal` mishandles Unicode
+ * characters in `file:` URLs, while `shell.openPath` opens a directory with
+ * the Explorer-specific `explore` verb, bypassing the user's file manager.
+ * The main process picks between them per target.
*
* **Security:** the URL must use the `file:` scheme and must have an
* empty hostname. UNC paths (`file://attacker.example/share/x`) are