Skip to content

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

Local apps: Add to Desktop, and the card's menu is no longer cut off (#7722)

Milind Sonibaa4c7b7aeaf
diff --git a/electron/app-install-desktop.node-test.mjs b/electron/app-install-desktop.node-test.mjs
new file mode 100644
index 0000000000..9558032aae
--- /dev/null
+++ b/electron/app-install-desktop.node-test.mjs
@@ -0,0 +1,298 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { createAppInstaller } from "./app-install/installer.mjs";
+import { desktopEntry, macInfoPlist, macLauncherScript, macPlistAppId, windowsShortcut } from "./app-install/launchers.mjs";
+import { launcherLink, windowsAppUserModelId } from "./app-install/names.mjs";
+import { L, PNG, linux, mac, windows } from "./app-install-test-fixture.mjs";
+
+const UD_MAC = "/Users/u/Library/Application Support/OpenMausBot/";
+
+test("macOS: installing puts nothing on the Desktop; Add to Desktop copies the launcher bundle there", async () => {
+ const { fs, calls, installer, dir, desktop } = mac({ makeDesktop: true });
+ await installer.installApp({ id: L("notes"), name: "Notes", iconPng: PNG });
+ assert.deepEqual(await fs.readdir(desktop), []);
+ const sipsRuns = calls.length;
+
+ const added = await installer.addToDesktop(L("notes"));
+ assert.deepEqual(added, { ok: true, app: { id: L("notes"), name: "Notes", path: `${dir}/Notes.app`, desktop: true } });
+ const copy = `${desktop}/Notes.app/Contents`;
+ assert.equal(fs.text(`${copy}/Info.plist`), fs.text(`${dir}/Notes.app/Contents/Info.plist`));
+ assert.equal(macPlistAppId(fs.text(`${copy}/Info.plist`)), L("notes"));
+ assert.equal(fs.text(`${copy}/MacOS/launcher`), macLauncherScript({ id: L("notes") }));
+ assert.equal(fs.entries.get(`${copy}/MacOS/launcher`).mode, 0o755);
+ assert.equal(fs.text(`${copy}/Resources/AppIcon.icns`), "icns");
+ assert.equal(fs.text(`${copy}/PkgInfo`), "APPL????");
+ assert.equal(calls.length, sipsRuns, "the icon is copied from the installed bundle, not made again");
+ assert.deepEqual(await fs.readdir(desktop), ["Notes.app"]);
+ assert.deepEqual(await installer.installedApps(), [{ id: L("notes"), name: "Notes", path: `${dir}/Notes.app`, desktop: true }]);
+ assert.deepEqual(await installer.addToDesktop(L("notes")), added);
+ for (const file of fs.files()) assert.ok(file.startsWith(`${dir}/`) || file.startsWith(`${desktop}/Notes.app/`) || file.startsWith(UD_MAC), file);
+
+ assert.deepEqual(await installer.removeFromDesktop(L("notes")), { ok: true, removed: true });
+ assert.deepEqual(await fs.readdir(desktop), []);
+ assert.equal(await installer.isInstalled(L("notes")), true);
+ assert.equal((await installer.installedApps())[0].desktop, false);
+ assert.deepEqual(await installer.removeFromDesktop(L("notes")), { ok: true, removed: false });
+});
+
+test("macOS: Add to Desktop refuses an app that is not installed, a bad id, and an installer that is off", async () => {
+ const { fs, installer, desktop } = mac({ makeDesktop: true });
+ assert.deepEqual(await installer.addToDesktop(L("notes")), { ok: false, reason: "not-installed" });
+ assert.deepEqual(await installer.addToDesktop("../x"), { ok: false, reason: "invalid-id" });
+ assert.deepEqual(await installer.removeFromDesktop("../x"), { ok: false, reason: "invalid-id" });
+ assert.deepEqual(await fs.readdir(desktop), []);
+ const off = mac({ makeDesktop: true, enabled: false });
+ assert.deepEqual(await off.installer.addToDesktop(L("notes")), { ok: false, reason: "unavailable" });
+});
+
+test("macOS: a Desktop item the person made is never replaced or removed; two apps of one name both get theirs", async () => {
+ const { fs, installer, desktop } = mac({ makeDesktop: true });
+ await fs.mkdir(`${desktop}/Notes.app/Contents`, { recursive: true });
+ await fs.writeFile(`${desktop}/Notes.app/Contents/Info.plist`, "<plist>theirs</plist>");
+ fs.entries.set(`${desktop}/Notes 2.app`, { type: "link" });
+ await installer.installApp({ id: L("a"), name: "Notes" });
+ await installer.installApp({ id: L("b"), name: "Notes" });
+ await installer.addToDesktop(L("a"));
+ await installer.addToDesktop(L("b"));
+ assert.equal(fs.text(`${desktop}/Notes.app/Contents/Info.plist`), "<plist>theirs</plist>");
+ assert.equal(fs.entries.get(`${desktop}/Notes 2.app`).type, "link");
+ assert.equal(macPlistAppId(fs.text(`${desktop}/Notes 3.app/Contents/Info.plist`)), L("a"));
+ assert.equal(macPlistAppId(fs.text(`${desktop}/Notes 2 2.app/Contents/Info.plist`)), L("b"));
+
+ await fs.writeFile(`${desktop}/Notes 3.app/Contents/Info.plist`, macInfoPlist({ id: L("someone-else"), name: "Notes" }));
+ assert.equal((await installer.installedApps()).find((a) => a.id === L("a")).desktop, false);
+ assert.deepEqual(await installer.removeFromDesktop(L("a")), { ok: true, removed: true, left: [`${desktop}/Notes 3.app`] });
+ assert.equal(macPlistAppId(fs.text(`${desktop}/Notes 3.app/Contents/Info.plist`)), L("someone-else"));
+});
+
+test("macOS: a renamed app's Desktop item takes the new name; one the person deleted is not brought back", async () => {
+ const { fs, trashed, installer, dir, desktop } = mac({ makeDesktop: true });
+ await installer.installApp({ id: L("notes"), name: "Notes" });
+ await installer.addToDesktop(L("notes"));
+ const renamed = await installer.installApp({ id: L("notes"), name: "Journal" });
+ assert.equal(renamed.app.desktop, true);
+ assert.deepEqual(await fs.readdir(desktop), ["Journal.app"]);
+ assert.equal(macPlistAppId(fs.text(`${desktop}/Journal.app/Contents/Info.plist`)), L("notes"));
+ assert.match(fs.text(`${desktop}/Journal.app/Contents/Info.plist`), /<string>Journal<\/string>/);
+ assert.deepEqual(trashed.sort(), [`${desktop}/Notes.app`, `${dir}/Notes.app`].sort());
+
+ await fs.rm(`${desktop}/Journal.app`, { recursive: true });
+ const again = await installer.installApp({ id: L("notes"), name: "Diary" });
+ assert.equal(again.app.desktop, false);
+ assert.deepEqual(await fs.readdir(desktop), []);
+});
+
+test("macOS: Uninstall and the cleanup of gone apps take the Desktop item too, and leftover Desktop staging folders", async () => {
+ const { fs, dir, desktop, options } = mac({ makeDesktop: true });
+ // A fresh installer for every call: what each one needs is read from disk, as after a restart.
+ const installer = new Proxy({}, { get: (_target, key) => createAppInstaller(options)[key] });
+ await installer.installApp({ id: L("keep"), name: "Keep" });
+ await installer.installApp({ id: L("gone"), name: "Gone" });
+ await installer.installApp({ id: L("bye"), name: "Bye" });
+ for (const id of [L("keep"), L("gone"), L("bye")]) await installer.addToDesktop(id);
+ await fs.mkdir(`${desktop}/.mausbot-0123456789abcdef.staging/Contents`, { recursive: true });
+ await fs.mkdir(`${desktop}/.mausbot-mine.staging`, { recursive: true });
+
+ assert.deepEqual(await installer.uninstallApp(L("bye")), { ok: true, removed: true });
+ assert.equal(fs.entries.has(`${desktop}/Bye.app`), false);
+ assert.equal(fs.entries.has(`${dir}/Bye.app`), false);
+
+ assert.deepEqual(await installer.cleanup([L("keep")]), [L("gone")]);
+ assert.deepEqual((await fs.readdir(desktop)).sort(), [".mausbot-mine.staging", "Keep.app"]);
+});
+
+test("macOS: installing, listing, uninstalling and cleanup never look at the Desktop of someone who never added an item", async () => {
+ const { fs, installer, desktop } = mac({ makeDesktop: true });
+ const looked = [];
+ for (const method of ["stat", "lstat", "readdir", "readFile"]) {
+ const real = fs[method];
+ fs[method] = (p, ...rest) => { if (p === desktop || p.startsWith(`${desktop}/`)) looked.push([method, p]); return real(p, ...rest); };
+ }
+ await installer.installApp({ id: L("a"), name: "A" });
+ await installer.installApp({ id: L("a"), name: "B" });
+ await installer.installApp({ id: L("gone"), name: "Gone" });
+ await installer.installedApps();
+ await installer.isInstalled(L("a"));
+ await installer.cleanup([L("a")]);
+ await installer.uninstallApp(L("a"));
+ await installer.removeFromDesktop(L("a"));
+ assert.deepEqual(looked, []);
+});
+
+test("macOS: no Desktop folder, or one that can't be written, fails and leaves the launcher as it was", async () => {
+ const missing = mac();
+ await missing.installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.deepEqual(await missing.installer.addToDesktop(L("notes")), { ok: false, reason: "no-desktop" });
+ assert.equal(missing.fs.entries.has(missing.desktop), false, "the Desktop folder is never made");
+ assert.equal(await missing.installer.isInstalled(L("notes")), true);
+
+ const home = mac({ desktop: "/Users/u", makeDesktop: true });
+ await home.installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.deepEqual(await home.installer.addToDesktop(L("notes")), { ok: false, reason: "no-desktop" });
+
+ const locked = mac({ makeDesktop: true });
+ await locked.installer.installApp({ id: L("notes"), name: "Notes" });
+ locked.fs.readOnly.add(locked.desktop);
+ assert.deepEqual(await locked.installer.addToDesktop(L("notes")), { ok: false, reason: "failed" });
+ assert.deepEqual(await locked.fs.readdir(locked.desktop), []);
+ assert.equal(await locked.installer.isInstalled(L("notes")), true);
+ assert.equal((await locked.installer.installedApps())[0].desktop, false);
+ locked.fs.readOnly.clear();
+ assert.equal((await locked.installer.addToDesktop(L("notes"))).ok, true);
+
+ const renameLocked = mac({ makeDesktop: true });
+ await renameLocked.installer.installApp({ id: L("notes"), name: "Notes" });
+ await renameLocked.installer.addToDesktop(L("notes"));
+ renameLocked.fs.readOnly.add(renameLocked.desktop);
+ const renamed = await renameLocked.installer.installApp({ id: L("notes"), name: "Journal" });
+ assert.equal(renamed.ok, true, "a Desktop that can't be written never fails the launcher's own rename");
+ assert.equal(renamed.app.desktop, true);
+ assert.ok(renameLocked.fs.entries.has(`${renameLocked.desktop}/Notes.app`));
+});
+
+test("macOS: a Desktop redirected into iCloud Drive is where the item goes", async () => {
+ const icloud = "/Users/u/Library/Mobile Documents/com~apple~CloudDocs/Desktop";
+ const { fs, installer } = mac({ desktop: icloud, makeDesktop: true });
+ await installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.equal((await installer.addToDesktop(L("notes"))).ok, true);
+ assert.equal(macPlistAppId(fs.text(`${icloud}/Notes.app/Contents/Info.plist`)), L("notes"));
+ assert.equal(fs.entries.has("/Users/u/Desktop"), false);
+ assert.deepEqual(await installer.uninstallApp(L("notes")), { ok: true, removed: true });
+ assert.deepEqual(await fs.readdir(icloud), []);
+});
+
+test("Windows: a Desktop shortcut like the Start menu one, refusing the person's own, following renames and moves", async () => {
+ const { fs, shortcuts, installer, dir, desktop, options } = windows({ makeDesktop: true });
+ await installer.installApp({ id: L("notes"), name: "Notes", iconPng: PNG });
+ assert.equal(shortcuts.length, 1);
+ assert.deepEqual(await installer.addToDesktop(L("notes")), { ok: true, app: { id: L("notes"), name: "Notes", path: `${dir}\\Notes.lnk`, desktop: true } });
+ const [start, onDesktop] = shortcuts.map(([file, op, link]) => ({ file, op, link }));
+ assert.equal(onDesktop.file, `${desktop}\\Notes.lnk`);
+ assert.equal(onDesktop.op, "create");
+ assert.deepEqual(onDesktop.link, start.link);
+ assert.equal(onDesktop.link.target, options.executable);
+ assert.equal(onDesktop.link.args, launcherLink(L("notes")));
+ assert.equal(onDesktop.link.appUserModelId, windowsAppUserModelId(L("notes")));
+ assert.match(onDesktop.link.icon, /\\app-install\\icons\\[0-9a-f]{16}\.ico$/);
+
+ fs.entries.set(`${desktop}\\Mine.lnk`, { type: "file", data: Buffer.from(JSON.stringify({ target: "C:\\x.exe", args: "" })) });
+ await installer.installApp({ id: L("mine"), name: "Mine" });
+ await installer.addToDesktop(L("mine"));
+ assert.equal(JSON.parse(fs.text(`${desktop}\\Mine.lnk`)).target, "C:\\x.exe");
+ assert.ok(fs.entries.has(`${desktop}\\Mine 2.lnk`));
+
+ await installer.installApp({ id: L("other"), name: "NOTES" });
+ assert.equal((await installer.installedApps()).find((a) => a.id === L("other")).path, `${dir}\\NOTES 2.lnk`);
+ await installer.addToDesktop(L("other"));
+ assert.equal(shortcuts.at(-1)[0], `${desktop}\\NOTES 2.lnk`);
+
+ await installer.installApp({ id: L("notes"), name: "Journal" });
+ assert.ok(fs.entries.has(`${desktop}\\Journal.lnk`));
+ assert.equal(fs.entries.has(`${desktop}\\Notes.lnk`), false);
+
+ const moved = createAppInstaller({ ...options, executable: "D:\\OpenMausBot\\OpenMausBot.exe" });
+ assert.equal((await moved.refreshTargets()).length, 3);
+ assert.equal(JSON.parse(fs.text(`${desktop}\\Journal.lnk`)).target, "D:\\OpenMausBot\\OpenMausBot.exe");
+
+ assert.deepEqual(await installer.uninstallApp(L("notes")), { ok: true, removed: true });
+ assert.equal(fs.entries.has(`${desktop}\\Journal.lnk`), false);
+ assert.deepEqual(await installer.cleanup([L("mine")]), [L("other")]);
+ assert.deepEqual((await fs.readdir(desktop)).sort(), ["Mine 2.lnk", "Mine.lnk"]);
+ assert.deepEqual(await installer.removeFromDesktop(L("mine")), { ok: true, removed: true });
+ assert.deepEqual(await fs.readdir(desktop), ["Mine.lnk"]);
+});
+
+test("Windows: a Desktop moved to OneDrive is used; a missing one fails without touching the Start menu", async () => {
+ const oneDrive = "C:\\Users\\u\\OneDrive\\Desktop";
+ const redirected = windows({ desktop: oneDrive, makeDesktop: true });
+ await redirected.installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.equal((await redirected.installer.addToDesktop(L("notes"))).ok, true);
+ assert.ok(redirected.fs.entries.has(`${oneDrive}\\Notes.lnk`));
+
+ const missing = windows();
+ await missing.installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.deepEqual(await missing.installer.addToDesktop(L("notes")), { ok: false, reason: "no-desktop" });
+ assert.equal(missing.fs.entries.has(missing.desktop), false);
+ assert.ok(missing.fs.entries.has(`${missing.dir}\\Notes.lnk`));
+
+ const locked = windows({ makeDesktop: true });
+ await locked.installer.installApp({ id: L("notes"), name: "Notes" });
+ locked.fs.readOnly.add(locked.desktop);
+ assert.deepEqual(await locked.installer.addToDesktop(L("notes")), { ok: false, reason: "failed" });
+ assert.ok(locked.fs.entries.has(`${locked.dir}\\Notes.lnk`));
+});
+
+test("Windows: installing with desktopShortcut also puts one there, and never fails over the Desktop", async () => {
+ const { fs, installer, desktop } = windows();
+ const result = await installer.installApp({ id: L("notes"), name: "Notes", desktopShortcut: true });
+ assert.equal(result.ok, true);
+ assert.equal(result.app.desktop, false);
+ assert.equal(fs.entries.has(desktop), false);
+ fs.entries.set(desktop, { type: "dir" });
+ assert.equal((await installer.installApp({ id: L("notes"), name: "Notes", desktopShortcut: true })).app.desktop, true);
+ assert.equal(JSON.parse(fs.text(`${desktop}\\Notes.lnk`)).args, launcherLink(L("notes")));
+});
+
+test("Linux: an executable copy of the desktop entry in the XDG Desktop folder", async () => {
+ const { fs, runs, installer, dir, options } = linux({ xdg: "/home/u/Schreibtisch", makeDesktop: "/home/u/Schreibtisch" });
+ await installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.equal(runs.length, 0);
+ assert.equal((await installer.addToDesktop(L("notes"))).app.desktop, true);
+ assert.deepEqual(runs, [["xdg-user-dir", "DESKTOP"]]);
+ const item = "/home/u/Schreibtisch/Notes.desktop";
+ assert.equal(fs.text(item), fs.text(`${dir}/mausbot-app-${L("notes")}.desktop`));
+ assert.equal(fs.entries.get(item).mode, 0o755);
+ assert.match(fs.text(item), /^X-OpenMausBot-LocalApp=la_notes00000000000$/m);
+
+ await fs.writeFile("/home/u/Schreibtisch/Budget.desktop", "[Desktop Entry]\nName=Budget\n");
+ await installer.installApp({ id: L("budget"), name: "Budget" });
+ await installer.addToDesktop(L("budget"));
+ assert.equal(fs.text("/home/u/Schreibtisch/Budget.desktop"), "[Desktop Entry]\nName=Budget\n");
+ assert.ok(fs.entries.has("/home/u/Schreibtisch/Budget 2.desktop"));
+
+ await installer.installApp({ id: L("twin"), name: "Notes" });
+ await installer.addToDesktop(L("twin"));
+ assert.match(fs.text("/home/u/Schreibtisch/Notes 2.desktop"), /^X-OpenMausBot-LocalApp=la_twin000000000000$/m);
+
+ await installer.installApp({ id: L("notes"), name: "Journal" });
+ assert.equal(fs.entries.has(item), false);
+ assert.match(fs.text("/home/u/Schreibtisch/Journal.desktop"), /^Name=Journal$/m);
+
+ const moved = createAppInstaller({ ...options, executable: "/opt/OpenMausBot/openmausbot" });
+ await moved.refreshTargets();
+ assert.match(fs.text("/home/u/Schreibtisch/Journal.desktop"), /^Exec="\/opt\/OpenMausBot\/openmausbot" /m);
+ assert.equal(fs.entries.get("/home/u/Schreibtisch/Journal.desktop").mode, 0o755);
+ assert.equal(fs.entries.get(`${dir}/mausbot-app-${L("notes")}.desktop`).mode, 0o644);
+
+ await fs.writeFile("/home/u/Schreibtisch/Journal.desktop", desktopEntry({ id: L("theirs"), name: "Journal", executable: "/x" }));
+ assert.deepEqual(await createAppInstaller(options).uninstallApp(L("notes")), { ok: true, removed: true, left: ["/home/u/Schreibtisch/Journal.desktop"] });
+ assert.ok(fs.entries.has("/home/u/Schreibtisch/Journal.desktop"));
+ assert.deepEqual(await createAppInstaller(options).cleanup([L("budget")]), [L("twin")]);
+ assert.deepEqual((await fs.readdir("/home/u/Schreibtisch")).sort(), ["Budget 2.desktop", "Budget.desktop", "Journal.desktop"]);
+});
+
+test("Linux: ~/Desktop when xdg-user-dir is missing or names the home folder; no folder at all fails", async () => {
+ for (const xdg of [null, "/home/u", "relative/Desktop", "/a\n/b"]) {
+ const { fs, installer } = linux({ xdg, makeDesktop: "/home/u/Desktop" });
+ await installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.equal((await installer.addToDesktop(L("notes"))).ok, true, String(xdg));
+ assert.equal(fs.entries.get("/home/u/Desktop/Notes.desktop").mode, 0o755);
+ }
+ const { fs, installer, dir } = linux({ xdg: "/home/u/Desktop" });
+ await installer.installApp({ id: L("notes"), name: "Notes" });
+ assert.deepEqual(await installer.addToDesktop(L("notes")), { ok: false, reason: "no-desktop" });
+ assert.equal(fs.entries.has("/home/u/Desktop"), false);
+ assert.ok(fs.entries.has(`${dir}/mausbot-app-${L("notes")}.desktop`));
+});
+
+test("Desktop items stay inside the Desktop folder whatever the app's name", async () => {
+ const { fs, installer, desktop } = mac({ makeDesktop: true });
+ for (const [short, name] of [["a", "../../Library/x"], ["b", "/etc/passwd"], ["c", "..."], ["d", "a\u202Eb"]]) {
+ await installer.installApp({ id: L(short), name });
+ assert.equal((await installer.addToDesktop(L(short))).ok, true, name);
+ }
+ for (const file of fs.files().filter((f) => !f.startsWith("/Users/u/Applications/") && !f.startsWith(UD_MAC))) {
+ assert.ok(file.startsWith(`${desktop}/`) && !file.slice(desktop.length + 1).split("/")[0].startsWith("."), file);
+ }
+ assert.equal(windowsShortcut({ id: L("a"), name: "x", executable: "C:\\x.exe" }).args, launcherLink(L("a")));
+});
diff --git a/electron/app-install-mac.node-test.mjs b/electron/app-install-mac.node-test.mjs
index 6468f921ea..49dc29b91e 100644
--- a/electron/app-install-mac.node-test.mjs
+++ b/electron/app-install-mac.node-test.mjs
@@ -38,3 +38,42 @@ test("macOS: a real bundle built in a temporary home is structurally valid", { s
assert.deepEqual(await installer.uninstallApp("la_realtest00000000"), { ok: true, removed: true });
assert.equal(fs.existsSync(bundle), false);
});
+
+test("macOS: a real Desktop copy built in a temporary home is structurally valid and leaves the launcher alone", { skip: process.platform !== "darwin" }, async (t) => {
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "app-desktop-")));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ assert.ok(root.startsWith(fs.realpathSync(os.tmpdir())), root);
+ const home = path.join(root, "home");
+ const desktop = path.join(home, "Desktop");
+ fs.mkdirSync(desktop, { recursive: true });
+ const installer = createAppInstaller({
+ platform: "darwin", path, home, userData: path.join(root, "user-data"), desktop, fs: fs.promises, run, hostBundleId: "com.openmausbot.app", enabled: true,
+ });
+ const id = "la_desktoptest00000";
+ assert.equal((await installer.installApp({ id, name: "Desk Test" })).ok, true);
+ assert.deepEqual(fs.readdirSync(desktop), []);
+ const added = await installer.addToDesktop(id);
+ assert.equal(added.ok, true);
+ assert.equal(added.app.desktop, true);
+ const launcher = path.join(home, "Applications", "MausBot Apps", "Desk Test.app");
+ const copy = path.join(desktop, "Desk Test.app");
+ assert.deepEqual(fs.readdirSync(desktop), ["Desk Test.app"]);
+ const plist = path.join(copy, "Contents", "Info.plist");
+ assert.equal((await run("/usr/bin/plutil", ["-lint", plist])).code, 0);
+ assert.equal(macPlistAppId(fs.readFileSync(plist, "utf8")), id);
+ assert.equal(fs.lstatSync(copy).isSymbolicLink(), false);
+ const executable = path.join(copy, "Contents", "MacOS", "launcher");
+ assert.equal(fs.statSync(executable).mode & 0o111, 0o111);
+ assert.equal(fs.readFileSync(executable, "utf8"), fs.readFileSync(path.join(launcher, "Contents", "MacOS", "launcher"), "utf8"));
+ const icns = (bundle) => fs.readFileSync(path.join(bundle, "Contents", "Resources", "AppIcon.icns"));
+ assert.ok(icns(copy).equals(icns(launcher)));
+ assert.equal(icns(copy).toString("latin1", 0, 4), "icns");
+
+ assert.equal((await installer.installApp({ id, name: "Desk Renamed" })).app.desktop, true);
+ assert.deepEqual(fs.readdirSync(desktop), ["Desk Renamed.app"]);
+ assert.deepEqual(await installer.removeFromDesktop(id), { ok: true, removed: true });
+ assert.deepEqual(fs.readdirSync(desktop), []);
+ assert.equal(await installer.isInstalled(id), true);
+ assert.deepEqual(await installer.uninstallApp(id), { ok: true, removed: true });
+ assert.deepEqual(fs.readdirSync(path.join(home, "Applications", "MausBot Apps")), []);
+});
diff --git a/electron/app-install-test-fixture.mjs b/electron/app-install-test-fixture.mjs
new file mode 100644
index 0000000000..802c55e900
--- /dev/null
+++ b/electron/app-install-test-fixture.mjs
@@ -0,0 +1,111 @@
+// The installer's tests share these: an in-memory file system in either path flavour and an installer for each platform
+// with its folders and effects faked.
+import path from "node:path";
+import { createAppInstaller } from "./app-install/installer.mjs";
+import { letterTilePng } from "./app-install/icons.mjs";
+
+/** A saved app's id from a short name: `la_` and 16 characters, as the store makes them. */
+export const L = (short) => `la_${short.padEnd(16, "0")}`;
+
+export function memoryFs(flavour) {
+ const entries = new Map();
+ const missing = (p) => Object.assign(new Error(`ENOENT: ${p}`), { code: "ENOENT" });
+ const children = (p) => [...entries.keys()].filter((k) => k.startsWith(p.endsWith(flavour.sep) ? p : p + flavour.sep));
+ const stat = (e) => ({ isDirectory: () => e.type === "dir", isFile: () => e.type === "file", isSymbolicLink: () => e.type === "link", mode: e.mode });
+ const parentReady = (p) => { if (entries.get(flavour.dirname(p))?.type !== "dir") throw missing(flavour.dirname(p)); };
+ const readOnly = new Set();
+ const writable = (p) => { if (readOnly.has(flavour.dirname(p))) throw Object.assign(new Error(`EACCES: ${p}`), { code: "EACCES" }); };
+ const fs = {
+ entries,
+ readOnly,
+ async mkdir(p, { recursive } = {}) {
+ const chain = [];
+ for (let at = p; !entries.has(at); at = flavour.dirname(at)) { chain.unshift(at); if (flavour.dirname(at) === at) break; }
+ if (!recursive && chain.length > 1) throw missing(p);
+ if (!recursive && !chain.length) throw Object.assign(new Error(`EEXIST: ${p}`), { code: "EEXIST" });
+ for (const dir of chain) { writable(dir); entries.set(dir, { type: "dir" }); }
+ },
+ async writeFile(p, data, opts) {
+ parentReady(p);
+ writable(p);
+ if (entries.get(p)?.type === "dir") throw new Error(`EISDIR: ${p}`);
+ entries.set(p, { type: "file", data: Buffer.from(data), mode: opts?.mode ?? 0o644 });
+ },
+ async readFile(p, encoding) {
+ const e = entries.get(p);
+ if (e?.type !== "file") throw missing(p);
+ return encoding ? e.data.toString(encoding) : e.data;
+ },
+ async rm(p, { recursive, force } = {}) {
+ if (!entries.has(p)) { if (force) return; throw missing(p); }
+ if (entries.get(p).type === "dir" && children(p).length && !recursive) throw new Error(`ENOTEMPTY: ${p}`);
+ for (const k of children(p)) entries.delete(k);
+ entries.delete(p);
+ },
+ async rename(a, b) {
+ if (!entries.has(a)) throw missing(a);
+ parentReady(b);
+ writable(b);
+ const moved = [[a, entries.get(a)], ...children(a).map((k) => [k, entries.get(k)])];
+ for (const [k] of moved) entries.delete(k);
+ for (const [k, v] of moved) entries.set(b + k.slice(a.length), v);
+ },
+ async lstat(p) { const e = entries.get(p); if (!e) throw missing(p); return stat(e); },
+ async stat(p) { const e = entries.get(p); if (!e) throw missing(p); return stat(e); },
+ async readdir(p) { return children(p).filter((k) => flavour.dirname(k) === p).map((k) => flavour.basename(k)); },
+ async chmod(p, mode) { const e = entries.get(p); if (!e) throw missing(p); e.mode = mode; },
+ text: (p) => entries.get(p)?.data?.toString("utf8"),
+ files: () => [...entries].filter(([, e]) => e.type !== "dir").map(([k]) => k),
+ };
+ return fs;
+}
+
+export const PNG = letterTilePng({ id: L("seed"), name: "Seed", size: 64 });
+
+/** `desktop`: the Desktop folder Electron names; `makeDesktop`: whether it exists. */
+export function mac({ runOk = true, trash = true, enabled = true, desktop = "/Users/u/Desktop", makeDesktop = false } = {}) {
+ const fs = memoryFs(path.posix);
+ if (makeDesktop) fs.entries.set(desktop, { type: "dir" });
+ const calls = [];
+ const trashed = [];
+ const run = async (file, args) => {
+ calls.push([file, ...args]);
+ if (!runOk) return { code: 1 };
+ const out = file.endsWith("sips") ? args[args.indexOf("--out") + 1] : args[args.indexOf("-o") + 1];
+ await fs.writeFile(out, file.endsWith("sips") ? PNG : Buffer.from("icns"));
+ return { code: 0 };
+ };
+ const shell = trash ? { trashItem: async (p) => { trashed.push(p); await fs.rm(p, { recursive: true }); } } : {};
+ const options = { platform: "darwin", path: path.posix, home: "/Users/u", userData: "/Users/u/Library/Application Support/OpenMausBot", desktop, fs, run, shell, hostBundleId: "com.openmausbot.app", enabled };
+ return { fs, calls, trashed, options, installer: createAppInstaller(options), dir: "/Users/u/Applications/MausBot Apps", desktop };
+}
+
+export function windows({ executable = "C:\\Users\\u\\AppData\\Local\\Programs\\OpenMausBot\\OpenMausBot.exe", desktop = "C:\\Users\\u\\Desktop", makeDesktop = false } = {}) {
+ const fs = memoryFs(path.win32);
+ if (makeDesktop) fs.entries.set(desktop, { type: "dir" });
+ const shortcuts = [];
+ const shell = {
+ writeShortcutLink(file, operation, options) {
+ if (fs.entries.get(path.win32.dirname(file))?.type !== "dir" || fs.readOnly.has(path.win32.dirname(file))) return false;
+ shortcuts.push([file, operation, options]);
+ fs.entries.set(file, { type: "file", data: Buffer.from(JSON.stringify(options)) });
+ return true;
+ },
+ readShortcutLink(file) { return JSON.parse(fs.text(file)); },
+ };
+ const options = { platform: "win32", path: path.win32, home: "C:\\Users\\u", userData: "C:\\Users\\u\\AppData\\Roaming\\OpenMausBot", appData: "C:\\Users\\u\\AppData\\Roaming", desktop, fs, shell, executable, resizePng: async (png) => png };
+ return { fs, shortcuts, options, installer: createAppInstaller(options), dir: "C:\\Users\\u\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\MausBot Apps", desktop };
+}
+
+/** `xdg`: what `xdg-user-dir DESKTOP` prints (null: it is not installed); `makeDesktop`: the folder that exists. */
+export function linux({ executable = "/home/u/Apps/OpenMausBot.AppImage", xdg = null, makeDesktop = null } = {}) {
+ const fs = memoryFs(path.posix);
+ if (makeDesktop) fs.entries.set(makeDesktop, { type: "dir" });
+ const runs = [];
+ const run = async (file, args) => {
+ runs.push([file, ...args]);
+ return xdg === null ? { code: 127, stdout: "" } : { code: 0, stdout: `${xdg}\n` };
+ };
+ const options = { platform: "linux", path: path.posix, home: "/home/u", userData: "/home/u/.config/OpenMausBot", fs, run, executable };
+ return { fs, runs, options, installer: createAppInstaller(options), dir: "/home/u/.local/share/applications" };
+}
diff --git a/electron/app-install.node-test.mjs b/electron/app-install.node-test.mjs
index 77f94f817a..cde62a0d6b 100644
--- a/electron/app-install.node-test.mjs
+++ b/electron/app-install.node-test.mjs
@@ -3,99 +3,11 @@ import path from "node:path";
import test from "node:test";
import { createAppInstaller } from "./app-install/installer.mjs";
import { icoFromPng, letterTilePng, pngSize, tileLetter } from "./app-install/icons.mjs";
+import { L, PNG, linux, mac, windows } from "./app-install-test-fixture.mjs";
import { installAppInstall } from "./app-install/ipc.mjs";
import { desktopEntry, macInfoPlist, macLauncherScript, macPlistAppId, windowsShortcut, windowsWindowDetails } from "./app-install/launchers.mjs";
import { launcherBundleId, launcherLink, launcherName, validAppId, windowsAppUserModelId } from "./app-install/names.mjs";
-/** A saved app's id from a short name: `la_` and 16 characters, as the store makes them. */
-const L = (short) => `la_${short.padEnd(16, "0")}`;
-
-function memoryFs(flavour) {
- const entries = new Map();
- const missing = (p) => Object.assign(new Error(`ENOENT: ${p}`), { code: "ENOENT" });
- const children = (p) => [...entries.keys()].filter((k) => k.startsWith(p.endsWith(flavour.sep) ? p : p + flavour.sep));
- const stat = (e) => ({ isDirectory: () => e.type === "dir", isFile: () => e.type === "file", isSymbolicLink: () => e.type === "link", mode: e.mode });
- const parentReady = (p) => { if (entries.get(flavour.dirname(p))?.type !== "dir") throw missing(flavour.dirname(p)); };
- const fs = {
- entries,
- async mkdir(p, { recursive } = {}) {
- const chain = [];
- for (let at = p; !entries.has(at); at = flavour.dirname(at)) { chain.unshift(at); if (flavour.dirname(at) === at) break; }
- if (!recursive && chain.length > 1) throw missing(p);
- for (const dir of chain) entries.set(dir, { type: "dir" });
- },
- async writeFile(p, data, opts) {
- parentReady(p);
- if (entries.get(p)?.type === "dir") throw new Error(`EISDIR: ${p}`);
- entries.set(p, { type: "file", data: Buffer.from(data), mode: opts?.mode ?? 0o644 });
- },
- async readFile(p, encoding) {
- const e = entries.get(p);
- if (e?.type !== "file") throw missing(p);
- return encoding ? e.data.toString(encoding) : e.data;
- },
- async rm(p, { recursive, force } = {}) {
- if (!entries.has(p)) { if (force) return; throw missing(p); }
- if (entries.get(p).type === "dir" && children(p).length && !recursive) throw new Error(`ENOTEMPTY: ${p}`);
- for (const k of children(p)) entries.delete(k);
- entries.delete(p);
- },
- async rename(a, b) {
- if (!entries.has(a)) throw missing(a);
- parentReady(b);
- const moved = [[a, entries.get(a)], ...children(a).map((k) => [k, entries.get(k)])];
- for (const [k] of moved) entries.delete(k);
- for (const [k, v] of moved) entries.set(b + k.slice(a.length), v);
- },
- async lstat(p) { const e = entries.get(p); if (!e) throw missing(p); return stat(e); },
- async readdir(p) { return children(p).filter((k) => flavour.dirname(k) === p).map((k) => flavour.basename(k)); },
- async chmod(p, mode) { const e = entries.get(p); if (!e) throw missing(p); e.mode = mode; },
- text: (p) => entries.get(p)?.data?.toString("utf8"),
- files: () => [...entries].filter(([, e]) => e.type !== "dir").map(([k]) => k),
- };
- return fs;
-}
-
-const PNG = letterTilePng({ id: L("seed"), name: "Seed", size: 64 });
-
-function mac({ runOk = true, trash = true, enabled = true } = {}) {
- const fs = memoryFs(path.posix);
- const calls = [];
- const trashed = [];
- const run = async (file, args) => {
- calls.push([file, ...args]);
- if (!runOk) return { code: 1 };
- const out = file.endsWith("sips") ? args[args.indexOf("--out") + 1] : args[args.indexOf("-o") + 1];
- await fs.writeFile(out, file.endsWith("sips") ? PNG : Buffer.from("icns"));
- return { code: 0 };
- };
- const shell = trash ? { trashItem: async (p) => { trashed.push(p); await fs.rm(p, { recursive: true }); } } : {};
- const installer = createAppInstaller({ platform: "darwin", path: path.posix, home: "/Users/u", userData: "/Users/u/Library/Application Support/OpenMausBot", fs, run, shell, hostBundleId: "com.openmausbot.app", enabled });
- return { fs, calls, trashed, installer, dir: "/Users/u/Applications/MausBot Apps" };
-}
-
-function windows({ executable = "C:\\Users\\u\\AppData\\Local\\Programs\\OpenMausBot\\OpenMausBot.exe" } = {}) {
- const fs = memoryFs(path.win32);
- const shortcuts = [];
- const shell = {
- writeShortcutLink(file, operation, options) {
- if (fs.entries.get(path.win32.dirname(file))?.type !== "dir") return false;
- shortcuts.push([file, operation, options]);
- fs.entries.set(file, { type: "file", data: Buffer.from(JSON.stringify(options)) });
- return true;
- },
- readShortcutLink(file) { return JSON.parse(fs.text(file)); },
- };
- const options = { platform: "win32", path: path.win32, home: "C:\\Users\\u", userData: "C:\\Users\\u\\AppData\\Roaming\\OpenMausBot", appData: "C:\\Users\\u\\AppData\\Roaming", desktop: "C:\\Users\\u\\Desktop", fs, shell, executable, resizePng: async (png) => png };
- return { fs, shortcuts, options, installer: createAppInstaller(options), dir: "C:\\Users\\u\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\MausBot Apps" };
-}
-
-function linux({ executable = "/home/u/Apps/OpenMausBot.AppImage" } = {}) {
- const fs = memoryFs(path.posix);
- const options = { platform: "linux", path: path.posix, home: "/home/u", userData: "/home/u/.config/OpenMausBot", fs, executable };
- return { fs, options, installer: createAppInstaller(options), dir: "/home/u/.local/share/applications" };
-}
-
test("launcher names are safe file names on macOS, Windows and Linux", () => {
const table = [
["Notes", "Notes"],
@@ -188,7 +100,7 @@ test("icons: PNG checks, a one-image .ico, and a letter tile", () => {
test("macOS: a bundle in ~/Applications/MausBot Apps with its plist, script and icon", async () => {
const { fs, calls, installer, dir } = mac();
const result = await installer.installApp({ id: L("notes"), name: "Notes", iconPng: PNG });
- assert.deepEqual(result, { ok: true, app: { id: L("notes"), name: "Notes", path: `${dir}/Notes.app` } });
+ assert.deepEqual(result, { ok: true, app: { id: L("notes"), name: "Notes", path: `${dir}/Notes.app`, desktop: false } });
const bundle = `${dir}/Notes.app/Contents`;
assert.equal(macPlistAppId(fs.text(`${bundle}/Info.plist`)), L("notes"));
assert.match(fs.text(`${bundle}/Info.plist`), /CFBundleIconFile/);
@@ -199,7 +111,7 @@ test("macOS: a bundle in ~/Applications/MausBot Apps with its plist, script and
assert.equal(calls.filter(([f]) => f === "/usr/bin/sips").length, 10);
assert.deepEqual(calls.at(-1).slice(0, 4), ["/usr/bin/iconutil", "-c", "icns", "-o"]);
assert.ok(calls.at(-1)[4].endsWith("AppIcon.icns") && calls.at(-1)[5].endsWith("icon.iconset"));
- assert.deepEqual(await installer.installedApps(), [{ id: L("notes"), name: "Notes", path: `${dir}/Notes.app` }]);
+ assert.deepEqual(await installer.installedApps(), [{ id: L("notes"), name: "Notes", path: `${dir}/Notes.app`, desktop: false }]);
assert.equal(await installer.isInstalled(L("notes")), true);
assert.equal(await installer.isInstalled(L("other")), false);
assert.equal(fs.files().some((f) => f.includes("/work/") || f.includes(".staging")), false);
@@ -295,7 +207,7 @@ test("refusals: unavailable when off, a bad id, and an unreadable list starts ag
});
test("Windows: a Start menu shortcut to MausBot's executable with the link, its own taskbar id and icon", async () => {
- const { fs, shortcuts, installer, dir, options } = windows();
+ const { fs, shortcuts, installer, dir, options } = windows({ makeDesktop: true });
const result = await installer.installApp({ id: L("notes"), name: "Notes", iconPng: PNG });
assert.equal(result.app.path, `${dir}\\Notes.lnk`);
const [file, operation, link] = shortcuts[0];
@@ -307,7 +219,7 @@ test("Windows: a Start menu shortcut to MausBot's executable with the link, its
assert.match(link.icon, /^C:\\Users\\u\\AppData\\Roaming\\OpenMausBot\\app-install\\icons\\[0-9a-f]{16}\.ico$/);
assert.deepEqual([...fs.entries.get(link.icon).data.subarray(0, 4)], [0, 0, 1, 0]);
assert.equal(shortcuts.length, 1);
- assert.equal(fs.entries.has("C:\\Users\\u\\Desktop"), false);
+ assert.equal(fs.files().some((f) => f.startsWith("C:\\Users\\u\\Desktop\\")), false);
await installer.installApp({ id: L("notes"), name: "Notes", desktopShortcut: true });
assert.deepEqual(shortcuts.slice(1).map(([f, op]) => [f, op]), [[`${dir}\\Notes.lnk`, "replace"], ["C:\\Users\\u\\Desktop\\Notes.lnk", "create"]]);
@@ -379,7 +291,7 @@ test("calls run one at a time, so two installs of one name never pick the same f
assert.deepEqual([a.app.name, b.app.name], ["Same", "Same 2"]);
});
-test("IPC: four guarded channels that pass on only what the installer takes", async () => {
+test("IPC: six guarded channels that pass on only what the installer takes", async () => {
const handlers = new Map();
const guarded = [];
const seen = [];
@@ -389,9 +301,13 @@ test("IPC: four guarded channels that pass on only what the installer takes", as
uninstallApp: async (id) => { seen.push(id); return { ok: true }; },
installedApps: async () => [{ id: L("a"), name: "A", path: "/p" }],
cleanup: async (ids) => { seen.push(["cleanup", ids]); return []; },
+ addToDesktop: async (id) => { seen.push(["add", id]); return { ok: true }; },
+ removeFromDesktop: async (id) => { seen.push(["remove", id]); return { ok: true }; },
};
installAppInstall({ ipcMain: { handle: (channel, fn) => handlers.set(channel, fn) }, guard: (channel, fn) => { guarded.push(channel); return fn; }, installer });
- assert.deepEqual([...handlers.keys()], ["app-install:install", "app-install:uninstall", "app-install:list", "app-install:cleanup"]);
+ assert.deepEqual([...handlers.keys()], [
+ "app-install:install", "app-install:uninstall", "app-install:add-to-desktop", "app-install:remove-from-desktop", "app-install:list", "app-install:cleanup",
+ ]);
assert.deepEqual(guarded, [...handlers.keys()]);
await handlers.get("app-install:install")({}, { id: L("a"), name: "x".repeat(600), iconPng: "x", desktopShortcut: 1, extra: true });
await handlers.get("app-install:uninstall")({}, { id: L("a") });
@@ -401,6 +317,12 @@ test("IPC: four guarded channels that pass on only what the installer takes", as
await handlers.get("app-install:cleanup")({}, [L("a")]);
for (const bad of [undefined, null, "x", [1], { length: 1 }]) assert.deepEqual(await handlers.get("app-install:cleanup")({}, bad), []);
assert.deepEqual(seen, [["cleanup", [L("a")]]]);
+ seen.length = 0;
+ await handlers.get("app-install:add-to-desktop")({}, L("a"));
+ await handlers.get("app-install:add-to-desktop")({}, { id: L("a") });
+ await handlers.get("app-install:remove-from-desktop")({}, L("a"));
+ await handlers.get("app-install:remove-from-desktop")({}, 7);
+ assert.deepEqual(seen, [["add", L("a")], ["add", ""], ["remove", L("a")], ["remove", ""]]);
});
test("Windows: an installed app's own window takes its launcher's taskbar details; nothing elsewhere or uninstalled", async () => {
diff --git a/electron/app-install/desktop.mjs b/electron/app-install/desktop.mjs
new file mode 100644
index 0000000000..09cb0f9ecd
--- /dev/null
+++ b/electron/app-install/desktop.mjs
@@ -0,0 +1,73 @@
+// An installed app's icon on the person's Desktop: on macOS a second copy of its small launcher bundle, on Windows a
+// second shortcut, on Linux a second, executable desktop entry. Each carries the same id marker as the launcher.
+//
+// Security invariants: the Desktop folder is never created, and nothing is written outside it; an item is replaced
+// only when it is this app's own (the installer's `chooseName` and `ownedBy`).
+import { desktopEntry } from "./launchers.mjs";
+
+const STAGING = /^\.mausbot-[0-9a-f]{16}\.staging$/;
+
+export const isDesktopFile = (file) => file?.desktop === true;
+
+/**
+ * `desktop`: the folder Electron names (`app.getPath("desktop")`, which follows an iCloud Drive or OneDrive redirection).
+ * On Linux the folder is `xdg-user-dir DESKTOP`, else ~/Desktop. `ctx` is the installer's own: `chooseName`,
+ * `placeMacBundle`, `writeShortcut`, `readBytes`.
+ */
+export function createDesktopItems({ platform, path, fs, home, run, desktop, executable, log }, ctx) {
+ async function xdgDesktop() {
+ if (!run) return null;
+ try {
+ const result = await run("xdg-user-dir", ["DESKTOP"]);
+ const out = result?.code === 0 ? String(result.stdout ?? "").trim() : "";
+ // xdg-user-dir prints $HOME itself when no Desktop folder is set.
+ return out && !out.includes("\n") && path.isAbsolute(out) && path.resolve(out) !== path.resolve(home) ? out : null;
+ } catch {
+ return null;
+ }
+ }
+
+ /** The Desktop folder when it exists as a folder, else null. */
+ async function folder() {
+ const dir = platform === "linux" ? (await xdgDesktop()) ?? (home ? path.join(home, "Desktop") : null) : desktop || null;
+ if (!dir || !path.isAbsolute(dir) || (home && path.resolve(dir) === path.resolve(home))) return null;
+ try { return (await fs.stat(dir)).isDirectory() ? path.resolve(dir) : null; } catch { return null; }
+ }
+
+ /** Writes the app's Desktop item into `dir` from its installed `entry`; null when every name is taken. */
+ async function write(manifest, id, entry, dir) {
+ const icon = entry.files?.find((f) => f.kind === "icon")?.path;
+ if (platform === "darwin") {
+ const launcher = entry.files?.find((f) => f.kind === "bundle" && !isDesktopFile(f))?.path;
+ const icns = launcher ? await ctx.readBytes(path.join(launcher, "Contents", "Resources", "AppIcon.icns")) : null;
+ const chosen = await ctx.chooseName(manifest, id, dir, entry.name, ".app", "bundle");
+ if (!chosen) return null;
+ const bundle = await ctx.placeMacBundle(id, dir, chosen, async (out) => {
+ if (!icns) return false;
+ await fs.writeFile(out, icns);
+ return true;
+ });
+ return bundle ? { path: bundle, kind: "bundle", desktop: true } : null;
+ }
+ if (platform === "win32") {
+ const written = await ctx.writeShortcut(manifest, id, dir, entry.name, icon, { create: false });
+ return written ? { ...written.file, desktop: true } : null;
+ }
+ const chosen = await ctx.chooseName(manifest, id, dir, entry.name, ".desktop", "desktop-entry");
+ if (!chosen) return null;
+ const file = path.join(dir, `${chosen}.desktop`);
+ await fs.writeFile(file, desktopEntry({ id, name: entry.name, executable, iconPath: icon }), { mode: 0o755 });
+ await fs.chmod?.(file, 0o755);
+ return { path: file, kind: "desktop-entry", desktop: true };
+ }
+
+ /** Leftover staging folders of a Desktop bundle that was being written when MausBot stopped. */
+ async function sweep(dir) {
+ if (platform !== "darwin" || !dir) return;
+ for (const name of await fs.readdir(dir).catch(() => [])) {
+ if (STAGING.test(name)) await fs.rm(path.join(dir, name), { recursive: true, force: true }).catch((error) => log(`[app-install] left ${name}: ${error?.message ?? error}`));
+ }
+ }
+
+ return { folder, write, sweep };
+}
diff --git a/electron/app-install/installer.mjs b/electron/app-install/installer.mjs
index f3752bc57f..ac88d7fa83 100644
--- a/electron/app-install/installer.mjs
+++ b/electron/app-install/installer.mjs
@@ -1,24 +1,27 @@
// Installs a saved app as a launcher of its own on this computer: a bundle in ~/Applications/MausBot Apps on macOS, a
-// Start menu shortcut in "MausBot Apps" on Windows, a desktop entry in ~/.local/share/applications on Linux. Each one
-// opens openmausbot://app/<id>?window=1: the app in a window of its own in MausBot.
+// Start menu shortcut in "MausBot Apps" on Windows, a desktop entry in ~/.local/share/applications on Linux, and, when
+// asked, a copy of it on the Desktop. Each one opens openmausbot://app/<id>?window=1: the app in a window of its own.
//
-// Security invariants: nothing is written outside those folders, this app's own data folder and, on Linux, its icon
-// folder; an existing file is replaced or removed only when it names the same app id inside it (a bundle's Info.plist,
-// a desktop entry's key, a shortcut's argument), so a launcher the person made or renamed into place is never touched.
+// Security invariants: nothing is written outside those folders, the Desktop folder, this app's own data folder and,
+// on Linux, its icon folder; an existing file is replaced or removed only when it names the same app id inside it (a
+// bundle's Info.plist, a desktop entry's key, a shortcut's argument), so a launcher the person made or renamed into
+// place is never touched.
import { firstFreeName, launcherName, nameKey, validAppId, appKey, launcherLink, FOLDER_NAME } from "./names.mjs";
import { MAC_ICONSET, icoFromPng, letterTilePng, pngSize } from "./icons.mjs";
import {
MAC_EXECUTABLE, MAC_ICON, desktopEntry, desktopEntryAppId, macInfoPlist, macLauncherScript, macPlistAppId, windowsShortcut, windowsWindowDetails,
} from "./launchers.mjs";
+import { createDesktopItems, isDesktopFile } from "./desktop.mjs";
const MANIFEST = "installed.json";
/**
* `platform`, `path` (the platform's flavour), `home`, `userData` (this app's data folder), `appData` (Windows roaming
- * folder) and `desktop` (Windows desktop folder), `dataHome` (Linux XDG data folder), `executable` (MausBot's own
- * executable or AppImage), `hostBundleId` (MausBot's macOS bundle id), `enabled` (false in an unpackaged build), and the
- * effects: `fs` (node:fs/promises shape), `run(file, args)` resolving `{ code }`, `shell` (Electron's: `trashItem`,
- * `writeShortcutLink`, `readShortcutLink`), `resizePng(png, side)` returning a PNG or null, `log(line)`.
+ * folder), `desktop` (the Desktop folder on macOS and Windows; Linux asks xdg-user-dir), `dataHome` (Linux XDG data
+ * folder), `executable` (MausBot's own executable or AppImage), `hostBundleId` (MausBot's macOS bundle id), `enabled`
+ * (false in an unpackaged build), and the effects: `fs` (node:fs/promises shape), `run(file, args)` resolving
+ * `{ code, stdout }`, `shell` (Electron's: `trashItem`, `writeShortcutLink`, `readShortcutLink`), `resizePng(png, side)`
+ * returning a PNG or null, `log(line)`.
*/
export function createAppInstaller(options) {
const { platform, path, home, userData, fs, run = null, shell = {}, resizePng = null, log = () => {} } = options;
@@ -30,7 +33,7 @@ export function createAppInstaller(options) {
const dataHome = options.dataHome || path.join(home ?? "", ".local", "share");
const roots = {
darwin: { launchers: path.join(home ?? "", "Applications", FOLDER_NAME) },
- win32: { launchers: path.join(options.appData ?? "", "Microsoft", "Windows", "Start Menu", "Programs", FOLDER_NAME), desktop: options.desktop || null },
+ win32: { launchers: path.join(options.appData ?? "", "Microsoft", "Windows", "Start Menu", "Programs", FOLDER_NAME) },
linux: { launchers: path.join(dataHome, "applications"), icons: path.join(dataHome, "icons", "mausbot-apps") },
}[platform] ?? {};
@@ -39,10 +42,14 @@ export function createAppInstaller(options) {
const rel = path.relative(dir, file);
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel) && !rel.includes(path.sep);
};
- const allowed = (file) => Object.values(roots).some((dir) => childOf(dir, file)) || childOf(path.join(stateDir, "icons"), file);
+ /** The Desktop folder as last resolved; null when there is none. */
+ let desktopRoot = null;
+ const allowed = (file) => Object.values(roots).some((dir) => childOf(dir, file)) || childOf(path.join(stateDir, "icons"), file)
+ || childOf(desktopRoot, file);
const lstat = async (file) => { try { return await fs.lstat(file); } catch { return null; } };
const readText = async (file) => { try { return String(await fs.readFile(file, "utf8")); } catch { return null; } };
+ const readBytes = async (file) => { try { return Buffer.from(await fs.readFile(file)); } catch { return null; } };
async function readManifest() {
const text = await readText(manifestFile);
@@ -78,7 +85,8 @@ export function createAppInstaller(options) {
* skipped even where the file system tells case or Unicode form apart. */
function chooseName(manifest, id, dir, base, ext, kind) {
const others = new Set(Object.entries(manifest.apps).filter(([other]) => other !== id)
- .flatMap(([, entry]) => (entry.files ?? []).filter((f) => f.kind === kind).map((f) => nameKey(path.basename(f.path)))));
+ .flatMap(([, entry]) => (entry.files ?? []).filter((f) => f.kind === kind && nameKey(path.dirname(f.path)) === nameKey(dir))
+ .map((f) => nameKey(path.basename(f.path)))));
return firstFreeName(base, async (candidate) => {
const file = path.join(dir, `${candidate}${ext}`);
if (others.has(nameKey(`${candidate}${ext}`))) return false;
@@ -131,31 +139,46 @@ export function createAppInstaller(options) {
}
}
+ /** Builds `<chosen>.app` in `dir` beside it and moves it into place; null when that name is not this app's own.
+ * `writeIcon(file)` writes the .icns and says whether it did. */
+ async function placeMacBundle(id, dir, chosen, writeIcon) {
+ const bundle = path.join(dir, `${chosen}.app`);
+ const staging = path.join(dir, `.mausbot-${appKey(id)}.staging`);
+ await fs.rm(staging, { recursive: true, force: true });
+ try {
+ await fs.mkdir(staging);
+ await fs.mkdir(path.join(staging, "Contents", "MacOS"), { recursive: true });
+ await fs.mkdir(path.join(staging, "Contents", "Resources"), { recursive: true });
+ const icon = await writeIcon(path.join(staging, "Contents", "Resources", `${MAC_ICON}.icns`));
+ await fs.writeFile(path.join(staging, "Contents", "Info.plist"), macInfoPlist({ id, name: chosen, hostBundleId: options.hostBundleId, icon }));
+ await fs.writeFile(path.join(staging, "Contents", "PkgInfo"), "APPL????");
+ await fs.writeFile(path.join(staging, "Contents", "MacOS", MAC_EXECUTABLE), macLauncherScript({ id, hostBundleId: options.hostBundleId }), { mode: 0o755 });
+ await fs.chmod?.(path.join(staging, "Contents", "MacOS", MAC_EXECUTABLE), 0o755);
+ if (await lstat(bundle)) {
+ if (!(await ownedBy(id, bundle, "bundle"))) { await fs.rm(staging, { recursive: true, force: true }); return null; }
+ await fs.rm(bundle, { recursive: true, force: true });
+ }
+ await fs.rename(staging, bundle);
+ return bundle;
+ } catch (error) {
+ await fs.rm(staging, { recursive: true, force: true }).catch(() => {});
+ throw error;
+ }
+ }
+
async function installMac(manifest, { id, name, iconPng }) {
const dir = roots.launchers;
await fs.mkdir(dir, { recursive: true });
const chosen = await chooseName(manifest, id, dir, name, ".app", "bundle");
if (!chosen) return { error: "taken" };
- const bundle = path.join(dir, `${chosen}.app`);
- const staging = path.join(dir, `.mausbot-${appKey(id)}.staging`);
- await fs.rm(staging, { recursive: true, force: true });
- await fs.mkdir(path.join(staging, "Contents", "MacOS"), { recursive: true });
- await fs.mkdir(path.join(staging, "Contents", "Resources"), { recursive: true });
- const icon = await macIcon(id, iconSource(id, name, iconPng, 1024), path.join(staging, "Contents", "Resources", `${MAC_ICON}.icns`));
- await fs.writeFile(path.join(staging, "Contents", "Info.plist"), macInfoPlist({ id, name: chosen, hostBundleId: options.hostBundleId, icon }));
- await fs.writeFile(path.join(staging, "Contents", "PkgInfo"), "APPL????");
- await fs.writeFile(path.join(staging, "Contents", "MacOS", MAC_EXECUTABLE), macLauncherScript({ id, hostBundleId: options.hostBundleId }), { mode: 0o755 });
- await fs.chmod?.(path.join(staging, "Contents", "MacOS", MAC_EXECUTABLE), 0o755);
- if (await lstat(bundle)) {
- if (!(await ownedBy(id, bundle, "bundle"))) { await fs.rm(staging, { recursive: true, force: true }); return { error: "taken" }; }
- await fs.rm(bundle, { recursive: true, force: true });
- }
- await fs.rename(staging, bundle);
+ const bundle = await placeMacBundle(id, dir, chosen, (out) => macIcon(id, iconSource(id, name, iconPng, 1024), out));
+ if (!bundle) return { error: "taken" };
return { name: chosen, files: [{ path: bundle, kind: "bundle" }] };
}
- async function writeShortcut(manifest, id, dir, name, iconPath) {
- await fs.mkdir(dir, { recursive: true });
+ /** `create: false` (the Desktop): the folder must already be there. */
+ async function writeShortcut(manifest, id, dir, name, iconPath, { create = true } = {}) {
+ if (create) await fs.mkdir(dir, { recursive: true });
const chosen = await chooseName(manifest, id, dir, name, ".lnk", "shortcut");
if (!chosen) return null;
const file = path.join(dir, `${chosen}.lnk`);
@@ -166,7 +189,7 @@ export function createAppInstaller(options) {
return { name: chosen, file: { path: file, kind: "shortcut" } };
}
- async function installWindows(manifest, { id, name, iconPng, desktopShortcut }) {
+ async function installWindows(manifest, { id, name, iconPng }) {
const iconDir = path.join(stateDir, "icons");
await fs.mkdir(iconDir, { recursive: true });
const iconPath = path.join(iconDir, `${appKey(id)}.ico`);
@@ -177,12 +200,7 @@ export function createAppInstaller(options) {
} catch (error) { log(`[app-install] no icon for ${id}: ${error?.message ?? error}`); }
const start = await writeShortcut(manifest, id, roots.launchers, name, icon?.path);
if (!start) return { error: "taken" };
- const files = [start.file, ...(icon ? [icon] : [])];
- if (desktopShortcut === true && roots.desktop) {
- const onDesktop = await writeShortcut(manifest, id, roots.desktop, name, icon?.path);
- if (onDesktop) files.push(onDesktop.file);
- }
- return { name: start.name, files };
+ return { name: start.name, files: [start.file, ...(icon ? [icon] : [])] };
}
async function installLinux(manifest, { id, name, iconPng }) {
@@ -207,21 +225,44 @@ export function createAppInstaller(options) {
return next;
};
- const launcherOf = (entry) => entry.files?.find((f) => f.kind !== "icon")?.path ?? null;
- const view = (id, entry) => ({ id, name: entry.name, path: launcherOf(entry) });
+ const launcherOf = (entry) => entry?.files?.find((f) => f.kind !== "icon" && !isDesktopFile(f)) ?? null;
+ const ownedFile = async (id, file) => Boolean(file && (await ownedBy(id, file.path, file.kind)));
+ async function onDesktop(id, entry) {
+ for (const file of (entry?.files ?? []).filter(isDesktopFile)) if (await ownedFile(id, file)) return true;
+ return false;
+ }
+ const view = (id, entry, desktop) => ({ id, name: entry.name, path: launcherOf(entry)?.path ?? null, desktop });
async function present(manifest) {
const out = [];
for (const [id, entry] of Object.entries(manifest.apps)) {
- const launcher = entry.files?.find((f) => f.kind !== "icon");
- if (launcher && (await ownedBy(id, launcher.path, launcher.kind))) out.push(view(id, entry));
+ if (await ownedFile(id, launcherOf(entry))) out.push(view(id, entry, await onDesktop(id, entry)));
}
return out;
}
+ const desktopItems = createDesktopItems({ platform, path, fs, home, run, desktop: options.desktop, executable: options.executable, log },
+ { chooseName, placeMacBundle, writeShortcut, readBytes });
+ const resolveDesktop = async () => { desktopRoot = await desktopItems.folder(); return desktopRoot; };
+
+ /** The app's Desktop item from its installed `entry`: `{ file }`, or `{ error }` with "no-desktop", "taken" or
+ * "failed". A missing Desktop folder is never made. */
+ async function writeDesktop(manifest, id, entry) {
+ const dir = await resolveDesktop();
+ if (!dir) return { error: "no-desktop" };
+ try {
+ const file = await desktopItems.write(manifest, id, entry, dir);
+ return file ? { file } : { error: "taken" };
+ } catch (error) {
+ log(`[app-install] could not put ${id} on the Desktop: ${error?.message ?? error}`);
+ return { error: "failed" };
+ }
+ }
+
async function uninstallLocked(manifest, id) {
const entry = manifest.apps[id];
if (!entry) return { ok: true, removed: false };
+ if (entry.files?.some(isDesktopFile)) await resolveDesktop();
const left = [];
for (const file of entry.files ?? []) if (!(await removeOwned(id, file).catch(() => false))) left.push(file.path);
delete manifest.apps[id];
@@ -232,9 +273,10 @@ export function createAppInstaller(options) {
return {
available: () => enabled,
- /** `{ id, name, iconPng?, desktopShortcut? }` → `{ ok: true, app: { id, name, path } }` or `{ ok: false, reason }`
- * with reason "unavailable", "invalid-id", "taken" or "failed". Installing again replaces the launcher; a new name
- * writes the new one and then removes the old. */
+ /** `{ id, name, iconPng?, desktopShortcut? }` → `{ ok: true, app: { id, name, path, desktop } }` or `{ ok: false,
+ * reason }` with reason "unavailable", "invalid-id", "taken" or "failed". Installing again replaces the launcher and
+ * a Desktop item still there; a new name writes the new ones and then removes the old. `desktopShortcut` also puts
+ * one on the Desktop, which never fails the install. */
installApp: (input) => serial(async () => {
if (!enabled) return { ok: false, reason: "unavailable" };
const id = input?.id;
@@ -253,11 +295,21 @@ export function createAppInstaller(options) {
return { ok: false, reason: "failed" };
}
if (written.error) return { ok: false, reason: written.error };
- const kept = new Set(written.files.map((f) => nameKey(f.path)));
+ const files = [...written.files];
+ const before = (previous?.files ?? []).filter(isDesktopFile);
+ if (input?.desktopShortcut === true || (await onDesktop(id, previous))) {
+ const desktop = await writeDesktop(manifest, id, { name: written.name, files });
+ if (desktop.file) files.push(desktop.file);
+ else {
+ log(`[app-install] ${id} kept its Desktop item as it was: ${desktop.error}`);
+ for (const file of before) if (await ownedFile(id, file)) files.push(file);
+ }
+ } else if (before.length) await resolveDesktop();
+ const kept = new Set(files.map((f) => nameKey(f.path)));
for (const file of previous?.files ?? []) if (!kept.has(nameKey(file.path))) await removeOwned(id, file).catch(() => false);
- manifest.apps[id] = { name: written.name, files: written.files, ...(options.executable ? { target: options.executable } : {}) };
+ manifest.apps[id] = { name: written.name, files, ...(options.executable ? { target: options.executable } : {}) };
await writeManifest(manifest);
- return { ok: true, app: view(id, manifest.apps[id]) };
+ return { ok: true, app: view(id, manifest.apps[id], files.some(isDesktopFile)) };
}),
/** Removes only this app's own launcher files; on macOS the bundle goes to the Trash when it can. */
@@ -266,7 +318,39 @@ export function createAppInstaller(options) {
return uninstallLocked(await readManifest(), id);
}),
- /** The launchers still on disk as this app wrote them, `{ id, name, path }` each. */
+ /** An installed app's icon on the Desktop → `{ ok: true, app }` or `{ ok: false, reason }` with "unavailable",
+ * "invalid-id", "not-installed", "no-desktop" (no Desktop folder), "taken" or "failed". The launcher stays as it is
+ * whatever happens here. */
+ addToDesktop: (id) => serial(async () => {
+ if (!enabled) return { ok: false, reason: "unavailable" };
+ if (!validAppId(id)) return { ok: false, reason: "invalid-id" };
+ const manifest = await readManifest();
+ const entry = manifest.apps[id];
+ if (!(await ownedFile(id, launcherOf(entry)))) return { ok: false, reason: "not-installed" };
+ if (await onDesktop(id, entry)) return { ok: true, app: view(id, entry, true) };
+ const desktop = await writeDesktop(manifest, id, entry);
+ if (desktop.error) return { ok: false, reason: desktop.error };
+ entry.files = [...entry.files.filter((f) => !isDesktopFile(f)), desktop.file];
+ await writeManifest(manifest);
+ return { ok: true, app: view(id, entry, true) };
+ }),
+
+ /** Removes only this app's own Desktop item; the launcher stays. */
+ removeFromDesktop: (id) => serial(async () => {
+ if (!validAppId(id)) return { ok: false, reason: "invalid-id" };
+ const manifest = await readManifest();
+ const entry = manifest.apps[id];
+ const items = (entry?.files ?? []).filter(isDesktopFile);
+ if (!items.length) return { ok: true, removed: false };
+ await resolveDesktop();
+ const left = [];
+ for (const file of items) if (!(await removeOwned(id, file).catch(() => false))) left.push(file.path);
+ entry.files = entry.files.filter((f) => !isDesktopFile(f));
+ await writeManifest(manifest);
+ return { ok: true, removed: true, ...(left.length ? { left } : {}) };
+ }),
+
+ /** The launchers still on disk as this app wrote them, `{ id, name, path, desktop }` each. */
installedApps: () => serial(async () => (enabled ? present(await readManifest()) : [])),
/** On Windows, what the app's own window gives the taskbar so it shows as its installed launcher (its own button,
@@ -281,9 +365,7 @@ export function createAppInstaller(options) {
isInstalled: (id) => serial(async () => {
if (!enabled || !validAppId(id)) return false;
- const entry = (await readManifest()).apps[id];
- const launcher = entry?.files?.find((f) => f.kind !== "icon");
- return Boolean(launcher && (await ownedBy(id, launcher.path, launcher.kind)));
+ return ownedFile(id, launcherOf((await readManifest()).apps[id]));
}),
/** Removes the launchers of apps that no longer exist (`ids`: every saved app's id, an array; anything else, such as
@@ -293,6 +375,8 @@ export function createAppInstaller(options) {
const keep = new Set(ids);
const manifest = await readManifest();
const removed = [];
+ // Only where a Desktop item was made: reading the Desktop folder asks the person for access on macOS.
+ if (Object.values(manifest.apps).some((entry) => entry.files?.some(isDesktopFile))) await desktopItems.sweep(await resolveDesktop());
for (const id of Object.keys(manifest.apps)) {
if (keep.has(id)) continue;
await uninstallLocked(manifest, id);
@@ -314,12 +398,17 @@ export function createAppInstaller(options) {
if (!enabled || platform === "darwin") return [];
const manifest = await readManifest();
const refreshed = [];
+ if (Object.values(manifest.apps).some((entry) => entry.target !== options.executable && entry.files?.some(isDesktopFile))) await resolveDesktop();
for (const [id, entry] of Object.entries(manifest.apps)) {
if (entry.target === options.executable) continue;
const icon = entry.files.find((f) => f.kind === "icon")?.path;
for (const file of entry.files) {
if (file.kind === "icon" || !allowed(file.path) || !(await ownedBy(id, file.path, file.kind))) continue;
- if (file.kind === "desktop-entry") await fs.writeFile(file.path, desktopEntry({ id, name: entry.name, executable: options.executable, iconPath: icon }), { mode: 0o644 });
+ if (file.kind === "desktop-entry") {
+ const mode = isDesktopFile(file) ? 0o755 : 0o644;
+ await fs.writeFile(file.path, desktopEntry({ id, name: entry.name, executable: options.executable, iconPath: icon }), { mode });
+ await fs.chmod?.(file.path, mode);
+ }
else shell.writeShortcutLink(file.path, "replace", windowsShortcut({ id, name: entry.name, executable: options.executable, iconPath: icon }));
}
entry.target = options.executable;
diff --git a/electron/app-install/ipc.mjs b/electron/app-install/ipc.mjs
index 0f01e79bb4..5bc851854b 100644
--- a/electron/app-install/ipc.mjs
+++ b/electron/app-install/ipc.mjs
@@ -15,13 +15,15 @@ export function installAppInstall({ ipcMain, guard, installer }) {
return installer.installApp({ id, name, iconPng, desktopShortcut: input?.desktopShortcut === true });
}));
ipcMain.handle("app-install:uninstall", guard("app-install:uninstall", (_event, id) => installer.uninstallApp(typeof id === "string" ? id : "")));
+ ipcMain.handle("app-install:add-to-desktop", guard("app-install:add-to-desktop", (_event, id) => installer.addToDesktop(typeof id === "string" ? id : "")));
+ ipcMain.handle("app-install:remove-from-desktop", guard("app-install:remove-from-desktop", (_event, id) => installer.removeFromDesktop(typeof id === "string" ? id : "")));
ipcMain.handle("app-install:list", guard("app-install:list", async () => ({ available: installer.available(), apps: await installer.installedApps() })));
// `ids`: every saved app's id, from the page that just read the whole list; anything else removes nothing.
ipcMain.handle("app-install:cleanup", guard("app-install:cleanup", (_event, ids) =>
(Array.isArray(ids) && ids.length <= 10_000 && ids.every((id) => typeof id === "string") ? installer.cleanup(ids) : [])));
}
-/** Main's wiring: the real folders, Electron's shell and image tools, and `execFile` for sips and iconutil. */
+/** Main's wiring: the real folders, Electron's shell and image tools, and `execFile` for sips, iconutil and xdg-user-dir. */
export function createDesktopAppInstaller({ app, shell, nativeImage, env, platform, log }) {
const userData = app.getPath("userData");
const executable = platform === "linux" ? env.APPIMAGE || process.execPath : process.execPath;
@@ -31,7 +33,7 @@ export function createDesktopAppInstaller({ app, shell, nativeImage, env, platfo
home: app.getPath("home"),
userData,
appData: platform === "win32" ? app.getPath("appData") : null,
- desktop: platform === "win32" ? app.getPath("desktop") : null,
+ desktop: platform === "linux" ? null : desktopFolder(app),
dataHome: env.XDG_DATA_HOME && path.isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : null,
executable,
hostBundleId: hostBundleId(platform),
@@ -39,7 +41,7 @@ export function createDesktopAppInstaller({ app, shell, nativeImage, env, platfo
fs: fs.promises,
shell,
run: (file, args) => new Promise((resolve) => {
- execFile(file, args, { timeout: 20_000 }, (error) => resolve({ code: error ? (typeof error.code === "number" ? error.code : 1) : 0 }));
+ execFile(file, args, { timeout: 20_000 }, (error, stdout) => resolve({ code: error ? (typeof error.code === "number" ? error.code : 1) : 0, stdout: String(stdout ?? "") }));
}),
resizePng: (png, side) => {
const image = nativeImage.createFromBuffer(Buffer.from(png));
@@ -51,6 +53,10 @@ export function createDesktopAppInstaller({ app, shell, nativeImage, env, platfo
return installer;
}
+function desktopFolder(app) {
+ try { return app.getPath("desktop"); } catch { return null; }
+}
+
function hostBundleId(platform) {
if (platform !== "darwin") return undefined;
try {
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 15874ba566..e1b807f212 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -514,12 +514,15 @@ const bridge = {
},
/** Saved apps as launchers on this computer: this app's own page only (never REMOTE_SAFE; main checks the sender
- * again). `install({ id, name, iconPng?, desktopShortcut? })`, `uninstall(id)`, `list()`, `cleanup(ids)` (every saved app's id). */
+ * again). `install({ id, name, iconPng?, desktopShortcut? })`, `uninstall(id)`, `addToDesktop(id)`, `removeFromDesktop(id)`,
+ * `list()`, `cleanup(ids)` (every saved app's id). */
appInstall: {
install: (input) => ipcRenderer.invoke("app-install:install", {
id: input?.id, name: input?.name, iconPng: iconBytes(input?.iconPng), desktopShortcut: input?.desktopShortcut === true,
}),
uninstall: (id) => ipcRenderer.invoke("app-install:uninstall", id),
+ addToDesktop: (id) => ipcRenderer.invoke("app-install:add-to-desktop", id),
+ removeFromDesktop: (id) => ipcRenderer.invoke("app-install:remove-from-desktop", id),
list: () => ipcRenderer.invoke("app-install:list"),
cleanup: (ids) => ipcRenderer.invoke("app-install:cleanup", Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : null),
},
diff --git a/electron/preload.node-test.mjs b/electron/preload.node-test.mjs
index b91ef8bf49..caade70f94 100644
--- a/electron/preload.node-test.mjs
+++ b/electron/preload.node-test.mjs
@@ -97,12 +97,16 @@ test("appInstall asks main over its own channels with only the fields it underst
const view = new DataView(new Uint8Array([9, 8]).buffer);
await exposed.api.appInstall.install({ id: "notes", name: "Notes", iconPng: view });
await exposed.api.appInstall.uninstall("notes");
+ await exposed.api.appInstall.addToDesktop("notes");
+ await exposed.api.appInstall.removeFromDesktop("notes");
await exposed.api.appInstall.list();
assert.deepEqual(invocations.slice(before), [
["app-install:install", { id: "notes", name: "Notes", iconPng: icon, desktopShortcut: false }],
["app-install:install", { id: "notes", name: "Notes", iconPng: undefined, desktopShortcut: false }],
["app-install:install", { id: "notes", name: "Notes", iconPng: new Uint8Array([9, 8]), desktopShortcut: false }],
["app-install:uninstall", "notes"],
+ ["app-install:add-to-desktop", "notes"],
+ ["app-install:remove-from-desktop", "notes"],
["app-install:list"],
]);
const source = (await import("node:fs")).readFileSync(new URL("./preload.cjs", import.meta.url), "utf8");
diff --git a/src/components/published-apps/LocalAppCard.tsx b/src/components/published-apps/LocalAppCard.tsx
index 4b49592ed9..299b106324 100644
--- a/src/components/published-apps/LocalAppCard.tsx
+++ b/src/components/published-apps/LocalAppCard.tsx
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from "react";
-import { AppWindowMac, MessageSquare, MonitorDown, MonitorUp, MoreHorizontal, Pencil, Trash2 } from "lucide-react";
+import { AppWindowMac, MessageSquare, MonitorDown, MonitorUp, MoreHorizontal, Pencil, SquareMinus, SquarePlus, Trash2 } from "lucide-react";
import type { LocalApp } from "../../../shared/local-apps";
import { t } from "@/lib/i18n";
@@ -34,12 +34,28 @@ export function InlineName({ name, onDone }: { name: string; onDone: (next: stri
);
}
-/** Install on this computer or Uninstall, for a menu: nothing where the desktop app can't install launchers. */
-export function installItems(install: { installed: boolean; run(): void } | undefined): SidebarMenuItem[] {
+/** What a saved app's menu offers on this computer. `desktop`: absent where this desktop build can't add a Desktop icon. */
+export type InstallActions = { installed: boolean; run(): void; desktop?: { on: boolean; run(): void } };
+
+/** Install on this computer or Uninstall, then Add to Desktop or Remove from Desktop, for a menu: nothing where the
+ * desktop app can't install launchers. */
+export function installItems(install: InstallActions | undefined): SidebarMenuItem[] {
if (!install) return [];
- return [install.installed
- ? { key: "uninstall", label: t("localApps.install.uninstall"), icon: <MonitorUp size={16} />, onSelect: install.run }
- : { key: "install", label: t("localApps.install.install"), icon: <MonitorDown size={16} />, onSelect: install.run }];
+ const { desktop } = install;
+ return [
+ install.installed
+ ? { key: "uninstall", label: t("localApps.install.uninstall"), icon: <MonitorUp size={16} />, onSelect: install.run }
+ : { key: "install", label: t("localApps.install.install"), icon: <MonitorDown size={16} />, onSelect: install.run },
+ ...(!desktop ? [] : desktop.on
+ ? [{ key: "desktop-remove", label: t("localApps.install.removeFromDesktop"), icon: <SquareMinus size={16} />, onSelect: desktop.run }]
+ : [{ key: "desktop-add", label: t("localApps.install.addToDesktop"), icon: <SquarePlus size={16} />, onSelect: desktop.run }]),
+ ];
+}
+
+/** The one line a failed Desktop change shows: installing first failed, or the Desktop item itself. */
+export function desktopFailedText(error: unknown, removing: boolean, name: string): string {
+ if (removing) return t("localApps.install.desktopRemoveFailed", { name });
+ return t(error instanceof Error && error.message === "install" ? "localApps.install.failed" : "localApps.install.desktopFailed", { name });
}
export function InstalledMark() {
@@ -57,7 +73,7 @@ export function LocalAppCard({ app, bot, onOpen, onOpenWindow, onRename, onGoToC
onGoToChat?: () => void;
onRemove: () => void;
/** Present only where this computer can install launchers. */
- install?: { installed: boolean; run(): void };
+ install?: InstallActions;
}) {
const [renaming, setRenaming] = useState(false);
const maker = bot?.name ?? app.bot?.name;
@@ -69,10 +85,10 @@ export function LocalAppCard({ app, bot, onOpen, onOpenWindow, onRename, onGoToC
{ key: "remove", label: t("localApps.card.remove"), icon: <Trash2 size={16} />, separatorBefore: true, onSelect: onRemove },
];
return (
- <li data-local-app={app.id} className="group relative flex min-w-0 flex-col overflow-hidden rounded-2xl border border-hairline/40 bg-card transition-colors duration-[120ms] hover:border-hairline motion-reduce:transition-none">
+ <li data-local-app={app.id} className="group relative flex min-w-0 flex-col rounded-2xl border border-hairline/40 bg-card transition-colors duration-[120ms] hover:border-hairline motion-reduce:transition-none">
<button type="button" onClick={onOpen} aria-label={t("localApps.card.openOf", { name: app.name })} title={app.name}
className="absolute inset-0 z-[1] rounded-2xl focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus" />
- <div className="border-b border-hairline/30">
+ <div className="overflow-hidden rounded-t-2xl border-b border-hairline/30">
<LocalAppThumb app={app} bot={bot} />
</div>
<div className="min-w-0 pb-3 pe-2 ps-3.5 pt-2">
diff --git a/src/components/published-apps/LocalAppView.tsx b/src/components/published-apps/LocalAppView.tsx
index c19f29f7f4..1731627129 100644
--- a/src/components/published-apps/LocalAppView.tsx
+++ b/src/components/published-apps/LocalAppView.tsx
@@ -8,8 +8,8 @@ import { t } from "@/lib/i18n";
import { changeLocalApp, fetchLocalAppDocument, loadLocalApps, useLocalApps } from "@/lib/local-apps";
import type { Bot } from "@/state/store";
import { AppFrame, type AppFrameHandle, type AppFrameProblem } from "../app/AppFrame";
-import { InstalledMark, installItems, LocalAppMark } from "./LocalAppCard";
-import { installLocalApp, readInstalled, uninstallLocalApp, useAppInstall } from "@/lib/local-app-install";
+import { desktopFailedText, InstalledMark, installItems, LocalAppMark, type InstallActions } from "./LocalAppCard";
+import { addLocalAppToDesktop, installLocalApp, readInstalled, removeLocalAppFromDesktop, uninstallLocalApp, useAppInstall } from "@/lib/local-app-install";
import { SidebarPopoverMenu, type SidebarMenuItem } from "../SidebarPopoverMenu";
import { TOOL_PAGE_TITLE, ToolPage, ToolPageActions, ToolPageHeader } from "../ToolPageShell";
@@ -90,11 +90,16 @@ export function LocalAppView({ id, botOf, onBack, onGoToChat, onOpenWindow }: {
const goToChat = app ? onGoToChat?.(app) : undefined;
const title = app?.name ?? "";
const installed = Boolean(app && install?.ids.has(app.id));
- const installOne = app && install?.available ? { installed, run: () => {
+ const onDesktop = Boolean(app && install?.desktop?.has(app.id));
+ const installOne: InstallActions | undefined = app && install?.available ? { installed, run: () => {
setInstallFailed(null);
void (installed ? uninstallLocalApp(app.id) : installLocalApp(app))
.catch(() => setInstallFailed(t(installed ? "localApps.install.uninstallFailed" : "localApps.install.failed", { name: app.name })));
- } } : undefined;
+ }, ...(install.canDesktop ? { desktop: { on: onDesktop, run: () => {
+ setInstallFailed(null);
+ void (onDesktop ? removeLocalAppFromDesktop(app.id) : addLocalAppToDesktop(app))
+ .catch((error: unknown) => setInstallFailed(desktopFailedText(error, onDesktop, app.name)));
+ } } } : {}) } : undefined;
const header = (
<>
diff --git a/src/components/published-apps/LocalApps.test.ts b/src/components/published-apps/LocalApps.test.ts
index 350ad0fe40..7dd6985216 100644
--- a/src/components/published-apps/LocalApps.test.ts
+++ b/src/components/published-apps/LocalApps.test.ts
@@ -309,6 +309,117 @@ describe("installing a saved app on this computer", () => {
});
});
+describe("an installed app's icon on the Desktop", () => {
+ type Bridge = Record<"list" | "install" | "uninstall" | "cleanup" | "addToDesktop" | "removeFromDesktop", ReturnType<typeof vi.fn>>;
+ let bridge: Bridge;
+ let installed: string[];
+ let onDesktop: string[];
+ const order: string[] = [];
+ beforeEach(() => {
+ resetAppInstall();
+ installed = [BOARD.id];
+ onDesktop = [];
+ order.length = 0;
+ bridge = {
+ list: vi.fn(async () => ({ available: true, apps: installed.map((id) => ({ id, name: "x", path: "/p", desktop: onDesktop.includes(id) })) })),
+ install: vi.fn(async (input: { id: string; name: string }) => { order.push(`install ${input.id}`); installed = [...installed, input.id]; return { ok: true, app: { id: input.id, name: input.name, path: "/p" } }; }),
+ uninstall: vi.fn(async (id: string) => { installed = installed.filter((one) => one !== id); onDesktop = onDesktop.filter((one) => one !== id); return { ok: true, removed: true }; }),
+ cleanup: vi.fn(async () => []),
+ addToDesktop: vi.fn(async (id: string) => { order.push(`desktop ${id}`); onDesktop = [...onDesktop, id]; return { ok: true, app: { id, name: "x", path: "/p", desktop: true } }; }),
+ removeFromDesktop: vi.fn(async (id: string) => { onDesktop = onDesktop.filter((one) => one !== id); return { ok: true, removed: true }; }),
+ };
+ vi.stubGlobal("ogb", { appInstall: bridge });
+ });
+
+ it("offers Add to Desktop on the card, and Remove from Desktop once it is there", async () => {
+ await show();
+ act(() => button(card(BOARD.id), "More for Sales board").click());
+ expect(menuItem("Remove from Desktop")).toBeUndefined();
+ await act(async () => menuItem("Add to Desktop").click());
+ await settle();
+ expect(bridge.addToDesktop).toHaveBeenCalledWith(BOARD.id);
+ expect(bridge.install).not.toHaveBeenCalled();
+ act(() => button(card(BOARD.id), "More for Sales board").click());
+ expect(menuItem("Add to Desktop")).toBeUndefined();
+ expect(menuItem("Uninstall")).toBeDefined();
+ await act(async () => menuItem("Remove from Desktop").click());
+ await settle();
+ expect(bridge.removeFromDesktop).toHaveBeenCalledWith(BOARD.id);
+ act(() => button(card(BOARD.id), "More for Sales board").click());
+ expect(menuItem("Add to Desktop")).toBeDefined();
+ expect(document.querySelector("[role=dialog], [role=alertdialog]")).toBeNull();
+ });
+
+ it("installs an app that is not installed yet, then adds it to the Desktop", async () => {
+ await show();
+ act(() => button(card(ROTA.id), "More for Staff rota").click());
+ expect(menuItem("Install on this computer")).toBeDefined();
+ await act(async () => menuItem("Add to Desktop").click());
+ await settle();
+ expect(order).toEqual([`install ${ROTA.id}`, `desktop ${ROTA.id}`]);
+ expect(card(ROTA.id).querySelector("[data-local-app-installed]")).not.toBeNull();
+ act(() => button(card(ROTA.id), "More for Staff rota").click());
+ expect(menuItem("Uninstall")).toBeDefined();
+ expect(menuItem("Remove from Desktop")).toBeDefined();
+ });
+
+ it("says so in one line when the install or the Desktop icon failed, and never adds one after a failed install", async () => {
+ bridge.addToDesktop.mockResolvedValueOnce({ ok: false, reason: "no-desktop" });
+ await show();
+ act(() => button(card(BOARD.id), "More for Sales board").click());
+ await act(async () => menuItem("Add to Desktop").click());
+ await settle();
+ expect([...host.querySelectorAll("[role=alert]")].map((line) => line.textContent)).toEqual(["“Sales board” couldn't be added to the Desktop. Try again."]);
+ bridge.install.mockResolvedValueOnce({ ok: false, reason: "failed" });
+ bridge.addToDesktop.mockClear();
+ act(() => button(card(ROTA.id), "More for Staff rota").click());
+ await act(async () => menuItem("Add to Desktop").click());
+ await settle();
+ expect(bridge.addToDesktop).not.toHaveBeenCalled();
+ expect([...host.querySelectorAll("[role=alert]")].map((line) => line.textContent)).toEqual(["“Staff rota” couldn't be installed on this computer. Try again."]);
+ });
+
+ it("offers no Desktop item in a desktop build without it", async () => {
+ vi.stubGlobal("ogb", { appInstall: { list: bridge.list, install: bridge.install, uninstall: bridge.uninstall, cleanup: bridge.cleanup } });
+ await show();
+ act(() => button(card(BOARD.id), "More for Sales board").click());
+ expect(menuItem("Uninstall")).toBeDefined();
+ expect(menuItem("Add to Desktop")).toBeUndefined();
+ });
+
+ it("offers both from the app view's header, and Uninstall clears the Desktop item", async () => {
+ onDesktop = [BOARD.id];
+ openLocalApp(BOARD.id);
+ await show();
+ act(() => button(host, "More for Sales board").click());
+ expect(menuItem("Uninstall")).toBeDefined();
+ await act(async () => menuItem("Remove from Desktop").click());
+ await settle();
+ expect(bridge.removeFromDesktop).toHaveBeenCalledWith(BOARD.id);
+ act(() => button(host, "More for Sales board").click());
+ await act(async () => menuItem("Add to Desktop").click());
+ await settle();
+ expect(bridge.addToDesktop).toHaveBeenCalledWith(BOARD.id);
+ act(() => button(host, "More for Sales board").click());
+ await act(async () => menuItem("Uninstall").click());
+ await settle();
+ act(() => button(host, "More for Sales board").click());
+ expect(menuItem("Install on this computer")).toBeDefined();
+ expect(menuItem("Add to Desktop")).toBeDefined();
+ });
+
+ it("shows a failed Desktop change in the app view's one line", async () => {
+ bridge.removeFromDesktop.mockResolvedValueOnce({ ok: false, reason: "invalid-id" });
+ onDesktop = [BOARD.id];
+ openLocalApp(BOARD.id);
+ await show();
+ act(() => button(host, "More for Sales board").click());
+ await act(async () => menuItem("Remove from Desktop").click());
+ await settle();
+ expect(host.querySelector("[role=alert]")?.textContent).toBe("“Sales board” couldn't be removed from the Desktop. Try again.");
+ });
+});
+
describe("a saved app's live data and state", () => {
const frame = () => host.querySelector<HTMLIFrameElement>("[data-local-app-view] iframe")!;
const fromPage = (data: unknown) => act(async () => {
diff --git a/src/components/published-apps/LocalAppsSection.tsx b/src/components/published-apps/LocalAppsSection.tsx
index dee5a1a94c..0bd661eca7 100644
--- a/src/components/published-apps/LocalAppsSection.tsx
+++ b/src/components/published-apps/LocalAppsSection.tsx
@@ -5,10 +5,10 @@ import { cn } from "@/lib/cn";
import type { LocalApp } from "../../../shared/local-apps";
import { t } from "@/lib/i18n";
import { changeLocalApp, hideLocalApp, loadLocalApps, openLocalApp, removeLocalApp, useLocalApps } from "@/lib/local-apps";
-import { installLocalApp, uninstallLocalApp, useAppInstall } from "@/lib/local-app-install";
+import { addLocalAppToDesktop, installLocalApp, removeLocalAppFromDesktop, uninstallLocalApp, useAppInstall } from "@/lib/local-app-install";
import type { Action, AppState } from "@/state/store";
import { useStoreDispatch, useStoreSelector } from "@/state/store-select";
-import { LocalAppCard } from "./LocalAppCard";
+import { desktopFailedText, LocalAppCard, type InstallActions } from "./LocalAppCard";
export const REMOVE_UNDO_MS = 6_000;
export const SECTION_TITLE = "text-[17px] font-semibold text-ink";
@@ -80,11 +80,17 @@ export function LocalAppsSection({ place, alone = false }: { place: "computer" |
void changeLocalApp(app.id, { name }).catch(() => setLine({ kind: "failed", text: t("localApps.renameFailed") }));
};
const install = useAppInstall();
- const installOf = (app: LocalApp) => {
+ const installOf = (app: LocalApp): InstallActions | undefined => {
if (!install?.available) return undefined;
const installed = install.ids.has(app.id);
- return { installed, run: () => void (installed ? uninstallLocalApp(app.id) : installLocalApp(app)).catch(() =>
- setLine({ kind: "failed", text: t(installed ? "localApps.install.uninstallFailed" : "localApps.install.failed", { name: app.name }) })) };
+ const onDesktop = Boolean(install.desktop?.has(app.id));
+ return {
+ installed,
+ run: () => void (installed ? uninstallLocalApp(app.id) : installLocalApp(app)).catch(() =>
+ setLine({ kind: "failed", text: t(installed ? "localApps.install.uninstallFailed" : "localApps.install.failed", { name: app.name }) })),
+ ...(install.canDesktop ? { desktop: { on: onDesktop, run: () => void (onDesktop ? removeLocalAppFromDesktop(app.id) : addLocalAppToDesktop(app))
+ .catch((error: unknown) => setLine({ kind: "failed", text: desktopFailedText(error, onDesktop, app.name) })) } } : {}),
+ };
};
const goToChat = (app: LocalApp) => {
const action = chatOfApp(app, { bots });
diff --git a/src/lib/local-app-install.ts b/src/lib/local-app-install.ts
index 377792699f..58ef028a80 100644
--- a/src/lib/local-app-install.ts
+++ b/src/lib/local-app-install.ts
@@ -1,15 +1,18 @@
// Saved apps installed as launchers on this computer (the desktop app's own page only): which are, Install and
-// Uninstall, and keeping the launchers in step with the saved apps (gone, renamed).
+// Uninstall, an icon on the Desktop, and keeping the launchers in step with the saved apps (gone, renamed).
import { useSyncExternalStore } from "react";
import type { LocalApp } from "../../shared/local-apps";
import { appIconPng } from "@/lib/app-icon";
-export type AppInstallState = { available: boolean; ids: ReadonlySet<string> } | null;
+/** `desktop`: the apps whose icon is on the Desktop too; `canDesktop`: this desktop build can put one there. */
+export type AppInstallState = { available: boolean; ids: ReadonlySet<string>; desktop?: ReadonlySet<string>; canDesktop?: boolean } | null;
let state: AppInstallState = null;
const listeners = new Set<() => void>();
const bridge = () => (typeof window === "undefined" ? undefined : window.ogb?.appInstall);
+const canDesktop = () => typeof bridge()?.addToDesktop === "function" && typeof bridge()?.removeFromDesktop === "function";
+const without = (set: ReadonlySet<string> | undefined, id: string) => new Set([...(set ?? [])].filter((one) => one !== id));
function changed(next: AppInstallState): void {
state = next;
@@ -31,9 +34,12 @@ export async function readInstalled(): Promise<void> {
if (!install) return;
try {
const { available, apps } = await install.list();
- changed({ available: available === true, ids: new Set(apps.map((app) => app.id)) });
+ changed({
+ available: available === true, ids: new Set(apps.map((app) => app.id)),
+ desktop: new Set(apps.filter((app) => app.desktop === true).map((app) => app.id)), canDesktop: canDesktop(),
+ });
} catch {
- changed({ available: false, ids: new Set() });
+ changed({ available: false, ids: new Set(), desktop: new Set(), canDesktop: false });
}
}
@@ -52,7 +58,7 @@ export async function installLocalApp(app: Pick<LocalApp, "id" | "name" | "bot">
const iconPng = await appIconPng(app.name, app.bot?.color).catch(() => undefined);
const answer = await install.install({ id: app.id, name: app.name, ...(iconPng ? { iconPng } : {}) });
if (!answer.ok) throw new Error(answer.reason);
- changed({ available: true, ids: new Set([...(state?.ids ?? []), app.id]) });
+ changed({ ...state, available: true, ids: new Set([...(state?.ids ?? []), app.id]) });
}
export async function uninstallLocalApp(id: string): Promise<void> {
@@ -60,7 +66,27 @@ export async function uninstallLocalApp(id: string): Promise<void> {
if (!install) return;
const answer = await install.uninstall(id);
if (!answer.ok) throw new Error(answer.reason);
- changed({ available: state?.available ?? true, ids: new Set([...(state?.ids ?? [])].filter((one) => one !== id)) });
+ changed({ ...state, available: state?.available ?? true, ids: without(state?.ids, id), desktop: without(state?.desktop, id) });
+}
+
+export const isOnDesktop = (id: string) => Boolean(state?.desktop?.has(id));
+
+/** Rejects with "install" when installing it first failed, else with the reason the Desktop item could not be written. */
+export async function addLocalAppToDesktop(app: Pick<LocalApp, "id" | "name" | "bot">): Promise<void> {
+ const install = bridge();
+ if (!install?.addToDesktop) throw new Error("unavailable");
+ if (!isInstalled(app.id)) await installLocalApp(app).catch(() => { throw new Error("install"); });
+ const answer = await install.addToDesktop(app.id);
+ if (!answer.ok) throw new Error(answer.reason);
+ changed({ ...state, available: true, ids: new Set([...(state?.ids ?? []), app.id]), desktop: new Set([...(state?.desktop ?? []), app.id]) });
+}
+
+export async function removeLocalAppFromDesktop(id: string): Promise<void> {
+ const install = bridge();
+ if (!install?.removeFromDesktop) return;
+ const answer = await install.removeFromDesktop(id);
+ if (!answer.ok) throw new Error(answer.reason);
+ changed({ ...state, available: state?.available ?? true, ids: state?.ids ?? new Set(), desktop: without(state?.desktop, id) });
}
export const isInstalled = (id: string) => Boolean(state?.ids.has(id));
diff --git a/src/local-apps-preview.tsx b/src/local-apps-preview.tsx
index 3e4d54b5e4..6bd2a092fc 100644
--- a/src/local-apps-preview.tsx
+++ b/src/local-apps-preview.tsx
@@ -138,12 +138,15 @@ const store = { state, dispatch: () => {}, flushBotPatches: async () => null, re
if (view === "app") openLocalApp(LOCAL[0]!.id);
if (params.get("desktop") === "1" || view === "window") {
let installed = [LOCAL[0]!.id];
+ let onDesktop: string[] = [];
(window as { ogb?: unknown }).ogb = {
localApps: { openWindow: async () => true, openChat: async () => true },
appInstall: {
- list: async () => ({ available: true, apps: installed.map((id) => ({ id, name: "", path: null })) }),
+ list: async () => ({ available: true, apps: installed.map((id) => ({ id, name: "", path: null, desktop: onDesktop.includes(id) })) }),
install: async ({ id, name }: { id: string; name: string }) => { installed = [...installed, id]; return { ok: true, app: { id, name, path: null } }; },
- uninstall: async (id: string) => { installed = installed.filter((one) => one !== id); return { ok: true, removed: true }; },
+ uninstall: async (id: string) => { installed = installed.filter((one) => one !== id); onDesktop = onDesktop.filter((one) => one !== id); return { ok: true, removed: true }; },
+ addToDesktop: async (id: string) => { onDesktop = [...onDesktop, id]; return { ok: true, app: { id, name: "", path: null, desktop: true } }; },
+ removeFromDesktop: async (id: string) => { onDesktop = onDesktop.filter((one) => one !== id); return { ok: true, removed: true }; },
cleanup: async () => [],
},
};
diff --git a/src/locales/en.json b/src/locales/en.json
index 4c2d69ea79..6dd78e269f 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -7421,6 +7421,10 @@
"localApps.install.installed": "Installed",
"localApps.install.failed": "“{name}” couldn't be installed on this computer. Try again.",
"localApps.install.uninstallFailed": "“{name}” couldn't be uninstalled. Try again.",
+ "localApps.install.addToDesktop": "Add to Desktop",
+ "localApps.install.removeFromDesktop": "Remove from Desktop",
+ "localApps.install.desktopFailed": "“{name}” couldn't be added to the Desktop. Try again.",
+ "localApps.install.desktopRemoveFailed": "“{name}” couldn't be removed from the Desktop. Try again.",
"botAccess.tools.budget": "Its last turn listed {listed} of the {limit} tools its AI takes at once.",
"botAccess.tools.budgetSearched": "Found through tool search instead: {names}",
"botAccess.tools.title": "Tool selection",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 713554691f..6085952c5b 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -7032,6 +7032,10 @@
"localApps.install.installed": "Instalado",
"localApps.install.failed": "Não foi possível instalar “{name}” neste computador. Tente de novo.",
"localApps.install.uninstallFailed": "Não foi possível desinstalar “{name}”. Tente de novo.",
+ "localApps.install.addToDesktop": "Adicionar à Área de Trabalho",
+ "localApps.install.removeFromDesktop": "Remover da Área de Trabalho",
+ "localApps.install.desktopFailed": "Não foi possível adicionar “{name}” à Área de Trabalho. Tente de novo.",
+ "localApps.install.desktopRemoveFailed": "Não foi possível remover “{name}” da Área de Trabalho. Tente de novo.",
"botAccess.tools.budget": "Ferramentas listadas na última sessão: {listed} de {limit}, o limite que a IA dele aceita de uma vez.",
"botAccess.tools.budgetSearched": "Disponíveis pela busca de ferramentas: {names}",
"botAccess.tools.title": "Seleção de ferramentas",
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index f83560ccb0..d44170c14e 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -558,10 +558,18 @@ const __APP_VERSION__: string;
* replaces the old one. Absent in older desktop builds and on any other page. */
appInstall?: {
install(input: { id: string; name: string; iconPng?: Uint8Array; desktopShortcut?: boolean }): Promise<
- | { ok: true; app: { id: string; name: string; path: string | null } }
+ | { ok: true; app: { id: string; name: string; path: string | null; desktop?: boolean } }
| { ok: false; reason: "unavailable" | "invalid-id" | "taken" | "failed" }>;
uninstall(id: string): Promise<{ ok: true; removed: boolean; left?: string[] } | { ok: false; reason: "invalid-id" }>;
- list(): Promise<{ available: boolean; apps: Array<{ id: string; name: string; path: string | null }> }>;
+ /** An installed app's icon on the Desktop too (a copy of its launcher); it never makes a missing Desktop folder.
+ * Absent in older desktop builds. */
+ addToDesktop?(id: string): Promise<
+ | { ok: true; app: { id: string; name: string; path: string | null; desktop: boolean } }
+ | { ok: false; reason: "unavailable" | "invalid-id" | "not-installed" | "no-desktop" | "taken" | "failed" }>;
+ /** Removes only that Desktop item; the launcher stays. Absent in older desktop builds. */
+ removeFromDesktop?(id: string): Promise<{ ok: true; removed: boolean; left?: string[] } | { ok: false; reason: "invalid-id" }>;
+ /** `desktop`: its icon is on the Desktop too (absent in older desktop builds). */
+ list(): Promise<{ available: boolean; apps: Array<{ id: string; name: string; path: string | null; desktop?: boolean }> }>;
/** `ids`: every saved app's id; launchers of any other app are removed. Absent in older desktop builds. */
cleanup?(ids: string[]): Promise<string[]>;
};