Skip to content

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

feat(html-preview): open HTML files in preview, add desktop "Open in browser" (#4406)

AdityaUmalef63eea855e92
diff --git a/electron/bridge-contract.json b/electron/bridge-contract.json
index ea477495de..a9487df60c 100644
--- a/electron/bridge-contract.json
+++ b/electron/bridge-contract.json
@@ -168,6 +168,7 @@
"openAtLogin.set",
"openAtLogin.state",
"openExternal",
+ "openHtmlInBrowser",
"openInstallTerminal",
"openLogsFolder",
"organization",
diff --git a/electron/main.mjs b/electron/main.mjs
index 182e4e4a5f..c0f127ec14 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, openLogsFolder, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
+import { collisionFreeDownloadPath, defaultSaveName, 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";
@@ -2326,11 +2326,11 @@ 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-html", localOnly("desktop:open-html", (_event, source, name) => openHtmlCopy(source, name, { dir: path.join(app.getPath("temp"), "openmausbot-open"), 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) => {
if (!isKnownSkin(skin)) return false;
diff --git a/electron/preload.cjs b/electron/preload.cjs
index c32ec6b923..ca593651ea 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -123,6 +123,14 @@ if (isLocalPage && !desktopRemoteClient && process.argv.includes("--omb-company-
// main passes app.getVersion(): a server's page carries that server's version, so About asks this for the app's own.
const appVersion = (process.argv.find((arg) => arg.startsWith("--omb-app-version="))?.slice("--omb-app-version=".length) ?? "").slice(0, 64);
+/** ipcRenderer wraps a main-process throw in "Error invoking remote method"; the page shows the text verbatim. */
+function invokeWithPlainError(channel, ...args) {
+ return ipcRenderer.invoke(channel, ...args).catch((error) => {
+ const message = String(error?.message ?? error);
+ throw new Error(message.replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/, ""));
+ });
+}
+
const bridge = {
platform: process.platform,
/** This app's version, and whether this page is this app's own (served by this computer, not a server from the Server menu). */
@@ -366,13 +374,9 @@ const bridge = {
},
pickFolder: (current) => ipcRenderer.invoke("desktop:pick-folder", current),
exportDiagnostics: () => ipcRenderer.invoke("desktop:export-diagnostics"),
- /** ipcRenderer wraps a main-process throw in "Error invoking remote method"; the bubble shows the text verbatim. */
- saveFile: (filePath) =>
- ipcRenderer.invoke("desktop:save-file", filePath).catch((error) => {
- const message = String(error?.message ?? error);
- throw new Error(message.replace(/^Error invoking remote method '[^']*':\s*(?:Error:\s*)?/, ""));
- }),
+ saveFile: (filePath) => invokeWithPlainError("desktop:save-file", filePath),
revealInFolder: (filePath) => ipcRenderer.invoke("desktop:reveal-file", filePath),
+ 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"),
openAtLogin: {
diff --git a/electron/save-file.mjs b/electron/save-file.mjs
index bb9220662c..4494204596 100644
--- a/electron/save-file.mjs
+++ b/electron/save-file.mjs
@@ -140,6 +140,35 @@ export async function openLogsFolder(folder, { open, fsp = fs.promises }) {
return { folder, opened: !error, ...(error ? { error: String(error).slice(0, 300) } : {}) };
}
+export const OPEN_HTML_MAX_BYTES = 2 * 1024 * 1024;
+
+/** A file name safe to write in our own folder: no folders, control or reserved characters, and a .html/.htm end. */
+export function htmlCopyName(name) {
+ const kept = [...String(name ?? "").split(/[\\/]/).pop()].filter((ch) => ch > "\u001f" && ch !== "\u007f" && !'<>:"|?*'.includes(ch));
+ const base = kept.join("").replace(/^[.\s]+|[.\s]+$/g, "");
+ const stem = (base.replace(/\.html?$/i, "") || "page").slice(0, 80);
+ return `${stem}${/\.htm$/i.test(base) ? ".htm" : ".html"}`;
+}
+
+/** Opens HTML the page already showed in the default browser: a fresh copy in our own temp folder, never a path a page
+ * names. `open` is shell.openPath, which answers "" or why it failed. Copies older than a day are cleared first. */
+export async function openHtmlCopy(source, name, { dir, open, fsp = fs.promises, now = Date.now() }) {
+ if (typeof source !== "string") throw new Error("Nothing to open");
+ if (Buffer.byteLength(source, "utf8") > OPEN_HTML_MAX_BYTES) throw new Error("This page is too large to open (2 MB)");
+ await fsp.mkdir(dir, { recursive: true, mode: 0o700 });
+ for (const entry of await fsp.readdir(dir, { withFileTypes: true }).catch(() => [])) {
+ if (!entry.isDirectory() || !entry.name.startsWith("p-")) continue;
+ const old = path.join(dir, entry.name);
+ const stat = await fsp.stat(old).catch(() => null);
+ if (stat && now - stat.mtimeMs > 24 * 60 * 60 * 1000) await fsp.rm(old, { recursive: true, force: true }).catch(() => undefined);
+ }
+ const file = path.join(await fsp.mkdtemp(path.join(dir, "p-")), htmlCopyName(name));
+ await fsp.writeFile(file, source, { encoding: "utf8", flag: "wx", mode: 0o600 });
+ const error = await open(file);
+ if (error) throw new Error(String(error).slice(0, 300));
+ return true;
+}
+
export async function defaultSaveName(dir, sourcePath, { fsp = fs.promises } = {}) {
const ext = path.extname(sourcePath);
const stem = path.basename(sourcePath, ext);
diff --git a/electron/save-file.node-test.mjs b/electron/save-file.node-test.mjs
index bfcf73af28..01c9659d26 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, openLogsFolder, resolveSavablePath, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
+import { collisionFreeDownloadPath, defaultSaveName, htmlCopyName, openHtmlCopy, openLogsFolder, resolveSavablePath, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";
// Creating a symlink on Windows needs elevation or developer mode.
const canSymlink = (() => {
@@ -290,3 +290,57 @@ describe("openLogsFolder", () => {
assert.match(main, /const LOG_DIR = app\.getPath\("logs"\);/);
});
});
+
+describe("openHtmlCopy (#4406)", () => {
+ it("opens a fresh private copy inside our own folder, never a path from the page", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omb-open-html-"));
+ try {
+ const opened = [];
+ assert.equal(await openHtmlCopy("<h1>hi</h1>", "../../evil/report.html", { dir, open: async (file) => { opened.push(file); return ""; } }), true);
+ assert.equal(opened.length, 1);
+ assert.equal(path.dirname(path.dirname(opened[0])), dir);
+ assert.equal(path.basename(opened[0]), "report.html");
+ assert.equal(fs.readFileSync(opened[0], "utf8"), "<h1>hi</h1>");
+ if (process.platform !== "win32") assert.equal(fs.statSync(opened[0]).mode & 0o777, 0o600);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("refuses what is not a page or is too large, and passes on why the system could not open it", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omb-open-html-"));
+ try {
+ const open = async () => "";
+ await assert.rejects(openHtmlCopy(42, "a.html", { dir, open }), /Nothing to open/);
+ await assert.rejects(openHtmlCopy("x".repeat(2 * 1024 * 1024 + 1), "a.html", { dir, open }), /too large/);
+ await assert.rejects(openHtmlCopy("<p>", "a.html", { dir, open: async () => "No application" }), /No application/);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("clears copies older than a day", async () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omb-open-html-"));
+ try {
+ const old = path.join(dir, "p-old");
+ fs.mkdirSync(old);
+ const day = Date.now() + 25 * 60 * 60 * 1000;
+ await openHtmlCopy("<p>", "a.html", { dir, open: async () => "", now: day });
+ assert.equal(fs.existsSync(old), false);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("keeps only a safe file name with an HTML ending", () => {
+ assert.equal(htmlCopyName("C:\\x\\Report.HTM"), "Report.htm");
+ assert.equal(htmlCopyName("a<b>:c?.txt"), "abc.txt.html");
+ assert.equal(htmlCopyName(".."), "page.html");
+ assert.equal(htmlCopyName(undefined), "page.html");
+ });
+
+ it("is wired in main for this computer's page only, with main's own temp folder", () => {
+ const main = fs.readFileSync(new URL("./main.mjs", import.meta.url), "utf8");
+ assert.match(main, /ipcMain\.handle\("desktop:open-html", localOnly\("desktop:open-html", \(_event, source, name\) =>\s*openHtmlCopy\(source, name, \{ dir: path\.join\(app\.getPath\("temp"\), "openmausbot-open"\)/);
+ });
+});
diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsx
index 1e0e10cff0..eec32624b7 100644
--- a/src/components/AttachmentPreview.tsx
+++ b/src/components/AttachmentPreview.tsx
@@ -15,6 +15,7 @@ import {
ChevronRight,
Download,
ExternalLink,
+ Eye,
FileText,
FolderOpen,
ImageOff,
@@ -33,6 +34,7 @@ import {
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { FilePreviewButton } from "./FilePreviewButton";
+import { chipNameAction, SaveIconButton, useHtmlPreview } from "./HtmlFilePreview";
import { ImageLoading } from "./ImageLoading";
export interface PreviewImage {
@@ -896,9 +898,10 @@ export function AttachedFileChip({ file, message, linked = false, compact = fals
className?: string;
}) {
const save = useLocalFileSave(file.path, file.name, message);
+ const preview = useHtmlPreview(file.path, file.name, message);
const failed = save.state === "failed";
const retryable = failed && !save.outsideWorkspace;
- if (compact) return <CompactFileChip file={file} message={message} linked={linked} save={save} className={className} />;
+ if (compact) return <CompactFileChip file={file} message={message} linked={linked} save={save} preview={preview} className={className} />;
if (!message || (!file.private && !linked)) {
return (
<div title={t("attach.legacyFile", { name: file.name })} className={cn("flex max-w-[280px] items-center gap-2 overflow-hidden rounded-lg border border-hairline/40 bg-inset/70 px-2.5 py-2 text-[12px] text-ink-secondary", className)}>
@@ -916,18 +919,12 @@ export function AttachedFileChip({ file, message, linked = false, compact = fals
<div className="flex items-center pe-1">
<button
type="button"
- onClick={() => void save.save()}
- disabled={save.state === "saving"}
- aria-label={
- retryable
- ? t("attach.retrySaveAria", { name: file.name })
- : t("attach.saveAria", { name: file.name })
- }
+ {...chipNameAction(preview, save, file.name, retryable)}
className="flex min-h-10 min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left transition-colors hover:bg-raised/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent/60 disabled:cursor-wait disabled:hover:bg-transparent"
>
<FileText size={14} className="shrink-0" aria-hidden="true" />
<span className="min-w-0 flex-1 truncate text-ink">{file.name}</span>
- {save.state === "saving" ? (
+ {preview.html ? <Eye size={13} className="shrink-0" /> : save.state === "saving" ? (
<LoaderCircle size={13} className="shrink-0 animate-spin" />
) : save.state === "saved" ? (
<Check size={13} className="shrink-0 text-success" />
@@ -937,7 +934,8 @@ export function AttachedFileChip({ file, message, linked = false, compact = fals
<Download size={13} className="shrink-0" />
)}
</button>
- <FilePreviewButton path={file.path} name={file.name} message={message} />
+ {preview.html ? <SaveIconButton name={file.name} save={save} retryable={retryable} /> : <FilePreviewButton path={file.path} name={file.name} message={message} />}
+ {preview.dialog}
</div>
{save.state !== "idle" && (
<div
@@ -965,11 +963,12 @@ export function AttachedFileChip({ file, message, linked = false, compact = fals
const FILE_CHIP = "inline-flex h-7 max-w-[16rem] items-center rounded-full bg-ink/[0.06] text-[13px] leading-none text-ink-secondary";
-function CompactFileChip({ file, message, linked, save, className }: {
+function CompactFileChip({ file, message, linked, save, preview, className }: {
file: TranscriptFileAttachment;
message?: MessageAttachmentContext;
linked: boolean;
save: ReturnType<typeof useLocalFileSave>;
+ preview: ReturnType<typeof useHtmlPreview>;
className?: string;
}) {
const failed = save.state === "failed";
@@ -992,14 +991,12 @@ function CompactFileChip({ file, message, linked, save, className }: {
>
<button
type="button"
- onClick={() => void save.save()}
- disabled={save.state === "saving"}
- aria-label={retryable ? t("attach.retrySaveAria", { name: file.name }) : t("attach.saveAria", { name: file.name })}
+ {...chipNameAction(preview, save, file.name, retryable)}
className="inline-flex h-7 min-w-0 items-center gap-1.5 rounded-full ps-2.5 pe-2 transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus disabled:cursor-wait"
>
<FileText size={14} strokeWidth={1.75} className="shrink-0" aria-hidden="true" />
{name}
- {save.state === "saving" ? (
+ {preview.html ? <Eye size={13} strokeWidth={1.75} className="shrink-0" aria-hidden="true" /> : save.state === "saving" ? (
<LoaderCircle size={13} className="shrink-0 animate-spin" aria-hidden="true" />
) : save.state === "saved" ? (
<Check size={13} className="shrink-0 text-success" aria-hidden="true" />
@@ -1009,7 +1006,8 @@ function CompactFileChip({ file, message, linked, save, className }: {
<Download size={13} strokeWidth={1.75} className="shrink-0" aria-hidden="true" />
)}
</button>
- <FilePreviewButton path={file.path} name={file.name} message={message} />
+ {preview.html ? <SaveIconButton name={file.name} save={save} retryable={retryable} /> : <FilePreviewButton path={file.path} name={file.name} message={message} />}
+ {preview.dialog}
</span>
{save.state !== "idle" && save.state !== "saved" && (
<span role={failed ? "alert" : "status"} className={cn("px-2.5 text-[12px]", failed ? "text-danger" : "text-ink-secondary")}>
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index aa7f5610c7..c0bda891f5 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -4,7 +4,7 @@ import Markdown, { defaultUrlTransform, type Components, type ExtraProps, type O
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { fromMarkdown, type Options as MarkdownParseOptions } from "mdast-util-from-markdown";
-import { Check, Copy, Download, LoaderCircle, RotateCcw, WrapText, X } from "lucide-react";
+import { Check, Copy, Download, Eye, LoaderCircle, RotateCcw, WrapText, X } from "lucide-react";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import { cn } from "@/lib/cn";
@@ -28,6 +28,7 @@ import { MarkdownTable } from "./MarkdownTable";
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";
const mermaidCache = new Map<string, string>();
const MERMAID_CACHE_MAX = 50;
@@ -321,6 +322,7 @@ export function MermaidDiagram({ code }: MermaidDiagramProps) {
// which calls shell.openExternal without main's containment check.
function LocalFileLink({ filePath, name, children, message }: { filePath: string; name?: string; children?: ReactNode; message?: MessageAttachmentContext }) {
const save = useLocalFileSave(filePath, name, message);
+ const preview = useHtmlPreview(filePath, name ?? fileName(filePath), message);
if (!message) {
return <span title="Unavailable legacy file reference" className="break-words text-ink-secondary">{children}</span>;
}
@@ -334,16 +336,20 @@ function LocalFileLink({ filePath, name, children, message }: { filePath: string
return (
<span dir="ltr" className="inline-flex flex-wrap items-center gap-x-1.5 [unicode-bidi:isolate]">
- <FilePreviewButton path={filePath} name={name ?? fileName(filePath)} message={message} />
+ {preview.html
+ ? <SaveIconButton name={name ?? fileName(filePath)} save={save} retryable={save.state === "failed" && !save.outsideWorkspace} />
+ : <FilePreviewButton path={filePath} name={name ?? fileName(filePath)} message={message} />}
<button
type="button"
- onClick={() => void save.save()}
- disabled={save.state === "saving"}
- title="Save a copy"
+ onClick={preview.html ? preview.show : () => void save.save()}
+ disabled={!preview.html && save.state === "saving"}
+ title={preview.html ? t("html.preview", { name: name ?? fileName(filePath) }) : "Save a copy"}
className="inline-flex items-center gap-1 break-words text-start text-accent underline decoration-accent/40 hover:decoration-accent disabled:cursor-wait"
>
{children}
- {save.state === "saving" ? (
+ {preview.html ? (
+ <Eye size={12} className="shrink-0" aria-hidden="true" />
+ ) : save.state === "saving" ? (
<LoaderCircle size={12} className="shrink-0 animate-spin" aria-hidden="true" />
) : save.state === "saved" ? (
<Check size={12} className="shrink-0 text-success" aria-hidden="true" />
@@ -368,6 +374,7 @@ function LocalFileLink({ filePath, name, children, message }: { filePath: string
</span>
)}
{save.folder && <MessageFolderFiles folderPath={filePath} listing={save.folder} message={message} />}
+ {preview.dialog}
</span>
);
}
diff --git a/src/components/HtmlFilePreview.test.ts b/src/components/HtmlFilePreview.test.ts
index 09cfa486b1..b68e160e6b 100644
--- a/src/components/HtmlFilePreview.test.ts
+++ b/src/components/HtmlFilePreview.test.ts
@@ -1,8 +1,8 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { AttachedFileChip } from "./AttachmentPreview";
-import { HTML_PREVIEW_MAX_BYTES, HtmlPreviewFrame, htmlPreviewDocument, isHtmlFile } from "./HtmlFilePreview";
+import { HTML_PREVIEW_MAX_BYTES, HtmlPreviewFrame, OpenInBrowserButton, htmlPreviewDocument, isHtmlFile } from "./HtmlFilePreview";
import { readTableResponse } from "./TableFilePreview";
const message = { threadId: "t", messageId: "m" };
@@ -59,6 +59,39 @@ describe("file chip preview button", () => {
});
});
+describe("HTML file chip (#4406)", () => {
+ it("opens the preview from the file name and keeps saving on its own button", () => {
+ const html = chip("report.html");
+ expect(html).toMatch(/aria-label="Preview page: report.html"[^>]*>[^]*report\.html/);
+ expect(html).not.toMatch(/<button[^>]*aria-label="Save a copy of report.html"[^>]*class="flex min-h-10/);
+ expect(html).toMatch(/class="table-action" aria-label="Save a copy of report.html"/);
+ });
+
+ it("leaves other files as they were: the name saves, the side button previews", () => {
+ const csv = chip("data.csv");
+ expect(csv).toMatch(/aria-label="Save a copy of data.csv"/);
+ expect(csv).toContain("Preview table: data.csv");
+ expect(csv).not.toContain("Preview page:");
+ });
+});
+
+describe("OpenInBrowserButton", () => {
+ afterEach(() => vi.unstubAllGlobals());
+ const button = () => renderToStaticMarkup(createElement(OpenInBrowserButton, { source: "<p>hi</p>", name: "report.html", onError: () => undefined }));
+
+ it("shows on the desktop app that holds the file", () => {
+ vi.stubGlobal("window", { ogb: { openHtmlInBrowser: async () => true } });
+ expect(button()).toContain('aria-label="Open report.html in your browser"');
+ });
+
+ it("is hidden in a web browser and when the window shows another computer", () => {
+ vi.stubGlobal("window", {});
+ expect(button()).toBe("");
+ vi.stubGlobal("window", { ogb: { openHtmlInBrowser: async () => true, remoteClient: { active: true } } });
+ expect(button()).toBe("");
+ });
+});
+
describe("bounded read", () => {
it("stops an HTML page at its own cap", async () => {
const signal = new AbortController().signal;
diff --git a/src/components/HtmlFilePreview.tsx b/src/components/HtmlFilePreview.tsx
index 9692f2d1d7..ae1dd25df6 100644
--- a/src/components/HtmlFilePreview.tsx
+++ b/src/components/HtmlFilePreview.tsx
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from "react";
-import { Code2, Download, Eye, LoaderCircle, RotateCcw } from "lucide-react";
+import { Check, Code2, Download, ExternalLink, Eye, LoaderCircle, RotateCcw } from "lucide-react";
import { requestMessageFile, useLocalFileSave, type MessageAttachmentContext } from "./AttachmentPreview";
import { TableDialog } from "./RichTable";
import { readTableResponse } from "./TableFilePreview";
@@ -19,20 +19,78 @@ export function htmlPreviewDocument(source: string): string {
return `<meta http-equiv="Content-Security-Policy" content="${HTML_PREVIEW_CSP}"><base target="_blank">${source}`;
}
-export function HtmlFileButton({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {
+/** The desktop app opens a copy of the page in this computer's default browser. Security: never on the web or in the
+ * Cloud app, where a page would have to run on the app's own origin, nor while the window shows another computer. */
+export function htmlBrowserBridge(): ((source: string, name: string) => Promise<unknown>) | undefined {
+ const ogb = typeof window === "undefined" ? undefined : window.ogb;
+ return ogb?.remoteClient?.active ? undefined : ogb?.openHtmlInBrowser;
+}
+
+/** The page preview dialog for an HTML file in a message, opened by the eye button or by the file's name. */
+export function useHtmlPreview(path: string, name: string, message?: MessageAttachmentContext) {
const [open, setOpen] = useState(false);
- const trigger = useRef<HTMLButtonElement>(null);
+ const opener = useRef<HTMLElement | null>(null);
+ const html = message !== undefined && (isHtmlFile(name) || isHtmlFile(path));
+ return {
+ html,
+ show: (event: { currentTarget: HTMLElement }) => {
+ opener.current = event.currentTarget;
+ setOpen(true);
+ },
+ dialog: html && open && message
+ ? <TableDialog title={name} returnFocus={opener.current} onClose={() => setOpen(false)}><HtmlFileContent key={`${message.threadId}:${message.messageId}:${path}`} path={path} name={name} message={message} /></TableDialog>
+ : null,
+ };
+}
+
+export function HtmlFileButton({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {
+ const preview = useHtmlPreview(path, name, message);
return <>
- <button ref={trigger} type="button" className="table-action" title={t("html.preview", { name })} aria-label={t("html.preview", { name })} onClick={() => setOpen(true)}><Eye size={14} /></button>
- {open && <TableDialog title={name} returnFocus={trigger.current} onClose={() => setOpen(false)}><HtmlFileContent key={`${message.threadId}:${message.messageId}:${path}`} path={path} name={name} message={message} /></TableDialog>}
+ <button type="button" className="table-action" title={t("html.preview", { name })} aria-label={t("html.preview", { name })} onClick={preview.show}><Eye size={14} /></button>
+ {preview.dialog}
</>;
}
+/** A file chip's name button: an HTML file's name opens its preview, any other file's name saves it. */
+export function chipNameAction(preview: ReturnType<typeof useHtmlPreview>, save: ReturnType<typeof useLocalFileSave>, name: string, retryable: boolean) {
+ if (preview.html) return { onClick: preview.show, disabled: false, "aria-label": t("html.preview", { name }) };
+ return { onClick: () => void save.save(), disabled: save.state === "saving", "aria-label": retryable ? t("attach.retrySaveAria", { name }) : t("attach.saveAria", { name }) };
+}
+
+/** Saves a file whose name opens its preview instead. */
+export function SaveIconButton({ name, save, retryable }: { name: string; save: ReturnType<typeof useLocalFileSave>; retryable: boolean }) {
+ const label = retryable ? t("attach.retrySaveAria", { name }) : t("attach.saveAria", { name });
+ return (
+ <button type="button" className="table-action" aria-label={label} title={label} disabled={save.state === "saving"} onClick={() => void save.save()}>
+ {save.state === "saving" ? (
+ <LoaderCircle size={14} className="animate-spin" aria-hidden="true" />
+ ) : save.state === "saved" ? (
+ <Check size={14} className="text-success" aria-hidden="true" />
+ ) : retryable ? (
+ <RotateCcw size={14} className="text-danger" aria-hidden="true" />
+ ) : (
+ <Download size={14} aria-hidden="true" />
+ )}
+ </button>
+ );
+}
+
+export function OpenInBrowserButton({ source, name, onError }: { source: string; name: string; onError: (reason: string) => void }) {
+ const open = htmlBrowserBridge();
+ if (!open) return null;
+ const label = t("html.openInBrowser", { name });
+ return <button type="button" className="table-action" aria-label={label} title={label} onClick={() => {
+ onError("");
+ open(source, name).catch((reason: unknown) => onError(reason instanceof Error && reason.message ? reason.message : t("html.openFailed")));
+ }}><ExternalLink size={14} /></button>;
+}
+
function HtmlFileContent({ path, name, message }: { path: string; name: string; message: MessageAttachmentContext }) {
const [attempt, setAttempt] = useState(0);
const [source, setSource] = useState<string | null>(null);
const [error, setError] = useState<"size" | "load" | null>(null);
const [showSource, setShowSource] = useState(false);
+ const [openFailed, setOpenFailed] = useState("");
const save = useLocalFileSave(path, name, message);
useEffect(() => {
const controller = new AbortController();
@@ -55,9 +113,11 @@ function HtmlFileContent({ path, name, message }: { path: string; name: string;
<div className="flex items-center justify-end gap-1">
<button type="button" className="table-action" aria-pressed={showSource} aria-label={t(showSource ? "html.rendered" : "html.source")} title={t(showSource ? "html.rendered" : "html.source")} onClick={() => setShowSource(!showSource)}>{showSource ? <Eye size={14} /> : <Code2 size={14} />}</button>
<button type="button" className="table-action" aria-label={t("html.reload")} title={t("html.reload")} onClick={() => setAttempt(attempt + 1)}><RotateCcw size={14} /></button>
+ <OpenInBrowserButton source={source} name={name} onError={setOpenFailed} />
<button type="button" className="table-action" aria-label={t("attach.saveAria", { name })} title={t("attach.saveAria", { name })} disabled={save.state === "saving"} onClick={() => void save.save()}><Download size={14} /></button>
</div>
{save.state === "failed" && <p role="alert" className="text-end text-[12px] text-danger">{save.reason}</p>}
+ {openFailed && <p role="alert" className="text-end text-[12px] text-danger">{openFailed}</p>}
{showSource
? <pre className="h-[72dvh] overflow-auto rounded-lg border border-hairline/40 bg-inset p-3 text-[12px] leading-5 whitespace-pre-wrap break-words text-ink">{source}</pre>
: <HtmlPreviewFrame source={source} name={name} />}
diff --git a/src/locales/en.json b/src/locales/en.json
index 6454005cd9..220b59e72b 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -122,6 +122,8 @@
"html.rendered": "View page",
"html.reload": "Reload",
"html.frameTitle": "Preview of {name}",
+ "html.openInBrowser": "Open {name} in your browser",
+ "html.openFailed": "Could not open this page in your browser.",
"table.loading": "Opening table…",
"table.tooLarge": "This file is too large for an in-app preview (10 MB, 100,000 rows, 200 columns or 500,000 cells). Download the original to view it all.",
"table.invalid": "This CSV/TSV could not be read as a table. Check its quotes and column counts, or download the original.",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 579936b8eb..068341a9ef 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -406,6 +406,8 @@ const __APP_VERSION__: string;
* it there and reveals it. Resolves the chosen path, or null if the
* user cancelled the dialog. */
saveFile?(filePath: string): Promise<string | null>;
+ /** Desktop only: opens HTML this page already showed in the default browser, from a temp copy main writes. */
+ openHtmlInBrowser?(source: string, name: string): Promise<unknown>;
/** 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">;