Skip to content

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

feat(chat): a file path a bot writes as plain text opens like a link

Azad Jagtapd94ef2e630e1
diff --git a/server/message-file.ts b/server/message-file.ts
index 75150adbb1..3dd1fe26e4 100644
--- a/server/message-file.ts
+++ b/server/message-file.ts
@@ -8,6 +8,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
import { fromMarkdown } from "mdast-util-from-markdown";
import { windowsPathDestinations } from "../shared/markdown-windows-paths.ts";
+import { linkPlainPaths } from "../shared/markdown-plain-paths.ts";
import { inSecretFolder, SECRET_FILE_REFUSAL } from "./secret-folder.ts";
export const MESSAGE_FILE_MAX_BYTES = 25 * 1024 * 1024;
@@ -148,12 +149,15 @@ function walkMarkdown(node: MarkdownNode, visit: (node: MarkdownNode) => void):
}
}
-function renderedMarkdownTargets(markdown: string): string[] {
+/** `plainPaths`: also the paths written as plain text, which the app renders as links too. */
+function renderedMarkdownTargets(markdown: string, plainPaths = false): string[] {
const definitions = new Map<string, string>();
const links: string[] = [];
const references: string[] = [];
- walkMarkdown(fromMarkdown(markdown, { mdastExtensions: [windowsPathDestinations] }), (node) => {
+ const tree = fromMarkdown(markdown, { mdastExtensions: [windowsPathDestinations] });
+ if (plainPaths) linkPlainPaths(tree, markdown);
+ walkMarkdown(tree, (node) => {
if (node.type === "definition" && node.identifier && node.url) {
if (!definitions.has(node.identifier)) definitions.set(node.identifier, node.url);
} else if ((node.type === "link" || node.type === "image") && node.url) {
@@ -205,7 +209,7 @@ export function messageReferencesFile(text: string, requested: string): boolean
return false;
}
- for (const target of renderedMarkdownTargets(text)) {
+ for (const target of renderedMarkdownTargets(text, true)) {
try {
if (referencedPathIdentity(target, false) === wanted) return true;
} catch {
diff --git a/shared/markdown-plain-paths.test.ts b/shared/markdown-plain-paths.test.ts
new file mode 100644
index 0000000000..38d076f447
--- /dev/null
+++ b/shared/markdown-plain-paths.test.ts
@@ -0,0 +1,45 @@
+import { fromMarkdown } from "mdast-util-from-markdown";
+import { describe, expect, it } from "vitest";
+
+import { linkPlainPaths } from "./markdown-plain-paths.ts";
+import { windowsPathDestinations } from "./markdown-windows-paths.ts";
+
+type Node = { type: string; url?: string; value?: string; children?: Node[] };
+
+function links(markdown: string): string[] {
+ const tree = fromMarkdown(markdown, { mdastExtensions: [windowsPathDestinations] }) as Node;
+ linkPlainPaths(tree, markdown);
+ const urls: string[] = [];
+ const pending: Node[] = [tree];
+ while (pending.length) {
+ const node = pending.shift()!;
+ if (node.type === "link" && node.url) urls.push(node.url);
+ pending.unshift(...(node.children ?? []));
+ }
+ return urls;
+}
+
+describe("plain file paths", () => {
+ it("links POSIX, Windows and UNC paths in prose, keeping each one's spelling", () => {
+ expect(links("I saved it to /Users/me/reports/q3.md, take a look.")).toEqual(["/Users/me/reports/q3.md"]);
+ expect(links(String.raw`Written to C:\Users\me\.openmausbot\report.md.`)).toEqual([String.raw`C:\Users\me\.openmausbot\report.md`]);
+ expect(links(String.raw`It's on \\fileserver\team\plans\roadmap.docx now.`)).toEqual([String.raw`\\fileserver\team\plans\roadmap.docx`]);
+ });
+
+ it("links a path in backticks, spaces and folders included", () => {
+ expect(links("Open `/Users/me/My Reports/q3 final.md`.")).toEqual(["/Users/me/My Reports/q3 final.md"]);
+ expect(links(String.raw`See ` + "`" + String.raw`\\fileserver\team\plans` + "`")).toEqual([String.raw`\\fileserver\team\plans`]);
+ expect(links("Run `npm test` in `src`.")).toEqual([]);
+ });
+
+ it("reads a POSIX path's Markdown escapes as escapes", () => {
+ expect(links(String.raw`Saved /tmp/out/my\_notes.md`)).toEqual(["/tmp/out/my_notes.md"]);
+ });
+
+ it("leaves prose, web links, code blocks and existing links alone", () => {
+ expect(links("Use and/or, see 1/2.5 or /etc alone.")).toEqual([]);
+ expect(links("See https://example.com/docs/guide.md for more.")).toEqual([]);
+ expect(links("```\ncat /Users/me/notes.md\n```")).toEqual([]);
+ expect(links("[the report](/Users/me/report.md)")).toEqual(["/Users/me/report.md"]);
+ });
+});
diff --git a/shared/markdown-plain-paths.ts b/shared/markdown-plain-paths.ts
new file mode 100644
index 0000000000..cabcd3b620
--- /dev/null
+++ b/shared/markdown-plain-paths.ts
@@ -0,0 +1,72 @@
+// A file path a bot writes in prose or in backticks becomes a link to that file. Markdown has already decoded a text
+// node's escapes, so "\\server\share" reads as "\server\share" there: paths are found in each node's source instead,
+// and a Windows or UNC path keeps its spelling. The server and the client both run this on the same source, so the
+// file authorized is the file rendered.
+
+type Node = {
+ type: string;
+ value?: string;
+ url?: string;
+ children?: Node[];
+ position?: { start: { offset?: number }; end: { offset?: number } };
+};
+
+const SKIP = new Set(["link", "linkReference", "definition", "code", "html", "math", "inlineMath", "image", "imageReference"]);
+const EXT = String.raw`\.[A-Za-z0-9]{1,10}`;
+const POSIX_PART = String.raw`(?:[\w.@+~-]|\\[_*~.-])`;
+const WIN_PART = String.raw`[^\s\\/:*?"<>|\x60()\[\]]`;
+// A path needs a folder and a file name with an extension, so "and/or" or a lone "/etc" stays prose.
+const PROSE_PATH = new RegExp(
+ [
+ String.raw`(?<![\w.~/\\:@-])\/(?:${POSIX_PART}+\/)+${POSIX_PART}*[\w@+~-]${EXT}(?![\w/\\])`,
+ String.raw`(?<![\w\\/])[A-Za-z]:\\(?:${WIN_PART}+\\)*${WIN_PART}*[^\s\\/:*?"<>|\x60()\[\].]${EXT}(?![\w\\])`,
+ String.raw`(?<![\w\\])\\\\${WIN_PART}+(?:\\${WIN_PART}+)+${EXT}(?![\w\\])`,
+ ].join("|"),
+ "g",
+);
+// In backticks the whole span is the path, so spaces are allowed and no extension is needed.
+const CODE_PATH = /^(?:\/(?:[^\s/][^/]*\/)+[^/]+|[A-Za-z]:\\(?:[^\\]+\\?)+|\\\\[^\\]+(?:\\[^\\]+)+)$/;
+
+/** Removes Markdown's backslash escapes, the one decoding a plain path's text goes through. */
+const unescape = (raw: string): string => raw.replace(/\\([!-/:-@[-`{-~])/g, "$1");
+const isPosix = (raw: string): boolean => raw.startsWith("/");
+
+function splitText(node: Node, source: string): Node[] {
+ const start = node.position?.start.offset, end = node.position?.end.offset, value = node.value;
+ if (start === undefined || end === undefined || typeof value !== "string") return [node];
+ const raw = source.slice(start, end);
+ const out: Node[] = [];
+ let cursor = 0;
+ for (const match of raw.matchAll(PROSE_PATH)) {
+ const spelled = match[0];
+ // POSIX backslashes are Markdown escapes; Windows and UNC backslashes are the path.
+ const decoded = unescape(spelled);
+ const at = value.indexOf(decoded, cursor);
+ if (at < 0) continue;
+ if (at > cursor) out.push({ type: "text", value: value.slice(cursor, at) });
+ const url = isPosix(spelled) ? decoded : spelled;
+ out.push({ type: "link", url, children: [{ type: "text", value: url }] });
+ cursor = at + decoded.length;
+ }
+ if (!out.length) return [node];
+ if (cursor < value.length) out.push({ type: "text", value: value.slice(cursor) });
+ return out;
+}
+
+/** Turns plain file paths under `tree` into links; `source` is the Markdown `tree` was parsed from. */
+export function linkPlainPaths(tree: object, source: string): void {
+ const visit = (node: Node) => {
+ if (!node.children) return;
+ node.children = node.children.flatMap((child): Node[] => {
+ if (SKIP.has(child.type)) return [child];
+ if (child.type === "inlineCode") {
+ const path = child.value?.trim() ?? "";
+ return CODE_PATH.test(path) ? [{ type: "link", url: path, children: [child] }] : [child];
+ }
+ if (child.type === "text") return splitText(child, source);
+ visit(child);
+ return [child];
+ });
+ };
+ visit(tree as Node);
+}
diff --git a/src/components/ChatMarkdown.test.ts b/src/components/ChatMarkdown.test.ts
index c48a4ec998..0e6974fadf 100644
--- a/src/components/ChatMarkdown.test.ts
+++ b/src/components/ChatMarkdown.test.ts
@@ -30,6 +30,7 @@ import { BotEditorStore, initialState, StoreProvider } from "@/state/store";
import { setLocale } from "@/lib/i18n";
import { ThreadRefsContext } from "./ThreadRefs";
import * as AttachmentPreview from "./AttachmentPreview";
+import { messageReferencesFile } from "../../server/message-file";
// Most of this file pins Advanced mode's chrome; the Simple code block has its own tests below.
const mode = vi.hoisted(() => ({ advanced: true }));
@@ -812,6 +813,34 @@ describe("ChatMarkdown attachments", () => {
}
});
+ it("links a path written as plain text, and the server authorizes the very path the link asks for", () => {
+ const cases: Array<[string, string]> = [
+ ["I saved the report to /Users/maus/reports/q3.md, have a look.", "/Users/maus/reports/q3.md"],
+ ["It's in `/Users/maus/My Reports/q3 final.md`.", "/Users/maus/My Reports/q3 final.md"],
+ [String.raw`Written to C:\Users\Maus\.openmausbot\report.md.`, String.raw`C:\Users\Maus\.openmausbot\report.md`],
+ [String.raw`It's on \\fileserver\team\plans\roadmap.docx now.`, String.raw`\\fileserver\team\plans\roadmap.docx`],
+ [String.raw`Saved /tmp/out/my\_notes.md`, "/tmp/out/my_notes.md"],
+ ];
+ for (const [text, expected] of cases) {
+ const save = vi.spyOn(AttachmentPreview, "useLocalFileSave");
+ try {
+ renderToStaticMarkup(createElement(ChatMarkdown, { text, message: { threadId: "thread-1", messageId: "message-1" } }));
+ const requested = save.mock.calls[0]?.[0];
+ // Spaces travel percent-encoded, as in any Markdown link, and the server decodes them once.
+ expect(requested!.replace(/%20/g, " ")).toBe(expected);
+ expect(messageReferencesFile(text, requested!)).toBe(true);
+ } finally {
+ save.mockRestore();
+ }
+ }
+ });
+
+ it("does not authorize a path the message never rendered as a link", () => {
+ expect(messageReferencesFile("Use and/or here, or /etc alone.", "/etc")).toBe(false);
+ expect(messageReferencesFile("```\ncat /Users/maus/notes.md\n```", "/Users/maus/notes.md")).toBe(false);
+ expect(messageReferencesFile(String.raw`On \\fileserver\team\a.md`, String.raw`\fileserver\team\a.md`.slice(1))).toBe(false);
+ });
+
it("keeps an unscoped legacy file link inert", () => {
const html = renderToStaticMarkup(createElement(ChatMarkdown, {
text: "[Download the report](/workspace/final-report.pdf)",
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index fed07b8e5f..b7a70c8425 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -16,6 +16,7 @@ import { markdownImageName, markdownImageOpenUrl } from "../lib/markdown-image";
import { repairMarkdownTables } from "../lib/markdown-tables";
import { TRANSCRIPT_WINDOW_SIZE } from "../lib/transcript-window";
import { windowsPathDestinations } from "../../shared/markdown-windows-paths";
+import { linkPlainPaths } from "../../shared/markdown-plain-paths";
import { GITHUB_REF_CLASS, isUseMyComputerUrl, LINK_CLASS, UseMyComputerLink, usePageOpener, withPageOpen } from "./ChatLinks";
import { githubRefFromProps, remarkGithubRefs } from "@/lib/github-refs";
import { GITHUB_REF_ICONS, LinkHoverCard } from "@/components/LinkHoverCard";
@@ -67,7 +68,7 @@ export function chatUrlTransform(value: string, key = "href"): string {
if (looksLikeThreadRefUrl(value) || isUseMyComputerUrl(value)) return value;
// Markdown-to-HTML percent-encodes a destination's backslashes (C:%5CUsers…); restore them and leave other escapes
// for the server's single decode.
- const url = /^[a-zA-Z]:%5C/i.test(value) ? value.replace(/%5C/gi, "\\") : value;
+ const url = /^(?:[a-zA-Z]:%5C|%5C%5C)/i.test(value) ? value.replace(/%5C/gi, "\\") : value;
if (/^file:\/\//i.test(url) || WINDOWS_PATH.test(url) || url.startsWith("\\\\")) {
return localFilePath(url) ? url : "";
}
@@ -76,6 +77,12 @@ export function chatUrlTransform(value: string, key = "href"): string {
}
/** Must parse link destinations exactly as the server's message-file parser does. */
+function remarkPlainPaths() {
+ return (tree: object, file: { value?: unknown }) => {
+ if (typeof file.value === "string") linkPlainPaths(tree, file.value);
+ };
+}
+
function remarkWindowsPathDestinations(this: { data(): object }) {
const data = this.data() as { fromMarkdownExtensions?: unknown[] };
(data.fromMarkdownExtensions ??= []).push(windowsPathDestinations);
@@ -725,7 +732,7 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
<MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered }}>
<div className="chat-md min-w-0 [&>*+*]:mt-2">
<Markdown
- remarkPlugins={[remarkGfm, remarkMath, remarkWindowsPathDestinations, unwrapLinkedImages, remarkGithubRefs, [remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }], remarkThreadRefs(threads, currentBotId)]}
+ remarkPlugins={[remarkGfm, remarkMath, remarkWindowsPathDestinations, remarkPlainPaths, unwrapLinkedImages, remarkGithubRefs, [remarkMentions, { peers: mentionPeers, everyone, person: mentionPerson }], remarkThreadRefs(threads, currentBotId)]}
rehypePlugins={mathPlugin ? [mathPlugin] : []}
urlTransform={chatUrlTransform}
components={MARKDOWN_COMPONENTS}