Skip to content

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

Open a linked folder only after the message's file route authorizes it

milind-sonie30fd52ff1f0
diff --git a/electron/main.mjs b/electron/main.mjs
index f1e69265cf..2419facd35 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -2276,14 +2276,8 @@ ipcMain.handle("desktop:save-file", localOnly("desktop:save-file", async (event,
return choice.filePath;
});
}));
-ipcMain.handle("desktop:reveal-file", localOnly("desktop:reveal-file", async (_event, rawPath) => {
- 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:reveal-file", localOnly("desktop:reveal-file", async (_event, rawPath) => { 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/save-file.node-test.mjs b/electron/save-file.node-test.mjs
index 4d8be8fa48..2e941e35fb 100644
--- a/electron/save-file.node-test.mjs
+++ b/electron/save-file.node-test.mjs
@@ -276,7 +276,7 @@ describe("openFolder for a folder a chat links to", () => {
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)]);
+ assert.deepEqual(opened, [await fs.promises.realpath(botHome)]);
});
it("never opens a file (that would run it): the page keeps its save-a-copy", async () => {
diff --git a/src/components/AttachmentPreview.test.ts b/src/components/AttachmentPreview.test.ts
index 725a87d3b5..7a79246d83 100644
--- a/src/components/AttachmentPreview.test.ts
+++ b/src/components/AttachmentPreview.test.ts
@@ -1,7 +1,11 @@
-import { createElement } from "react";
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vitest";
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
import {
AttachedFileChips,
AttachedImageGallery,
@@ -17,6 +21,7 @@ import {
requestMessageFile,
safeDownloadFilename,
saveFailureText,
+ useLocalFileSave,
wrappedImageIndex,
} from "./AttachmentPreview";
@@ -223,6 +228,69 @@ describe("a file over the download limit", () => {
});
});
+describe("a folder linked in a message", () => {
+ const folderPath = "/work/Reports";
+ const listing = { name: "Reports", entries: [{ name: "q3.pdf", bytes: 2048, mime: "application/pdf" }], truncated: false };
+ const authorized = () => new Response(JSON.stringify(listing), { status: 200, headers: { "content-type": "application/json", "x-openmausbot-folder": "1" } });
+ const refused = () => new Response(JSON.stringify({ error: "the linked file is outside this conversation's workspace", code: "outside_workspace" }), { status: 403, headers: { "content-type": "application/json" } });
+
+ async function clickLink(answer: () => Response) {
+ vi.stubGlobal("fetch", vi.fn(async () => answer()));
+ const seen: { current: ReturnType<typeof useLocalFileSave> | null } = { current: null };
+ const Probe = () => {
+ seen.current = useLocalFileSave(folderPath, undefined, { threadId: "thread-1", messageId: "message-1" });
+ return null;
+ };
+ const root = createRoot(document.createElement("div"));
+ await act(async () => { root.render(createElement(Probe)); });
+ await act(async () => { await seen.current!.save(); });
+ const result = { state: seen.current!.state, folder: seen.current!.folder };
+ await act(async () => { root.unmount(); });
+ return result;
+ }
+
+ it("opens in the file manager once the route authorized it, with no listing", async () => {
+ const openFolder = vi.fn(async () => "opened");
+ vi.stubGlobal("ogb", { openFolder, remoteClient: { active: false } });
+ try {
+ expect(await clickLink(authorized)).toEqual({ state: "idle", folder: null });
+ expect(openFolder).toHaveBeenCalledWith(folderPath);
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("shows the listing when the desktop would not open it", async () => {
+ const openFolder = vi.fn(async () => "not-folder");
+ vi.stubGlobal("ogb", { openFolder, remoteClient: { active: false } });
+ try {
+ expect(await clickLink(authorized)).toEqual({ state: "idle", folder: listing });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("shows the listing where there is no desktop bridge", async () => {
+ vi.stubGlobal("ogb", undefined);
+ try {
+ expect(await clickLink(authorized)).toEqual({ state: "idle", folder: listing });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it("never reaches the desktop when the route refuses the link", async () => {
+ const openFolder = vi.fn(async () => "opened");
+ vi.stubGlobal("ogb", { openFolder, remoteClient: { active: false } });
+ try {
+ expect(await clickLink(refused)).toEqual({ state: "failed", folder: null });
+ expect(openFolder).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+});
+
describe("local Markdown image lifecycle", () => {
it("builds a path-free, directly streamable message preview URL", () => {
expect(messageImagePreviewUrl(
diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsx
index c7fa01271e..782fc11606 100644
--- a/src/components/AttachmentPreview.tsx
+++ b/src/components/AttachmentPreview.tsx
@@ -36,7 +36,7 @@ import { t } from "@/lib/i18n";
import { serverErrorText } from "@/lib/server-error";
import { FilePreviewButton } from "./FilePreviewButton";
import { chipNameAction, SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";
-import { ImageLoading } from "./ImageLoading";
+import { ImageLoading } from "./ImageLoading"; import { openLinkedFolder } from "./RevealOriginalMenu";
export interface PreviewImage {
src: string;
@@ -301,8 +301,8 @@ export function useLocalFileSave(filePath: string, name?: string, message?: Mess
if (response.headers.get("x-openmausbot-folder") === "1") {
const listing = await response.json() as MessageFolderListing;
if (!mounted.current || controller.signal.aborted) return;
- setFolder(listing);
setState("idle");
+ if (!(await openLinkedFolder(filePath)) && !controller.signal.aborted) setFolder(listing); // Security: only a path this message's route just authorized reaches the desktop bridge.
return;
}
const blob = await response.blob();
diff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.ts
index 5e7c0578ad..582e3980f4 100644
--- a/src/components/ChatMarkdown.test.ts
+++ b/src/components/ChatMarkdown.test.ts
@@ -900,43 +900,6 @@ describe("ChatMarkdown attachments", () => {
}
});
- it("shows Opening while a folder link opens, then stops showing an earlier save failure", async () => {
- let finish: (result: "opened") => void = () => {};
- const openFolder = vi.fn(() => new Promise<"opened">((resolve) => { finish = resolve; }));
- const save = vi.spyOn(AttachmentPreview, "useLocalFileSave").mockReturnValue({
- state: "failed",
- reason: "Couldn't save",
- savedTo: "",
- outsideWorkspace: false,
- retryable: true,
- folder: null,
- save: vi.fn(async () => undefined),
- });
- vi.stubGlobal("ogb", { openFolder, remoteClient: { active: false } });
- const host = document.createElement("div");
- document.body.append(host);
- const root = createRoot(host);
- try {
- await act(async () => {
- root.render(createElement(ChatMarkdown, { text: "[post](/work/Instagram/04_post/)", message: { threadId: "thread-1", messageId: "message-1" } }));
- });
- const link = [...host.querySelectorAll("button")].find((button) => button.textContent?.includes("post"))!;
- await act(async () => { link.click(); });
- expect(openFolder).toHaveBeenCalledWith("/work/Instagram/04_post/");
- expect(host.querySelector('[role="status"]')?.textContent).toBe("Opening…");
- expect(host.querySelector('[role="alert"]')).toBeNull();
- expect(link.querySelector(".animate-spin")).not.toBeNull();
- await act(async () => { finish("opened"); });
- expect(host.querySelector('[role="alert"]')).toBeNull();
- expect(host.textContent).not.toContain("Couldn't save");
- } finally {
- act(() => root.unmount());
- host.remove();
- vi.unstubAllGlobals();
- save.mockRestore();
- }
- });
-
describe("a file link outside the conversation's workspace", () => {
const filePath = "C:\\Users\\Maus\\_draft\\ollama-gen.js";
const render = (outsideWorkspace: boolean, href = filePath) => {
@@ -948,7 +911,7 @@ describe("ChatMarkdown attachments", () => {
retryable: !outsideWorkspace,
folder: null,
save: vi.fn(async () => undefined),
- });
+ });
try {
return renderToStaticMarkup(createElement(ChatMarkdown, {
text: `[ollama-gen.js](${href})`, message: { threadId: "thread-1", messageId: "message-1" },
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index c578f1fcca..fb13ff1a63 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -30,7 +30,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 { openLinkedFolder, useRevealOriginalMenu } from "./RevealOriginalMenu";
+import { useRevealOriginalMenu } from "./RevealOriginalMenu";
const mermaidCache = new Map<string, string>();
const MERMAID_CACHE_MAX = 50;
@@ -333,20 +333,14 @@ function LocalFileLink({ filePath, name, source, children, message }: { filePath
const save = useLocalFileSave(filePath, name, message);
const preview = useHtmlPreview(filePath, name ?? fileName(filePath), message);
const revealMenu = useRevealOriginalMenu();
- const [opening, setOpening] = useState(false);
- const [opened, setOpened] = useState(false);
if (!message) {
return <span title={t("chat.file.legacy")} className="break-words text-ink-secondary">{children}</span>;
}
- // While a folder link opens, and after it opened, an earlier failed save is no longer what the link shows.
- const shown = opening ? "opening" : opened && save.state === "failed" ? "idle" : save.state;
- const label = shown === "opening"
- ? t("settings.updates.opening")
- : shown === "saving"
+ const label = save.state === "saving"
? t("common.saving")
- : shown === "saved"
+ : save.state === "saved"
? t("common.saved")
- : shown === "failed"
+ : save.state === "failed"
? t("chat.retry")
: null;
@@ -358,23 +352,19 @@ 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 : () => {
- setOpening(true);
- setOpened(false);
- void openLinkedFolder(filePath).then((done) => done ? setOpened(true) : save.save()).finally(() => setOpening(false));
- }}
- disabled={!preview.html && (opening || save.state === "saving")}
+ onClick={preview.html ? preview.show : () => void 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"
>
{children}
{preview.html ? (
<Eye size={12} className="shrink-0" aria-hidden="true" />
- ) : shown === "opening" || shown === "saving" ? (
+ ) : save.state === "saving" ? (
<LoaderCircle size={12} className="shrink-0 animate-spin" aria-hidden="true" />
- ) : shown === "saved" ? (
+ ) : save.state === "saved" ? (
<Check size={12} className="shrink-0 text-success" aria-hidden="true" />
- ) : shown === "failed" ? (
+ ) : save.state === "failed" ? (
save.retryable && <RotateCcw size={12} className="shrink-0" aria-hidden="true" />
) : (
<Download size={12} className="shrink-0" aria-hidden="true" />
@@ -382,14 +372,14 @@ function LocalFileLink({ filePath, name, source, children, message }: { filePath
</button>
{label && (
<span
- role={shown === "failed" ? "alert" : "status"}
- title={shown === "saved" ? save.savedTo : undefined}
- className={`text-[12px] ${shown === "saved" ? "text-success" : shown === "failed" ? "text-danger" : "text-ink-secondary"}`}
+ role={save.state === "failed" ? "alert" : "status"}
+ title={save.state === "saved" ? save.savedTo : undefined}
+ className={`text-[12px] ${save.state === "saved" ? "text-success" : save.state === "failed" ? "text-danger" : "text-ink-secondary"}`}
>
- {shown === "failed" ? saveFailureText(save) : label}
+ {save.state === "failed" ? saveFailureText(save) : label}
</span>
)}
- {shown === "failed" && save.outsideWorkspace && (
+ {save.state === "failed" && save.outsideWorkspace && (
<span className="inline-flex flex-wrap items-center gap-x-1.5 text-[12px]">
<OutsideWorkspaceFile filePath={filePath} />
</span>