Skip to content

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

feat(desktop): right-click menu for pictures, videos, links and plain spots

milind-soni6319fb1fbcdb
diff --git a/electron/context-menu.mjs b/electron/context-menu.mjs
new file mode 100644
index 0000000000..49159b3b7d
--- /dev/null
+++ b/electron/context-menu.mjs
@@ -0,0 +1,201 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import nativeText from "./native-text.cjs";
+import { pasteMenuItem } from "./paste-menu-item.mjs";
+
+/** The only types "Open in Default App" hands to the operating system, each with the extension the copy is given. */
+const OPENABLE = Object.freeze({
+ "image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp", "image/bmp": ".bmp", "image/avif": ".avif",
+ "video/mp4": ".mp4", "video/webm": ".webm", "video/quicktime": ".mov", "video/x-m4v": ".m4v",
+ "audio/mpeg": ".mp3", "audio/mp4": ".m4a", "audio/x-m4a": ".m4a", "audio/aac": ".aac", "audio/wav": ".wav", "audio/x-wav": ".wav",
+ "audio/wave": ".wav", "audio/ogg": ".ogg", "audio/opus": ".opus", "audio/flac": ".flac", "audio/x-flac": ".flac",
+});
+const MEDIA_SAVE_LABEL = Object.freeze({ image: "native.context.saveImageAs", video: "native.context.saveVideoAs", audio: "native.context.saveAudioAs" });
+const MEDIA_EXTENSION = /\.(?:png|jpe?g|gif|webp|bmp|avif|mp4|webm|mov|m4v|mp3|m4a|aac|wav|ogg|oga|opus|flac)$/i;
+const PAGE_EXTENSION = /\.(?:html?|php|aspx?|jsp)$/i;
+const PENDING_MS = 60_000;
+const OPENED_COPY_MS = 24 * 60 * 60 * 1000;
+
+/** A URL the window's own session can download: what the page itself loaded, never a file: path. */
+export function downloadableUrl(url) {
+ try {
+ return ["http:", "https:", "blob:", "data:"].includes(new URL(url).protocol);
+ } catch {
+ return false;
+ }
+}
+
+/** A link that names a file (report.pdf, a chat file route), not a web page. */
+export function fileLink(url) {
+ try {
+ const target = new URL(url);
+ if (target.protocol !== "http:" && target.protocol !== "https:") return false;
+ if (/^\/api\/(?:attachments\/[^/]+|threads\/[^/]+\/messages\/[^/]+\/file)$/.test(target.pathname)) return true;
+ const last = decodeURIComponent(target.pathname).split("/").pop() ?? "";
+ return /\.[a-z0-9]{1,8}$/i.test(last) && !PAGE_EXTENSION.test(last);
+ } catch {
+ return false;
+ }
+}
+
+/** A file link to a picture, video or audio, by its name or a chat player's link; the download's type is checked again. */
+export function mediaLink(url) {
+ if (!fileLink(url)) return false;
+ const target = new URL(url);
+ if (target.pathname.endsWith("/file") && target.searchParams.has("media")) return true;
+ return MEDIA_EXTENSION.test(decodeURIComponent(target.pathname));
+}
+
+/** A name safe to write in our own folder: no folders, control or reserved characters, no Windows device name. */
+export function mediaCopyName(suggested, extension) {
+ const kept = [...String(suggested ?? "").split(/[\\/]/).pop()].filter((ch) => ch > "\u001f" && ch !== "\u007f" && !'<>:"|?*'.includes(ch));
+ const base = kept.join("").replace(/^[.\s]+|[.\s]+$/g, "");
+ const stem = (base.replace(/\.[A-Za-z0-9]{1,8}$/, "") || "media").slice(0, 80);
+ return `${/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(stem) ? "_" : ""}${stem}${extension}`;
+}
+
+function mimeOf(item) {
+ return String(item.getMimeType?.() ?? "").split(";", 1)[0].trim().toLowerCase();
+}
+
+/** Chromium's suggested name, with the extension its type implies when it has none (a chat video link ends in /file). */
+export function savedName(item) {
+ const name = item.getFilename() || "download";
+ const extension = OPENABLE[mimeOf(item)];
+ return extension && !/\.[A-Za-z0-9]{1,8}$/.test(name) ? `${name}${extension}` : name;
+}
+
+/**
+ * Save As and Open in Default App go through `webContents.downloadURL`, so each request carries exactly what the page's
+ * own request would (the Cloud's session cookie, the desktop's owner header) and streams to disk, never into memory.
+ * `claim(item)` runs first in the session's will-download handler and takes only the downloads this menu started.
+ */
+export function createMediaDownloads({ dialog, shell, openDir, downloadsDir, t = nativeText.englishText.t, now = Date.now, fsSync = fs, log = () => {} }) {
+ const pending = new Map();
+ const forget = (url) => pending.delete(url);
+ const sweepOpened = () => {
+ const dir = openDir();
+ let entries = [];
+ try { entries = fsSync.readdirSync(dir, { withFileTypes: true }); } catch {}
+ for (const entry of entries) {
+ if (!entry.isDirectory() || !entry.name.startsWith("m-")) continue;
+ const old = path.join(dir, entry.name);
+ try {
+ if (now() - fsSync.statSync(old).mtimeMs > OPENED_COPY_MS) fsSync.rmSync(old, { recursive: true, force: true });
+ } catch {}
+ }
+ };
+ const tell = (message, detail) => void Promise.resolve(dialog.showMessageBox({ type: "warning", message, ...(detail ? { detail } : {}) })).catch(() => {});
+
+ const openCopy = (item) => {
+ const extension = OPENABLE[mimeOf(item)];
+ if (!extension) {
+ item.cancel();
+ tell(t("native.context.cannotOpen"));
+ return;
+ }
+ sweepOpened();
+ fsSync.mkdirSync(openDir(), { recursive: true, mode: 0o700 });
+ const file = path.join(fsSync.mkdtempSync(path.join(openDir(), "m-")), mediaCopyName(item.getFilename(), extension));
+ item.setSavePath(file);
+ item.once("done", (_event, state) => {
+ if (state !== "completed") return;
+ void Promise.resolve(shell.openPath(file)).then((error) => {
+ if (error) tell(t("native.context.openFailed"), String(error).slice(0, 300));
+ }, (error) => tell(t("native.context.openFailed"), String(error?.message ?? error).slice(0, 300)));
+ });
+ };
+
+ return {
+ /** `mode` is "save" (the system's Save dialog) or "open" (a private copy opened in its default app). */
+ start(webContents, url, mode) {
+ if (!downloadableUrl(url)) return false;
+ pending.set(url, { mode, at: now() });
+ try {
+ webContents.downloadURL(url);
+ return true;
+ } catch (error) {
+ forget(url);
+ log(`context menu download failed: ${error?.message ?? error}`);
+ return false;
+ }
+ },
+ claim(item) {
+ const url = item.getURLChain?.()[0] ?? item.getURL();
+ const intent = pending.get(url);
+ if (!intent) return false;
+ forget(url);
+ if (now() - intent.at > PENDING_MS) return false;
+ try {
+ if (intent.mode === "open") openCopy(item);
+ else item.setSaveDialogOptions({ defaultPath: path.join(downloadsDir(), savedName(item)) });
+ } catch (error) {
+ item.cancel();
+ log(`context menu download failed: ${error?.message ?? error}`);
+ tell(t("native.context.openFailed"), String(error?.message ?? error).slice(0, 300));
+ }
+ return true;
+ },
+ };
+}
+
+function editItems(params, paste, t) {
+ return [
+ { label: t("native.role.undo"), role: "undo", enabled: params.editFlags.canUndo },
+ { label: t("native.role.redo"), role: "redo", enabled: params.editFlags.canRedo },
+ { type: "separator" },
+ { label: t("native.role.cut"), role: "cut", enabled: params.editFlags.canCut },
+ { label: t("native.role.copy"), role: "copy", enabled: params.editFlags.canCopy },
+ paste,
+ { label: t("native.role.pasteAndMatchStyle"), role: "pasteAndMatchStyle", enabled: params.editFlags.canPaste },
+ { type: "separator" },
+ { label: t("native.role.selectAll"), role: "selectAll", enabled: params.editFlags.canSelectAll },
+ ];
+}
+
+function mediaItems(params, { webContents, downloads, t }) {
+ const kind = Object.hasOwn(MEDIA_SAVE_LABEL, params.mediaType) ? params.mediaType : null;
+ if (!kind) return [];
+ const items = kind === "image" && params.hasImageContents
+ ? [{ label: t("native.context.copyImage"), click: () => webContents.copyImageAt(params.x, params.y) }]
+ : [];
+ if (downloadableUrl(params.srcURL)) {
+ items.push(
+ { label: t(MEDIA_SAVE_LABEL[kind]), click: () => downloads.start(webContents, params.srcURL, "save") },
+ { label: t("native.context.openInDefaultApp"), click: () => downloads.start(webContents, params.srcURL, "open") },
+ );
+ }
+ return items;
+}
+
+/** The window's right-click menu, built from Electron's context-menu params: never empty, so right-click always answers. */
+export function contextMenuTemplate(params, { webContents, clipboard, downloads, t = nativeText.englishText.t }) {
+ const sections = [];
+ if (params.misspelledWord) {
+ sections.push((params.dictionarySuggestions ?? []).slice(0, 5).map((suggestion) => ({
+ label: suggestion,
+ click: () => webContents.replaceMisspelling(suggestion),
+ })));
+ }
+ if (params.linkURL) {
+ sections.push([
+ { label: t("native.context.copyLink"), click: () => clipboard.writeText(params.linkURL) },
+ ...(fileLink(params.linkURL) ? [{ label: t("native.context.saveLinkAs"), click: () => downloads.start(webContents, params.linkURL, "save") }] : []),
+ ...(mediaLink(params.linkURL) ? [{ label: t("native.context.openInDefaultApp"), click: () => downloads.start(webContents, params.linkURL, "open") }] : []),
+ ]);
+ }
+ const media = mediaItems(params, { webContents, downloads, t });
+ sections.push(media);
+ if (params.isEditable || params.linkURL || params.misspelledWord || params.selectionText) {
+ sections.push(editItems(params, pasteMenuItem(params, clipboard, webContents, t), t));
+ } else if (media.length === 0) {
+ sections.push([
+ { label: t("native.role.copy"), role: "copy", enabled: params.editFlags.canCopy },
+ { label: t("native.role.selectAll"), role: "selectAll" },
+ { type: "separator" },
+ { label: t("native.role.reload"), click: () => webContents.reload() },
+ ]);
+ }
+ return sections.filter((section) => section.length > 0).flatMap((section, index) => index === 0 ? section : [{ type: "separator" }, ...section]);
+}
diff --git a/electron/context-menu.node-test.mjs b/electron/context-menu.node-test.mjs
new file mode 100644
index 0000000000..b860a0f889
--- /dev/null
+++ b/electron/context-menu.node-test.mjs
@@ -0,0 +1,219 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { test } from "node:test";
+
+import { contextMenuTemplate, createMediaDownloads, fileLink, mediaCopyName, mediaLink, savedName } from "./context-menu.mjs";
+
+const CLOUD = "https://bright-otter.mausbot.cloud";
+const VIDEO = `${CLOUD}/api/threads/t1/messages/m1/file?media=${"a".repeat(43)}`;
+const editFlags = { canUndo: false, canRedo: false, canCut: false, canCopy: false, canPaste: false, canSelectAll: true };
+const base = { mediaType: "none", srcURL: "", hasImageContents: false, linkURL: "", isEditable: false, misspelledWord: "", dictionarySuggestions: [], selectionText: "", x: 12, y: 34, editFlags, pageURL: `${CLOUD}/` };
+
+function harness() {
+ const calls = [];
+ const webContents = {
+ copyImageAt: (x, y) => calls.push(["copyImageAt", x, y]),
+ downloadURL: (url) => calls.push(["downloadURL", url]),
+ reload: () => calls.push(["reload"]),
+ replaceMisspelling: (word) => calls.push(["replaceMisspelling", word]),
+ paste: () => calls.push(["paste"]),
+ };
+ const clipboard = { writeText: (text) => calls.push(["writeText", text]), availableFormats: () => [], readImage: () => ({ isEmpty: () => true }) };
+ const downloads = { start: (contents, url, mode) => { assert.equal(contents, webContents); calls.push(["download", url, mode]); return true; } };
+ const menu = (params) => contextMenuTemplate({ ...base, ...params }, { webContents, clipboard, downloads });
+ return { calls, menu };
+}
+
+const labels = (items) => items.map((item) => item.type === "separator" ? "---" : item.label);
+const click = (items, label) => items.find((item) => item.label === label).click();
+
+test("a picture offers copy, Save Image As and Open in Default App through the window's session", () => {
+ const { calls, menu } = harness();
+ const items = menu({ mediaType: "image", hasImageContents: true, srcURL: `${CLOUD}/api/attachments/shot.png` });
+ assert.deepEqual(labels(items), ["Copy Image", "Save Image As…", "Open in Default App"]);
+ click(items, "Copy Image");
+ click(items, "Save Image As…");
+ click(items, "Open in Default App");
+ assert.deepEqual(calls, [
+ ["copyImageAt", 12, 34],
+ ["download", `${CLOUD}/api/attachments/shot.png`, "save"],
+ ["download", `${CLOUD}/api/attachments/shot.png`, "open"],
+ ]);
+});
+
+test("a video or audio player offers Save As and Open in Default App for its streamed link or blob", () => {
+ const { calls, menu } = harness();
+ const video = menu({ mediaType: "video", srcURL: VIDEO });
+ assert.deepEqual(labels(video), ["Save Video As…", "Open in Default App"]);
+ click(video, "Open in Default App");
+ assert.deepEqual(calls, [["download", VIDEO, "open"]]);
+ assert.deepEqual(labels(menu({ mediaType: "audio", srcURL: `blob:${CLOUD}/0f8e` })), ["Save Audio As…", "Open in Default App"]);
+});
+
+test("media the session cannot download falls back to the plain menu instead of a dead right-click", () => {
+ const { menu } = harness();
+ assert.deepEqual(labels(menu({ mediaType: "video", srcURL: "file:///etc/passwd" })), ["Copy", "Select All", "---", "Reload"]);
+ assert.deepEqual(labels(menu({ mediaType: "image", hasImageContents: true, srcURL: "" })), ["Copy Image"]);
+});
+
+test("a link keeps Copy Link and the text menu, and gains Save Link As only when it names a file", () => {
+ const { calls, menu } = harness();
+ const file = menu({ linkURL: "https://example.com/files/report.pdf" });
+ assert.deepEqual(labels(file), ["Copy Link", "Save Link As…", "---", "Undo", "Redo", "---", "Cut", "Copy", "Paste", "Paste and Match Style", "---", "Select All"]);
+ click(file, "Copy Link");
+ click(file, "Save Link As…");
+ assert.deepEqual(calls, [["writeText", "https://example.com/files/report.pdf"], ["download", "https://example.com/files/report.pdf", "save"]]);
+ assert.deepEqual(labels(menu({ linkURL: "https://example.com/about" })).slice(0, 2), ["Copy Link", "---"]);
+ assert.equal(fileLink("https://example.com/index.html"), false);
+ assert.equal(fileLink(`${CLOUD}/api/threads/t1/messages/m1/file`), true);
+ assert.equal(fileLink("openmausbot://bot/abc.def"), false);
+ assert.equal(fileLink("mailto:[email protected]"), false);
+});
+
+test("a link to a picture, video or audio file, or a chat player's link, also opens in the default app", () => {
+ const { calls, menu } = harness();
+ const items = menu({ linkURL: VIDEO });
+ assert.deepEqual(labels(items).slice(0, 4), ["Copy Link", "Save Link As…", "Open in Default App", "---"]);
+ click(items, "Open in Default App");
+ assert.deepEqual(calls, [["download", VIDEO, "open"]]);
+ assert.equal(mediaLink("https://example.com/clips/demo.MOV"), true);
+ assert.equal(mediaLink("https://example.com/photo.jpeg"), true);
+ assert.equal(mediaLink("https://example.com/files/report.pdf"), false);
+ assert.equal(mediaLink(`${CLOUD}/api/threads/t1/messages/m1/file`), false);
+ assert.equal(mediaLink("https://example.com/watch?v=1"), false);
+});
+
+test("an editable field and a spelling mistake keep the existing menu", () => {
+ const { calls, menu } = harness();
+ const editable = menu({ isEditable: true, editFlags: { ...editFlags, canCopy: true, canPaste: true } });
+ assert.deepEqual(labels(editable), ["Undo", "Redo", "---", "Cut", "Copy", "Paste", "Paste and Match Style", "---", "Select All"]);
+ assert.equal(editable.find((item) => item.label === "Paste").role, "paste");
+ const spelling = menu({ isEditable: true, misspelledWord: "teh", dictionarySuggestions: ["the", "tea", "ten", "tech", "tee", "toe"] });
+ assert.deepEqual(labels(spelling).slice(0, 6), ["the", "tea", "ten", "tech", "tee", "---"]);
+ click(spelling, "the");
+ assert.deepEqual(calls, [["replaceMisspelling", "the"]]);
+ assert.deepEqual(labels(menu({ selectionText: "words" })).at(-1), "Select All");
+});
+
+test("a plain spot answers with Copy, Select All and Reload", () => {
+ const { calls, menu } = harness();
+ const items = menu({});
+ assert.deepEqual(labels(items), ["Copy", "Select All", "---", "Reload"]);
+ assert.equal(items[0].enabled, false);
+ click(items, "Reload");
+ assert.deepEqual(calls, [["reload"]]);
+});
+
+function scratch() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omb-context-menu-"));
+ return { dir, done: () => fs.rmSync(dir, { recursive: true, force: true }) };
+}
+
+function downloadItem({ url = VIDEO, filename = "file", mime = "video/mp4" } = {}) {
+ const item = new EventEmitter();
+ Object.assign(item, {
+ savePath: null, dialogOptions: null, cancelled: false,
+ getURL: () => url, getURLChain: () => [url], getFilename: () => filename, getMimeType: () => mime,
+ setSavePath(file) { this.savePath = file; },
+ setSaveDialogOptions(options) { this.dialogOptions = options; },
+ cancel() { this.cancelled = true; },
+ });
+ return item;
+}
+
+function mediaDownloads(dir, clock = { now: 1_000 }) {
+ const opened = [], told = [], fetched = [];
+ const downloads = createMediaDownloads({
+ dialog: { showMessageBox: async (options) => told.push(options) },
+ shell: { openPath: async (file) => { opened.push(file); return ""; } },
+ openDir: () => path.join(dir, "open"),
+ downloadsDir: () => path.join(dir, "Downloads"),
+ now: () => clock.now,
+ });
+ const webContents = { downloadURL: (url) => fetched.push(url) };
+ return { downloads, webContents, opened, told, fetched, clock };
+}
+
+test("Save As asks where to save, named for the video's type, and leaves other downloads to the app", () => {
+ const { dir, done } = scratch();
+ try {
+ const { downloads, webContents, fetched } = mediaDownloads(dir);
+ assert.equal(downloads.claim(downloadItem()), false);
+ assert.equal(downloads.start(webContents, VIDEO, "save"), true);
+ assert.deepEqual(fetched, [VIDEO]);
+ const item = downloadItem();
+ assert.equal(downloads.claim(item), true);
+ assert.equal(item.savePath, null);
+ assert.deepEqual(item.dialogOptions, { defaultPath: path.join(dir, "Downloads", "file.mp4") });
+ assert.equal(downloads.claim(downloadItem()), false);
+ } finally {
+ done();
+ }
+});
+
+test("Open in Default App saves a private copy with its type's extension, then opens it", async () => {
+ const { dir, done } = scratch();
+ try {
+ const { downloads, webContents, opened } = mediaDownloads(dir);
+ downloads.start(webContents, VIDEO, "open");
+ const item = downloadItem({ filename: "clip.final.exe", mime: "video/quicktime" });
+ assert.equal(downloads.claim(item), true);
+ assert.equal(path.basename(item.savePath), "clip.final.mov");
+ assert.ok(item.savePath.startsWith(path.join(dir, "open") + path.sep));
+ item.emit("done", {}, "completed");
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(opened, [item.savePath]);
+ downloads.start(webContents, VIDEO, "open");
+ const stopped = downloadItem();
+ downloads.claim(stopped);
+ stopped.emit("done", {}, "cancelled");
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(opened, [item.savePath]);
+ } finally {
+ done();
+ }
+});
+
+test("Open in Default App refuses a file that is not a picture, video or audio", async () => {
+ const { dir, done } = scratch();
+ try {
+ const { downloads, webContents, opened, told } = mediaDownloads(dir);
+ const url = `${CLOUD}/api/attachments/shot.png`;
+ downloads.start(webContents, url, "open");
+ const item = downloadItem({ url, filename: "shot.png", mime: "text/html" });
+ assert.equal(downloads.claim(item), true);
+ assert.equal(item.cancelled, true);
+ assert.equal(item.savePath, null);
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.deepEqual(opened, []);
+ assert.equal(told[0].message, "This file can't be opened from here. Use Save As… instead.");
+ } finally {
+ done();
+ }
+});
+
+test("a download started long ago, or from a URL the session cannot fetch, is not claimed", () => {
+ const { dir, done } = scratch();
+ try {
+ const { downloads, webContents, fetched, clock } = mediaDownloads(dir);
+ assert.equal(downloads.start(webContents, "file:///etc/passwd", "open"), false);
+ assert.deepEqual(fetched, []);
+ downloads.start(webContents, VIDEO, "open");
+ clock.now += 61_000;
+ assert.equal(downloads.claim(downloadItem()), false);
+ } finally {
+ done();
+ }
+});
+
+test("names stay inside the folder and away from Windows device names", () => {
+ assert.equal(mediaCopyName("../../evil/clip.mp4", ".mp4"), "clip.mp4");
+ assert.equal(mediaCopyName("CON", ".png"), "_CON.png");
+ assert.equal(mediaCopyName("", ".webm"), "media.webm");
+ assert.equal(mediaCopyName('a<b>:"c|?*.jpg', ".jpg"), "abc.jpg");
+ assert.equal(savedName(downloadItem({ filename: "report.pdf", mime: "application/pdf" })), "report.pdf");
+ assert.equal(savedName(downloadItem({ filename: "", mime: "image/png" })), "download.png");
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 0696e1b7af..40261039fd 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -12,7 +12,7 @@ import { finishSpeech, speechBusy, startSpeech, stopSpeech } from "./speech.mjs"
import { installTalk, isTalkPanel } from "./talk-main.mjs";
import { openBlankTerminal } from "./terminal-launch.mjs";
import { linuxDisablesGpu, SOFTWARE_RENDERING_ARG } from "./linux-gpu.mjs";
-import { pasteMenuItem } from "./paste-menu-item.mjs";
+import { contextMenuTemplate, createMediaDownloads } from "./context-menu.mjs";
import { attachUpdaterWindow, startUpdater, registerUpdaterIpc, sendUpdaterState, reopenedOutOfSight, quietSignals } from "./updater.mjs";
import {
appendDesktopCrashRecord,
@@ -1924,36 +1924,10 @@ async function forgetEnvironment(id, purge = false, confirmed = false) {
}
function showContextMenu(win, params) {
- if (!params.isEditable && !params.linkURL && !params.misspelledWord && !params.selectionText) return;
- const menuItems = [];
- if (params.misspelledWord) {
- for (const suggestion of params.dictionarySuggestions.slice(0, 5)) {
- menuItems.push({
- label: suggestion,
- click: () => win.webContents.replaceMisspelling(suggestion),
- });
- }
- if (menuItems.length) menuItems.push({ type: "separator" });
- }
- if (params.linkURL) {
- menuItems.push(
- { label: nativeT("native.context.copyLink"), click: () => clipboard.writeText(params.linkURL) },
- { type: "separator" },
- );
- }
- menuItems.push(
- { label: nativeT("native.role.undo"), role: "undo", enabled: params.editFlags.canUndo },
- { label: nativeT("native.role.redo"), role: "redo", enabled: params.editFlags.canRedo },
- { type: "separator" },
- { label: nativeT("native.role.cut"), role: "cut", enabled: params.editFlags.canCut },
- { label: nativeT("native.role.copy"), role: "copy", enabled: params.editFlags.canCopy },
- pasteMenuItem(params, clipboard, win.webContents, nativeT),
- { label: nativeT("native.role.pasteAndMatchStyle"), role: "pasteAndMatchStyle", enabled: params.editFlags.canPaste },
- { type: "separator" },
- { label: nativeT("native.role.selectAll"), role: "selectAll", enabled: params.editFlags.canSelectAll },
- );
- Menu.buildFromTemplate(menuItems).popup({ window: win, frame: params.frame });
+ Menu.buildFromTemplate(contextMenuTemplate(params, { webContents: win.webContents, clipboard, downloads: mediaDownloads, t: nativeT })).popup({ window: win, frame: params.frame });
}
+const mediaDownloads = createMediaDownloads({ dialog, shell, t: (...args) => nativeT(...args), log: slog,
+ openDir: () => path.join(app.getPath("temp"), "openmausbot-open-media"), downloadsDir: () => app.getPath("downloads") });
function createWindow({ deferNavigation = false } = {}) {
const waitsForSkinSync = process.platform === "win32";
@@ -2840,6 +2814,7 @@ app.whenReady().then(async () => {
await startupScreen?.ready;
if (desktopShutdownStarted) return;
session.defaultSession.on("will-download", (_event, item) => {
+ if (mediaDownloads.claim(item)) return;
item.setSavePath(collisionFreeDownloadPath(app.getPath("downloads"), item.getFilename()));
revealDownloadWhenDone(item, (filePath) => shell.showItemInFolder(filePath));
});
diff --git a/src/components/MessageActions.toggle.test.ts b/src/components/MessageActions.toggle.test.ts
index 456d41f7d9..03a1b892b7 100644
--- a/src/components/MessageActions.toggle.test.ts
+++ b/src/components/MessageActions.toggle.test.ts
@@ -26,7 +26,7 @@ async function render(forceOpen = false) {
await act(async () => {
root.render(
createElement("div", { [MESSAGE_ROW]: "" },
- createElement("div", { "data-chat-bubble": "" }, createElement("p", null, "an answer")),
+ createElement("div", { "data-chat-bubble": "" }, createElement("p", null, "an answer"), createElement("video", { "data-media": "" })),
createElement("span", { "data-outside": "" }, "gap"),
createElement(MessageActions, {
side: "bot",
@@ -151,6 +151,12 @@ describe("message actions row", () => {
expect(items()).toHaveLength(0);
});
+ it("leaves the native menu for a video in the bubble, which offers Save and Open", async () => {
+ await render();
+ expect(await rightClick(host.querySelector("[data-media]")!)).toBe(false);
+ expect(items()).toHaveLength(0);
+ });
+
it("keeps a row that must stay reachable out", async () => {
await render(true);
expect(shown()).toBe(true);
diff --git a/src/components/MessageActions.tsx b/src/components/MessageActions.tsx
index 652ad5f8f0..ed367957e4 100644
--- a/src/components/MessageActions.tsx
+++ b/src/components/MessageActions.tsx
@@ -30,6 +30,7 @@ export const ChatBusyContext = createContext(false);
export const MESSAGE_ROW = "data-message-row";
const INTERACTIVE = "a, button, input, textarea, select, summary, label, [role=button], [contenteditable=true]";
+const OWN_MENU_MEDIA = "img, video, audio";
const LONG_PRESS_MS = 450;
function focusVisible(target: EventTarget | null): boolean {
@@ -119,7 +120,7 @@ export function MessageActions({
const context = (event: MouseEvent) => {
if (!canPointRef.current || (event as Partial<PointerEvent>).pointerType === "touch") return;
const target = event.target;
- if (!(target instanceof Element) || !target.closest("[data-chat-bubble]") || target.closest(INTERACTIVE)) return;
+ if (!(target instanceof Element) || !target.closest("[data-chat-bubble]") || target.closest(INTERACTIVE) || target.closest(OWN_MENU_MEDIA)) return;
if (window.getSelection()?.toString().trim()) return;
const box = rootRef.current?.getBoundingClientRect();
if (!box) return;
diff --git a/src/locales/en.json b/src/locales/en.json
index 1ff8c2e2ed..9dd5fa8d45 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -9518,6 +9518,14 @@
"native.role.zoom": "Zoom",
"native.role.front": "Bring All to Front",
"native.context.copyLink": "Copy Link",
+ "native.context.copyImage": "Copy Image",
+ "native.context.saveImageAs": "Save Image As…",
+ "native.context.saveVideoAs": "Save Video As…",
+ "native.context.saveAudioAs": "Save Audio As…",
+ "native.context.saveLinkAs": "Save Link As…",
+ "native.context.openInDefaultApp": "Open in Default App",
+ "native.context.cannotOpen": "This file can't be opened from here. Use Save As… instead.",
+ "native.context.openFailed": "Couldn't open this file",
"native.title.connected": "OpenMausBot — Connected to: {server} ({host})",
"native.title.hosted": "OpenMausBot — Hosted: {name} ({host})",
"native.switcher.addCloudSub": "Keeps your bots running 24/7",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 2ec653b676..4f2c7eb78c 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -9435,6 +9435,14 @@
"native.role.zoom": "Zoom",
"native.role.front": "Trazer todas as janelas para a frente",
"native.context.copyLink": "Copiar link",
+ "native.context.copyImage": "Copiar imagem",
+ "native.context.saveImageAs": "Salvar imagem como…",
+ "native.context.saveVideoAs": "Salvar vídeo como…",
+ "native.context.saveAudioAs": "Salvar áudio como…",
+ "native.context.saveLinkAs": "Salvar link como…",
+ "native.context.openInDefaultApp": "Abrir no app padrão",
+ "native.context.cannotOpen": "Não dá para abrir este arquivo daqui. Use Salvar como… para guardar uma cópia.",
+ "native.context.openFailed": "Não foi possível abrir este arquivo",
"native.title.connected": "OpenMausBot — Conectado a: {server} ({host})",
"native.title.hosted": "OpenMausBot — Hospedado: {name} ({host})",
"native.switcher.addCloudSub": "Mantém seus bots rodando 24/7",