Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Open a folder linked in chat in Finder/Explorer on the desktop app

AdityaUmale1aaab227b4a0
diff --git a/electron/bridge-contract.json b/electron/bridge-contract.json
index 65f532f2f6..0b8899bfad 100644
--- a/electron/bridge-contract.json
+++ b/electron/bridge-contract.json
@@ -175,6 +175,7 @@
"openAtLogin.set",
"openAtLogin.state",
"openExternal",
+ "openFolder",
"openHtmlInBrowser",
"openInstallTerminal",
"openLogsFolder",
diff --git a/electron/main.mjs b/electron/main.mjs
index 3430f8c505..f1e69265cf 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -42,7 +42,7 @@ import { missingPermissions } from "./lent-screen-failures.mjs";
import { createScreenControl } from "./screen-control.mjs"; import { createAskPrompt } from "./ask-prompt.mjs";
let startupScreen = null;
let desktopTray = null;
-import { collisionFreeDownloadPath, defaultSaveName, openHtmlCopy, openLogsFolder, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
+import { collisionFreeDownloadPath, defaultSaveName, openFolder, openHtmlCopy, openLogsFolder, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
import { desktopViewerPermissionAllowed } from "./desktop-viewer-permissions.mjs";
import { appPermissionHandlers, externalLinkUrl } from "./app-permissions.mjs";
import { appFrameNavigationAllowed } from "./app-frame-guard.mjs";
@@ -2280,6 +2280,10 @@ ipcMain.handle("desktop:reveal-file", localOnly("desktop:reveal-file", async (_e
if (desktopRemoteAccess) throw new Error("That file is on the computer this app is connected to");
return revealInFolder(rawPath, { reveal: (target) => shell.showItemInFolder(target) });
}));
+ipcMain.handle("desktop:open-folder", localOnly("desktop:open-folder", async (_event, rawPath) => {
+ if (desktopRemoteAccess) throw new Error("That folder is on the computer this app is connected to");
+ return openFolder(rawPath, { open: (target) => shell.openPath(target) });
+}));
ipcMain.handle("desktop:open-html", localOnly("desktop:open-html", (_event, source, name) => openHtmlCopy(source, name, { dir: path.join(app.getPath("userData"), "open-html"), t: nativeT, open: (file) => shell.openPath(file) })));
ipcMain.handle("desktop:open-logs", localOrHome("desktop:open-logs", () => openLogsFolder(LOG_DIR, { open: (folder) => shell.openPath(folder) })));
ipcMain.handle("desktop:skin", (event, skin) => {
diff --git a/electron/preload.cjs b/electron/preload.cjs
index da01c30ac1..5df4c454ce 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -409,6 +409,7 @@ const bridge = {
exportDiagnostics: () => ipcRenderer.invoke("desktop:export-diagnostics"),
saveFile: (filePath) => invokeWithPlainError("desktop:save-file", filePath),
revealInFolder: (filePath) => ipcRenderer.invoke("desktop:reveal-file", filePath),
+ openFolder: (folderPath) => ipcRenderer.invoke("desktop:open-folder", folderPath),
openHtmlInBrowser: (source, name) => invokeWithPlainError("desktop:open-html", source, name),
// This app's own logs folder (server.log, desktop-crashes.log, updater.log); the page names no path.
openLogsFolder: () => ipcRenderer.invoke("desktop:open-logs"),
diff --git a/electron/save-file.mjs b/electron/save-file.mjs
index 17522c98a6..9d4f233838 100644
--- a/electron/save-file.mjs
+++ b/electron/save-file.mjs
@@ -114,13 +114,18 @@ export async function withSavableFile(
// Untrusted path: nothing here opens, reads or runs it. Network shares are refused, since merely looking one up can hand
// this computer's sign-in to whoever runs that server.
-export async function revealInFolder(rawPath, { reveal, fsp = fs.promises, pathApi = path }) {
+function localTarget(rawPath, pathApi) {
const local = (value) => !/^[\\/]{2}/.test(value) && pathApi.isAbsolute(value);
if (typeof rawPath !== "string" || rawPath.includes("\0") || /^[a-z][a-z\d+.-]+:/i.test(rawPath) || !local(rawPath)) {
- return "invalid";
+ return null;
}
const target = pathApi.normalize(rawPath);
- if (!local(target)) return "invalid";
+ return local(target) ? target : null;
+}
+
+export async function revealInFolder(rawPath, { reveal, fsp = fs.promises, pathApi = path }) {
+ const target = localTarget(rawPath, pathApi);
+ if (!target) return "invalid";
let stats;
try {
stats = await fsp.stat(target);
@@ -132,6 +137,30 @@ export async function revealInFolder(rawPath, { reveal, fsp = fs.promises, pathA
return "shown";
}
+// A folder a chat links to, opened in Explorer or Finder. Same untrusted-path rules as revealInFolder, and only a plain
+// folder is ever handed to `open` (shell.openPath), since opening anything else runs it: never a file, and never a
+// folder that is really a program, as a Mac app (Name.app, or any folder with Contents/Info.plist) or a link to one is.
+// Links are resolved first and any folder name with an extension is left alone. Anything refused answers "not-folder"
+// so the page keeps today's save-a-copy. `open` answers "" or why it failed.
+export async function openFolder(rawPath, { open, fsp = fs.promises, pathApi = path }) {
+ const target = localTarget(rawPath, pathApi);
+ if (!target) return "invalid";
+ let real;
+ let stats;
+ try {
+ real = await fsp.realpath(target);
+ stats = await fsp.stat(real);
+ } catch {
+ return "missing";
+ }
+ if (!stats.isDirectory() || /.\.[^.]+$/.test(pathApi.basename(real))) return "not-folder";
+ const bundle = await fsp.stat(pathApi.join(real, "Contents", "Info.plist")).then(() => true, () => false);
+ if (bundle) return "not-folder";
+ let error = "";
+ try { error = await open(real); } catch (failure) { error = failure?.message ?? String(failure); }
+ return error ? "failed" : "opened";
+}
+
/** This app's own logs folder in Explorer or Finder, made first if nothing has been logged yet. The folder is main's
* own (app.getPath("logs")), never one a page names; `open` is shell.openPath, which answers "" or why it failed. */
export async function openLogsFolder(folder, { open, fsp = fs.promises }) {
diff --git a/electron/save-file.node-test.mjs b/electron/save-file.node-test.mjs
index 2ae1fb3e90..862c774243 100644
--- a/electron/save-file.node-test.mjs
+++ b/electron/save-file.node-test.mjs
@@ -6,7 +6,7 @@ import path from "node:path";
import { after, before, describe, it } from "node:test";
import { pathToFileURL } from "node:url";
-import { collisionFreeDownloadPath, defaultSaveName, htmlCopyName, openHtmlCopy, openLogsFolder, resolveSavablePath, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
+import { collisionFreeDownloadPath, defaultSaveName, htmlCopyName, openFolder, openHtmlCopy, openLogsFolder, resolveSavablePath, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
// Creating a symlink on Windows needs elevation or developer mode.
const canSymlink = (() => {
@@ -267,6 +267,70 @@ describe("Show in folder for a file outside the workspace", () => {
});
});
+describe("openFolder for a folder a chat links to", () => {
+ const shell = (answer = "") => {
+ const opened = [];
+ return { opened, open: async (target) => { opened.push(target); return answer; } };
+ };
+
+ it("opens an existing folder by its normalised absolute path", async () => {
+ const { opened, open } = shell();
+ assert.equal(await openFolder(path.join(botHome, "..", path.basename(botHome)), { open }), "opened");
+ assert.deepEqual(opened, [fs.realpathSync(botHome)]);
+ });
+
+ it("never opens a file (that would run it): the page keeps its save-a-copy", async () => {
+ const { opened, open } = shell();
+ assert.equal(await openFolder(path.join(home, "secret.txt"), { open }), "not-folder");
+ assert.deepEqual(opened, []);
+ });
+
+ it("never opens a Mac app or other program folder, or a link to one", async () => {
+ const { opened, open } = shell();
+ const app = path.join(home, "Calculator.app");
+ const bundle = path.join(home, "NoExtension");
+ fs.mkdirSync(path.join(app, "Contents"), { recursive: true });
+ fs.mkdirSync(path.join(bundle, "Contents"), { recursive: true });
+ fs.writeFileSync(path.join(bundle, "Contents", "Info.plist"), "");
+ const link = path.join(home, "innocent-looking");
+ fs.symlinkSync(app, link, process.platform === "win32" ? "junction" : "dir");
+ for (const target of [app, bundle, link]) assert.equal(await openFolder(target, { open }), "not-folder", target);
+ assert.deepEqual(opened, []);
+ });
+
+ it("says a missing folder is missing, and reports a failed open", async () => {
+ const { opened, open } = shell();
+ assert.equal(await openFolder(path.join(home, "gone"), { open }), "missing");
+ assert.deepEqual(opened, []);
+ assert.equal(await openFolder(botHome, { open: shell("no file manager").open }), "failed");
+ });
+
+ it("refuses relative paths, URLs and network shares without touching the disk", async () => {
+ const { opened, open } = shell();
+ const fsp = { stat: () => assert.fail("an invalid path must not be looked up") };
+ for (const rawPath of ["notes", "../notes", "https://example.com/x", "//server/share/x", "", "\0", null, 42]) {
+ assert.equal(await openFolder(rawPath, { open, fsp }), "invalid", String(rawPath));
+ }
+ for (const rawPath of ["\\\\server\\share\\x", "C:relative", "file:///C:/x"]) {
+ assert.equal(await openFolder(rawPath, { open, fsp, pathApi: path.win32 }), "invalid", rawPath);
+ }
+ assert.deepEqual(opened, []);
+ });
+
+ it("opens a Windows folder path", async () => {
+ const { opened, open } = shell();
+ const fsp = {
+ realpath: async (target) => target,
+ stat: async (target) => {
+ if (target.endsWith("Info.plist")) throw Object.assign(new Error("gone"), { code: "ENOENT" });
+ return { isFile: () => false, isDirectory: () => true };
+ },
+ };
+ assert.equal(await openFolder("C:\\Users\\Maus\\Reports\\..\\Reports", { open, fsp, pathApi: path.win32 }), "opened");
+ assert.deepEqual(opened, ["C:\\Users\\Maus\\Reports"]);
+ });
+});
+
describe("openLogsFolder", () => {
it("opens exactly main's own logs folder, making it first, and says where it is when the system cannot open it", async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "omb-logs-folder-"));
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index dd5c0fa28d..216f100f2c 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -29,7 +29,7 @@ import { CodeBlock, CodePlate, codeHash } from "./CodeBlock";
export { CodeBlock, HIGHLIGHT_CACHE_MAX, HIGHLIGHT_CACHE_MAX_CHARS, HIGHLIGHT_MAX_CHARS, type CodeBlockProps } from "./CodeBlock";
import { FilePreviewButton } from "./FilePreviewButton";
import { SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";
-import { useRevealOriginalMenu } from "./RevealOriginalMenu";
+import { openLinkedFolder, useRevealOriginalMenu } from "./RevealOriginalMenu";
const mermaidCache = new Map<string, string>();
const MERMAID_CACHE_MAX = 50;
@@ -345,7 +345,7 @@ function LocalFileLink({ filePath, name, source, children, message }: { filePath
: <FilePreviewButton path={filePath} name={name ?? fileName(filePath)} message={message} />}
<button
type="button"
- onClick={preview.html ? preview.show : () => void save.save()}
+ onClick={preview.html ? preview.show : () => void openLinkedFolder(filePath).then((opened) => { if (!opened) return save.save(); })}
disabled={!preview.html && save.state === "saving"}
title={preview.html ? t("html.preview", { name: name ?? fileName(filePath) }) : t("chat.file.saveCopy")}
className="inline-flex items-center gap-1 break-words text-start text-accent underline decoration-accent/40 hover:decoration-accent disabled:cursor-wait"
diff --git a/src/components/RevealOriginalMenu.test.ts b/src/components/RevealOriginalMenu.test.ts
index 8fddf616f2..0eaf853bfc 100644
--- a/src/components/RevealOriginalMenu.test.ts
+++ b/src/components/RevealOriginalMenu.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
-import { canRevealOriginal, revealOriginal, revealOriginalLabel } from "./RevealOriginalMenu";
+import { canRevealOriginal, openLinkedFolder, revealOriginal, revealOriginalLabel } from "./RevealOriginalMenu";
afterEach(() => vi.unstubAllGlobals());
@@ -42,3 +42,34 @@ describe("Show in Finder for the original of a bot's attachment", () => {
expect(reveal).toHaveBeenCalledTimes(4);
});
});
+
+describe("a folder link in chat opens the folder in the desktop app", () => {
+ it("opens a local folder and says so; a file or a failure keeps the save-a-copy", async () => {
+ const open = vi.fn(async (_path: string) => "opened" as "opened" | "not-folder" | "missing" | "invalid" | "failed");
+ expect(await openLinkedFolder("/Users/me/Reports", open)).toBe(true);
+ expect(open).toHaveBeenCalledWith("/Users/me/Reports");
+ for (const answer of ["not-folder", "missing", "invalid", "failed"] as const) {
+ open.mockResolvedValueOnce(answer);
+ expect(await openLinkedFolder("/Users/me/Reports/q3.pdf", open)).toBe(false);
+ }
+ open.mockRejectedValueOnce(new Error("ipc"));
+ expect(await openLinkedFolder("/Users/me/Reports", open)).toBe(false);
+ });
+
+ it("never asks for a relative path or a network share", async () => {
+ const open = vi.fn(async () => "opened" as const);
+ expect(await openLinkedFolder("Reports", open)).toBe(false);
+ expect(await openLinkedFolder("//server/share/Reports", open)).toBe(false);
+ expect(open).not.toHaveBeenCalled();
+ });
+
+ it("does nothing on the web, a phone or a window connected to another computer", async () => {
+ const open = vi.fn(async () => "opened" as const);
+ expect(await openLinkedFolder("/Users/me/Reports")).toBe(false);
+ vi.stubGlobal("window", { ogb: { openFolder: open, remoteClient: { active: true } } });
+ expect(await openLinkedFolder("/Users/me/Reports")).toBe(false);
+ expect(open).not.toHaveBeenCalled();
+ vi.stubGlobal("window", { ogb: { openFolder: open } });
+ expect(await openLinkedFolder("C:\\Users\\me\\Reports")).toBe(true);
+ });
+});
diff --git a/src/components/RevealOriginalMenu.tsx b/src/components/RevealOriginalMenu.tsx
index 4266a8f83a..f1aa009d29 100644
--- a/src/components/RevealOriginalMenu.tsx
+++ b/src/components/RevealOriginalMenu.tsx
@@ -18,6 +18,24 @@ function revealBridge(): Reveal | undefined {
return ogb?.remoteClient?.active ? undefined : ogb?.revealInFolder;
}
+type OpenFolder = NonNullable<NonNullable<Window["ogb"]>["openFolder"]>;
+
+/** Desktop app on the computer that holds the path: a folder a chat links to opens in Finder or Explorer. True only when
+ * it opened; a file, a missing path, a phone, the web or a connected window answer false and keep their own handling. */
+export async function openLinkedFolder(folderPath: string, open: OpenFolder | undefined = openFolderBridge()): Promise<boolean> {
+ if (!open || !REVEALABLE_PATH.test(folderPath)) return false;
+ try {
+ return await open(folderPath) === "opened";
+ } catch {
+ return false;
+ }
+}
+
+function openFolderBridge(): OpenFolder | undefined {
+ const ogb = typeof window === "undefined" ? undefined : window.ogb;
+ return ogb?.remoteClient?.active ? undefined : ogb?.openFolder;
+}
+
export function canRevealOriginal(source: string | undefined, reveal: Reveal | undefined = revealBridge()): source is string {
return Boolean(reveal) && typeof source === "string" && REVEALABLE_PATH.test(source);
}
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 2a64afa7f5..26f05475ae 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -441,6 +441,8 @@ const __APP_VERSION__: string;
/** Points this computer's file manager at a file a bot linked outside
* its workspace, without opening or reading it. Local app only. */
revealInFolder?(filePath: string): Promise<"shown" | "missing" | "invalid">;
+ /** Opens a folder (never a file) in Finder or Explorer; "not-folder" means keep the page's own handling. */
+ openFolder?(folderPath: string): Promise<"opened" | "not-folder" | "missing" | "invalid" | "failed">;
/** Opens this app's logs folder in Explorer or Finder and says where it is. */
openLogsFolder?(): Promise<{ folder: string; opened: boolean; error?: string }>;
/** This app's own login item, which opens the window. `available`: false in a build that cannot add one. */