Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Local apps: save a bot's page as an app, open it without the chat, install it on this computer (#7668)
Milind Sonicb72ca1c5234
diff --git a/electron/app-install-mac.node-test.mjs b/electron/app-install-mac.node-test.mjsnew file mode 100644index 0000000000..6468f921ea--- /dev/null+++ b/electron/app-install-mac.node-test.mjs@@ -0,0 +1,40 @@+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { createAppInstaller } from "./app-install/installer.mjs";+import { macPlistAppId } from "./app-install/launchers.mjs";++const run = (file, args) => new Promise((resolve) => {+ execFile(file, args, { timeout: 20_000 }, (error, stdout, stderr) => resolve({ code: error ? 1 : 0, stdout, stderr }));+});++test("macOS: a real bundle built in a temporary home is structurally valid", { skip: process.platform !== "darwin" }, async (t) => {+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "app-install-")));+ 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 installer = createAppInstaller({+ platform: "darwin", path, home, userData: path.join(root, "user-data"), fs: fs.promises, run, hostBundleId: "com.openmausbot.app", enabled: true,+ });+ const result = await installer.installApp({ id: "la_realtest00000000", name: "Real Test" });+ assert.equal(result.ok, true);+ const bundle = path.join(home, "Applications", "MausBot Apps", "Real Test.app");+ assert.equal(result.app.path, bundle);+ const plist = path.join(bundle, "Contents", "Info.plist");+ assert.equal((await run("/usr/bin/plutil", ["-lint", plist])).code, 0);+ assert.equal(macPlistAppId(fs.readFileSync(plist, "utf8")), "la_realtest00000000");+ const executable = path.join(bundle, "Contents", "MacOS", "launcher");+ assert.equal(fs.statSync(executable).mode & 0o111, 0o111);+ assert.match(fs.readFileSync(executable, "utf8"), /^#!\/bin\/sh\n/);+ const icns = fs.readFileSync(path.join(bundle, "Contents", "Resources", "AppIcon.icns"));+ assert.equal(icns.toString("latin1", 0, 4), "icns");+ assert.equal(icns.readUInt32BE(4), icns.length);+ assert.deepEqual(fs.readdirSync(path.join(root, "user-data", "app-install")), ["installed.json"]);+ assert.deepEqual(fs.readdirSync(path.join(home, "Applications", "MausBot Apps")), ["Real Test.app"]);++ assert.deepEqual(await installer.uninstallApp("la_realtest00000000"), { ok: true, removed: true });+ assert.equal(fs.existsSync(bundle), false);+});diff --git a/electron/app-install.node-test.mjs b/electron/app-install.node-test.mjsnew file mode 100644index 0000000000..77f94f817a--- /dev/null+++ b/electron/app-install.node-test.mjs@@ -0,0 +1,417 @@+import assert from "node:assert/strict";+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 { 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"],+ [" Budget 2026 ", "Budget 2026"],+ ["a/b\\c:d*e?f\"g<h>i|j", "a b c d e f g h i j"],+ ["...hidden", "hidden"],+ ["trailing. . ", "trailing"],+ ["CON", "CON_"],+ ["con.txt", "con_.txt"],+ ["LPT9", "LPT9_"],+ ["COM¹", "COM¹_"],+ ["Console", "Console"],+ ["evil\u202Etxt.exe", "eviltxt.exe"],+ ["zero\u200Bwidth\u2066x\u2069", "zerowidthx"],+ ["line\nbreak\ttab\u0000", "line break tab"],+ ["Cafe\u0301", "Café"],+ ["مرحبا", "مرحبا"],+ ["", "App"],+ [null, "App"],+ ["\u202E\u200B", "App"],+ ["../../etc/passwd", "etc passwd"],+ ];+ for (const [raw, want] of table) assert.equal(launcherName(raw), want, JSON.stringify(raw));+ const long = launcherName("x".repeat(300));+ assert.equal([...long].length, 64);+ const emoji = launcherName("👩👩👧".repeat(100));+ assert.ok(Buffer.byteLength(emoji) <= 180 && emoji.length > 0);+ assert.equal(launcherName("é".repeat(100)).length, 64);+});++test("app ids: only a saved app's id, which launchers and bundle ids are made from", () => {+ for (const id of [L("notes"), "la_AbCdEfGhIjKlMnOp", "la_0000000000000000", "la_-_-_-_-_-_-_-_-_"]) assert.ok(validAppId(id), id);+ for (const id of ["", "notes", "la_short", `${L("notes")}x`, "la_aaaaaaaaaaaaaa b", "la_aaaaaaaaaaaaaa/b", "la_aaaaaaaaaaaaaa.b", "la_aaaaaaaaaaaaa'b", 5, null]) {+ assert.equal(validAppId(id), false, String(id));+ }+ assert.equal(launcherLink(L("notes")), `openmausbot://app/${L("notes")}?window=1`);+ assert.match(launcherBundleId(L("notes")), /^com\.openmausbot\.app\.localapp\.[0-9a-f]{16}$/);+ assert.notEqual(launcherBundleId(L("notes")), launcherBundleId(L("notes2")));+ assert.equal(launcherBundleId(L("notes"), "bad id;rm"), launcherBundleId(L("notes")));+ assert.equal(windowsAppUserModelId(L("notes")), launcherBundleId(L("notes")));+});++test("Info.plist names the app, a bundle id of its own, the id marker and no Dock tile; the script opens the link", () => {+ const plist = macInfoPlist({ id: L("notes"), name: "Tom & Jerry <3>" });+ assert.match(plist, /<key>CFBundleDisplayName<\/key>\n {2}<string>Tom & Jerry <3><\/string>/);+ assert.match(plist, /<key>CFBundleExecutable<\/key>\n {2}<string>launcher<\/string>/);+ assert.match(plist, /<key>CFBundleIconFile<\/key>\n {2}<string>AppIcon<\/string>/);+ assert.match(plist, new RegExp(`<key>CFBundleIdentifier</key>\\n {2}<string>${launcherBundleId(L("notes")).replaceAll(".", "\\.")}</string>`));+ assert.match(plist, /<key>CFBundlePackageType<\/key>\n {2}<string>APPL<\/string>/);+ assert.match(plist, /<key>LSUIElement<\/key>\n {2}<true\/>/);+ assert.equal(macPlistAppId(plist), L("notes"));+ assert.doesNotMatch(macInfoPlist({ id: L("notes"), name: "N", icon: false }), /CFBundleIconFile/);+ assert.throws(() => macInfoPlist({ id: "x'y", name: "N" }));+ assert.equal(macLauncherScript({ id: L("notes") }),+ `#!/bin/sh\n/usr/bin/open -b 'com.openmausbot.app' '${launcherLink(L("notes"))}' 2>/dev/null || exec /usr/bin/open '${launcherLink(L("notes"))}'\n`);+ assert.match(macLauncherScript({ id: L("notes"), hostBundleId: "x'; rm -rf ~" }), /open -b 'com\.openmausbot\.app'/);+ assert.throws(() => macLauncherScript({ id: "a;b" }));+});++test("desktop entry and Windows shortcut carry the link, quoted executable and id marker", () => {+ const entry = desktopEntry({ id: L("notes"), name: "My\nNotes", executable: "/home/u/My Apps/100%$x\\y.AppImage", iconPath: "/home/u/.local/share/icons/mausbot-apps/i.png" });+ assert.match(entry, /^Name=My\\nNotes$/m);+ assert.match(entry, /^Exec="\/home\/u\/My Apps\/100%%\\\\\$x\\\\\\\\y\.AppImage" "openmausbot:\/\/app\/la_notes00000000000\?window=1"$/m);+ assert.match(entry, /^Icon=\/home\/u\/\.local\/share\/icons\/mausbot-apps\/i\.png$/m);+ assert.match(entry, /^X-OpenMausBot-LocalApp=la_notes00000000000$/m);+ assert.match(entry, /^Terminal=false$/m);+ assert.deepEqual(windowsShortcut({ id: L("notes"), name: "Notes", executable: "C:\\P\\OpenMausBot.exe", iconPath: "C:\\i.ico" }), {+ target: "C:\\P\\OpenMausBot.exe", args: launcherLink(L("notes")), description: "Notes", icon: "C:\\i.ico", iconIndex: 0, appUserModelId: windowsAppUserModelId(L("notes")),+ });+ assert.equal(windowsWindowDetails({ id: L("notes"), name: "Notes", executable: "C:\\P\\O.exe" }).relaunchCommand, `"C:\\P\\O.exe" ${launcherLink(L("notes"))}`);+});++test("icons: PNG checks, a one-image .ico, and a letter tile", () => {+ assert.deepEqual(pngSize(PNG), { width: 64, height: 64 });+ assert.equal(pngSize(Buffer.from("GIF89a not a png at all, long enough....")), null);+ assert.equal(pngSize("x"), null);+ const ico = icoFromPng(PNG);+ assert.deepEqual([...ico.subarray(0, 8)], [0, 0, 1, 0, 1, 0, 64, 64]);+ assert.equal(ico.readUInt32LE(14), PNG.length);+ assert.equal(ico.readUInt32LE(18), 22);+ assert.ok(ico.subarray(22).equals(PNG));+ assert.equal(icoFromPng(letterTilePng({ id: L("a"), name: "A", size: 256 }))[6], 0);+ assert.throws(() => icoFromPng(Buffer.from("nope")));+ assert.equal(tileLetter("élan"), "E");+ assert.equal(tileLetter(" 9 lives"), "9");+ assert.equal(tileLetter("日本"), null);+ assert.deepEqual(pngSize(letterTilePng({ id: L("x"), name: "日本", size: 32 })), { width: 32, height: 32 });+});++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` } });+ const bundle = `${dir}/Notes.app/Contents`;+ assert.equal(macPlistAppId(fs.text(`${bundle}/Info.plist`)), L("notes"));+ assert.match(fs.text(`${bundle}/Info.plist`), /CFBundleIconFile/);+ assert.equal(fs.text(`${bundle}/MacOS/launcher`), macLauncherScript({ id: L("notes") }));+ assert.equal(fs.entries.get(`${bundle}/MacOS/launcher`).mode, 0o755);+ assert.equal(fs.text(`${bundle}/Resources/AppIcon.icns`), "icns");+ assert.equal(fs.text(`${bundle}/PkgInfo`), "APPL????");+ 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.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);+ for (const file of fs.files()) assert.ok(file.startsWith(`${dir}/`) || file.startsWith("/Users/u/Library/Application Support/OpenMausBot/app-install/"), file);+});++test("macOS: when sips or iconutil fails the bundle has no icon of its own and still installs", async () => {+ const { fs, installer, dir } = mac({ runOk: false });+ assert.equal((await installer.installApp({ id: L("notes"), name: "Notes" })).ok, true);+ assert.doesNotMatch(fs.text(`${dir}/Notes.app/Contents/Info.plist`), /CFBundleIconFile/);+ assert.equal(fs.entries.has(`${dir}/Notes.app/Contents/Resources/AppIcon.icns`), false);+ assert.equal(fs.files().some((f) => f.includes("/work/")), false);+});++test("macOS: two apps with one name, a name only case apart, and a bundle someone else made", async () => {+ const { fs, installer, dir } = mac();+ await fs.mkdir(`${dir}/Budget.app/Contents`, { recursive: true });+ await fs.writeFile(`${dir}/Budget.app/Contents/Info.plist`, "<plist>theirs</plist>");+ fs.entries.set(`${dir}/Linked.app`, { type: "link" });+ assert.equal((await installer.installApp({ id: L("a"), name: "Notes" })).app.name, "Notes");+ assert.equal((await installer.installApp({ id: L("b"), name: "Notes" })).app.name, "Notes 2");+ assert.equal((await installer.installApp({ id: L("c"), name: "notes" })).app.name, "notes 3");+ assert.equal((await installer.installApp({ id: L("d"), name: "Budget" })).app.name, "Budget 2");+ assert.equal((await installer.installApp({ id: L("e"), name: "Linked" })).app.name, "Linked 2");+ assert.equal(fs.text(`${dir}/Budget.app/Contents/Info.plist`), "<plist>theirs</plist>");+ assert.equal((await installer.installApp({ id: L("a"), name: "Notes" })).app.name, "Notes");+ assert.equal(macPlistAppId(fs.text(`${dir}/Notes 2.app/Contents/Info.plist`)), L("b"));+});++test("macOS: a new name writes the new bundle and moves the old one to the Trash", async () => {+ const { fs, trashed, installer, dir } = mac();+ await installer.installApp({ id: L("notes"), name: "Notes" });+ const renamed = await installer.installApp({ id: L("notes"), name: "Journal" });+ assert.equal(renamed.app.path, `${dir}/Journal.app`);+ assert.deepEqual(trashed, [`${dir}/Notes.app`]);+ assert.equal(fs.entries.has(`${dir}/Notes.app`), false);+ assert.deepEqual((await installer.installedApps()).map((a) => a.name), ["Journal"]);+});++test("macOS: uninstall removes only this app's own bundle, deleting it when there is no Trash", async () => {+ const { fs, installer, dir } = mac({ trash: false });+ await installer.installApp({ id: L("a"), name: "Alpha" });+ await installer.installApp({ id: L("b"), name: "Beta" });+ await fs.writeFile(`${dir}/Beta.app/Contents/Info.plist`, macInfoPlist({ id: L("someone-else"), name: "Beta" }));+ assert.deepEqual(await installer.uninstallApp(L("a")), { ok: true, removed: true });+ assert.equal(fs.entries.has(`${dir}/Alpha.app`), false);+ assert.deepEqual(await installer.uninstallApp(L("b")), { ok: true, removed: true, left: [`${dir}/Beta.app`] });+ assert.ok(fs.entries.has(`${dir}/Beta.app/Contents/Info.plist`));+ assert.deepEqual(await installer.uninstallApp(L("b")), { ok: true, removed: false });+ assert.deepEqual(await installer.uninstallApp("../x"), { ok: false, reason: "invalid-id" });+});++test("macOS: a file the person put at our launcher's path is never replaced", async () => {+ const { fs, installer, dir } = mac();+ await installer.installApp({ id: L("notes"), name: "Notes" });+ await fs.rm(`${dir}/Notes.app`, { recursive: true });+ await fs.mkdir(`${dir}/Notes.app/Contents`, { recursive: true });+ await fs.writeFile(`${dir}/Notes.app/Contents/Info.plist`, "mine");+ assert.equal(await installer.isInstalled(L("notes")), false);+ assert.deepEqual(await installer.installedApps(), []);+ assert.equal((await installer.installApp({ id: L("notes"), name: "Notes" })).app.name, "Notes 2");+ assert.equal(fs.text(`${dir}/Notes.app/Contents/Info.plist`), "mine");+});++test("cleanup removes launchers of apps that are gone, and leftover staging folders", async () => {+ const { fs, installer, dir } = mac();+ await installer.installApp({ id: L("keep"), name: "Keep" });+ await installer.installApp({ id: L("gone"), name: "Gone" });+ await fs.mkdir(`${dir}/.mausbot-0123456789abcdef.staging/Contents`, { recursive: true });+ await fs.mkdir(`${dir}/.someone-elses.staging`, { recursive: true });+ assert.deepEqual(await installer.cleanup(undefined), []);+ assert.deepEqual(await installer.cleanup(null), []);+ assert.ok(fs.entries.has(`${dir}/Gone.app`));+ assert.deepEqual(await installer.cleanup([L("keep")]), [L("gone")]);+ assert.equal(fs.entries.has(`${dir}/Gone.app`), false);+ assert.equal(fs.entries.has(`${dir}/.mausbot-0123456789abcdef.staging`), false);+ assert.ok(fs.entries.has(`${dir}/.someone-elses.staging`));+ assert.deepEqual((await installer.installedApps()).map((a) => a.id), [L("keep")]);+});++test("refusals: unavailable when off, a bad id, and an unreadable list starts again", async () => {+ const off = mac({ enabled: false });+ assert.deepEqual(await off.installer.installApp({ id: L("notes"), name: "N" }), { ok: false, reason: "unavailable" });+ assert.deepEqual(await off.installer.installedApps(), []);+ assert.equal(off.fs.files().length, 0);+ const { fs, installer } = mac();+ for (const id of ["../../x", "a b", "", undefined]) assert.deepEqual(await installer.installApp({ id, name: "N" }), { ok: false, reason: "invalid-id" });+ await fs.mkdir("/Users/u/Library/Application Support/OpenMausBot/app-install", { recursive: true });+ await fs.writeFile("/Users/u/Library/Application Support/OpenMausBot/app-install/installed.json", "{not json");+ assert.equal((await installer.installApp({ id: L("n"), name: "N" })).ok, true);+ assert.equal(createAppInstaller({ platform: "freebsd", path: path.posix, home: "/h", userData: "/d", fs }).available(), false);+ assert.equal(createAppInstaller({ platform: "win32", path: path.win32, home: "C:\\h", userData: "C:\\d", appData: "C:\\a", fs, executable: "C:\\x.exe" }).available(), false);+});++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 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];+ assert.equal(file, `${dir}\\Notes.lnk`);+ assert.equal(operation, "create");+ assert.equal(link.target, options.executable);+ assert.equal(link.args, launcherLink(L("notes")));+ assert.equal(link.appUserModelId, windowsAppUserModelId(L("notes")));+ 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);++ 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"]]);++ await installer.installApp({ id: L("other"), name: "NOTES" });+ assert.equal(shortcuts.at(-1)[0], `${dir}\\NOTES 2.lnk`);++ await installer.installApp({ id: L("notes"), name: "Journal" });+ assert.ok(fs.entries.has(`${dir}\\Journal.lnk`));+ assert.equal(fs.entries.has(`${dir}\\Notes.lnk`), false);+ assert.equal(fs.entries.has("C:\\Users\\u\\Desktop\\Notes.lnk"), false);++ fs.entries.set(`${dir}\\Mine.lnk`, { type: "file", data: Buffer.from(JSON.stringify({ target: "C:\\x.exe", args: "" })) });+ assert.equal((await installer.installApp({ id: L("m"), name: "Mine" })).app.name, "Mine 2");+ assert.equal(JSON.parse(fs.text(`${dir}\\Mine.lnk`)).target, "C:\\x.exe");++ assert.deepEqual(await installer.uninstallApp(L("notes")), { ok: true, removed: true });+ assert.equal(fs.entries.has(`${dir}\\Journal.lnk`), false);+ assert.equal(fs.entries.has(link.icon), false);+ for (const f of fs.files()) assert.ok(f.startsWith(`${dir}\\`) || f.startsWith("C:\\Users\\u\\AppData\\Roaming\\OpenMausBot\\app-install\\"), f);+});++test("Windows: shortcuts follow MausBot's executable when it moved", async () => {+ const first = windows();+ await first.installer.installApp({ id: L("notes"), name: "Notes" });+ const moved = createAppInstaller({ ...first.options, executable: "D:\\OpenMausBot\\OpenMausBot.exe" });+ assert.deepEqual(await moved.refreshTargets(), [L("notes")]);+ assert.deepEqual(first.shortcuts.at(-1).slice(0, 2), [`${first.dir}\\Notes.lnk`, "replace"]);+ assert.equal(first.shortcuts.at(-1)[2].target, "D:\\OpenMausBot\\OpenMausBot.exe");+ assert.deepEqual(await moved.refreshTargets(), []);+});++test("Linux: a desktop entry and an icon, refusing an entry it did not write", async () => {+ const { fs, installer, dir, options } = linux();+ const result = await installer.installApp({ id: L("notes"), name: "Notes" });+ assert.equal(result.app.path, `${dir}/mausbot-app-${L("notes")}.desktop`);+ const entry = fs.text(`${dir}/mausbot-app-${L("notes")}.desktop`);+ assert.match(entry, /^Exec="\/home\/u\/Apps\/OpenMausBot\.AppImage" "openmausbot:\/\/app\/la_notes00000000000\?window=1"$/m);+ const icon = /^Icon=(.+)$/m.exec(entry)[1];+ assert.match(icon, /^\/home\/u\/\.local\/share\/icons\/mausbot-apps\/mausbot-app-[0-9a-f]{16}\.png$/);+ assert.ok(pngSize(fs.entries.get(icon).data));+ await installer.installApp({ id: L("notes"), name: "Journal" });+ assert.match(fs.text(`${dir}/mausbot-app-${L("notes")}.desktop`), /^Name=Journal$/m);++ await fs.writeFile(`${dir}/mausbot-app-${L("theirs")}.desktop`, "[Desktop Entry]\nName=Theirs\n");+ assert.deepEqual(await installer.installApp({ id: L("theirs"), name: "X" }), { ok: false, reason: "taken" });+ assert.equal(fs.text(`${dir}/mausbot-app-${L("theirs")}.desktop`), "[Desktop Entry]\nName=Theirs\n");++ const moved = createAppInstaller({ ...options, executable: "/opt/OpenMausBot/openmausbot" });+ assert.deepEqual(await moved.refreshTargets(), [L("notes")]);+ assert.match(fs.text(`${dir}/mausbot-app-${L("notes")}.desktop`), /^Exec="\/opt\/OpenMausBot\/openmausbot" "openmausbot:\/\/app\/la_notes00000000000\?window=1"$/m);++ assert.deepEqual(await installer.uninstallApp(L("notes")), { ok: true, removed: true });+ assert.equal(fs.entries.has(`${dir}/mausbot-app-${L("notes")}.desktop`), false);+ assert.equal(fs.entries.has(icon), false);+ assert.deepEqual(fs.files().sort(), ["/home/u/.config/OpenMausBot/app-install/installed.json", `${dir}/mausbot-app-${L("theirs")}.desktop`]);+});++test("Linux: XDG data home moves the launcher folders", async () => {+ const { fs, options } = linux();+ const installer = createAppInstaller({ ...options, dataHome: "/data" });+ assert.equal((await installer.installApp({ id: L("n"), name: "N" })).app.path, `/data/applications/mausbot-app-${L("n")}.desktop`);+ assert.ok(fs.files().some((f) => f.startsWith("/data/icons/mausbot-apps/")));+});++test("calls run one at a time, so two installs of one name never pick the same file", async () => {+ const { installer } = mac();+ const [a, b] = await Promise.all([installer.installApp({ id: L("a"), name: "Same" }), installer.installApp({ id: L("b"), name: "Same" })]);+ 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 () => {+ const handlers = new Map();+ const guarded = [];+ const seen = [];+ const installer = {+ available: () => true,+ installApp: async (input) => { seen.push(input); return { ok: true }; },+ 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 []; },+ };+ 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(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") });+ assert.deepEqual(seen, [{ id: L("a"), name: "x".repeat(512), iconPng: undefined, desktopShortcut: false }, ""]);+ assert.deepEqual(await handlers.get("app-install:list")({}), { available: true, apps: [{ id: L("a"), name: "A", path: "/p" }] });+ seen.length = 0;+ 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")]]]);+});++test("Windows: an installed app's own window takes its launcher's taskbar details; nothing elsewhere or uninstalled", async () => {+ const { installer } = windows();+ assert.equal(await installer.windowDetails(L("notes")), null);+ await installer.installApp({ id: L("notes"), name: "Notes", iconPng: PNG });+ const details = await installer.windowDetails(L("notes"));+ assert.equal(details.appId, windowsAppUserModelId(L("notes")));+ assert.equal(details.relaunchDisplayName, "Notes");+ assert.match(details.relaunchCommand, new RegExp(`OpenMausBot\\.exe" openmausbot://app/${L("notes")}\\?window=1$`));+ assert.match(details.appIconPath, /\.ico$/);+ assert.equal(await installer.windowDetails("../x"), null);+ assert.equal(await linux().installer.windowDetails(L("notes")), null);+});diff --git a/electron/app-install/icons.mjs b/electron/app-install/icons.mjsnew file mode 100644index 0000000000..792e1e1192--- /dev/null+++ b/electron/app-install/icons.mjs@@ -0,0 +1,121 @@+// Icons for a launcher: the app's own PNG when it sent a usable one, else a coloured tile with its first letter.+import { deflateSync } from "node:zlib";+import { appKey } from "./names.mjs";++const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);+export const MAX_ICON_BYTES = 8 * 1024 * 1024;+const MAX_SIDE = 4096;++/** `{ width, height }` of a PNG within the size limits, or null for anything else. */+export function pngSize(bytes) {+ if (!(bytes instanceof Uint8Array) || bytes.length < 33 || bytes.length > MAX_ICON_BYTES) return null;+ const png = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ if (!png.subarray(0, 8).equals(PNG_SIGNATURE) || png.toString("latin1", 12, 16) !== "IHDR") return null;+ const width = png.readUInt32BE(16), height = png.readUInt32BE(20);+ if (width < 1 || height < 1 || width > MAX_SIDE || height > MAX_SIDE) return null;+ return { width, height };+}++/** A Windows icon file holding one PNG image (Windows Vista and later read PNG entries); 256 and over is stored as 0. */+export function icoFromPng(png) {+ const size = pngSize(png);+ if (!size) throw new Error("not a PNG");+ const header = Buffer.alloc(22);+ header.writeUInt16LE(0, 0);+ header.writeUInt16LE(1, 2);+ header.writeUInt16LE(1, 4);+ header.writeUInt8(size.width >= 256 ? 0 : size.width, 6);+ header.writeUInt8(size.height >= 256 ? 0 : size.height, 7);+ header.writeUInt8(0, 8);+ header.writeUInt8(0, 9);+ header.writeUInt16LE(1, 10);+ header.writeUInt16LE(32, 12);+ header.writeUInt32LE(png.length, 14);+ header.writeUInt32LE(22, 18);+ return Buffer.concat([header, Buffer.from(png)]);+}++/** The files `iconutil` expects in a .iconset folder, each with its side in pixels. */+export const MAC_ICONSET = [16, 32, 128, 256, 512].flatMap((side) => [+ { file: `icon_${side}x${side}.png`, px: side },+ { file: `icon_${side}x${side}@2x.png`, px: side * 2 },+]);++const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {+ let c = n;+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;+ return c >>> 0;+});++function crc32(bytes) {+ let c = 0xffffffff;+ for (const byte of bytes) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);+ return (c ^ 0xffffffff) >>> 0;+}++function chunk(type, data) {+ const length = Buffer.alloc(4);+ length.writeUInt32BE(data.length);+ const body = Buffer.concat([Buffer.from(type, "latin1"), data]);+ const crc = Buffer.alloc(4);+ crc.writeUInt32BE(crc32(body));+ return Buffer.concat([length, body, crc]);+}++export function encodePng(width, height, rgba) {+ const ihdr = Buffer.alloc(13);+ ihdr.writeUInt32BE(width, 0);+ ihdr.writeUInt32BE(height, 4);+ ihdr.set([8, 6, 0, 0, 0], 8);+ const rows = Buffer.alloc((width * 4 + 1) * height);+ for (let y = 0; y < height; y += 1) rgba.copy(rows, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);+ return Buffer.concat([PNG_SIGNATURE, chunk("IHDR", ihdr), chunk("IDAT", deflateSync(rows)), chunk("IEND", Buffer.alloc(0))]);+}++// 5×7 capitals and digits, one string per glyph, rows top to bottom.+const GLYPHS = {+ A: "01110100011000111111100011000110001", B: "11110100011000111110100011000111110", C: "01110100011000010000100001000101110",+ D: "11110100011000110001100011000111110", E: "11111100001000011110100001000011111", F: "11111100001000011110100001000010000",+ G: "01110100011000010111100011000101111", H: "10001100011000111111100011000110001", I: "01110001000010000100001000010001110",+ J: "00111000100001000010000101001001100", K: "10001100101010011000101001001010001", L: "10000100001000010000100001000011111",+ M: "10001110111010110101100011000110001", N: "10001100011100110101100111000110001", O: "01110100011000110001100011000101110",+ P: "11110100011000111110100001000010000", Q: "01110100011000110001101011001001101", R: "11110100011000111110101001001010001",+ S: "01111100001000001110000010000111110", T: "11111001000010000100001000010000100", U: "10001100011000110001100011000101110",+ V: "10001100011000110001100010101000100", W: "10001100011000110101101011010101010", X: "10001100010101000100010101000110001",+ Y: "10001100010101000100001000010000100", Z: "11111000010001000100010001000011111",+ 0: "01110100011001110101110011000101110", 1: "00100011000010000100001000010001110", 2: "01110100010000100010001000100011111",+ 3: "11111000100010000010000011000101110", 4: "00010001100101010010111110001000010", 5: "11111100001111000001000011000101110",+ 6: "00110010001000011110100011000101110", 7: "11111000010001000100010000100001000", 8: "01110100011000101110100011000101110",+ 9: "01110100011000101111000010001001100",+};++const TILE_COLOURS = [[0x4f, 0x5b, 0xd5], [0x0f, 0x76, 0x6e], [0xb4, 0x53, 0x09], [0x9d, 0x17, 0x4d], [0x1d, 0x4e, 0xd8], [0x6d, 0x28, 0xd9], [0x15, 0x80, 0x3d]];++/** The glyph for a name's first letter or digit (accents dropped), or null when it has none in the 5×7 set. */+export function tileLetter(name) {+ const first = [...(typeof name === "string" ? name.normalize("NFD").replace(/\p{M}/gu, "") : "")].find((c) => /\S/u.test(c));+ const letter = first?.toUpperCase();+ return letter && GLYPHS[letter] ? letter : null;+}++/** A square PNG: a rounded tile in a colour picked from the app's id, with the name's first letter in white. */+export function letterTilePng({ id, name, size = 1024 }) {+ const rgba = Buffer.alloc(size * size * 4);+ const [r, g, b] = TILE_COLOURS[parseInt(appKey(String(id)).slice(0, 8), 16) % TILE_COLOURS.length];+ const inset = size * 0.1, side = size - inset * 2, radius = side * 0.225;+ const letter = tileLetter(name);+ const glyph = letter ? GLYPHS[letter] : null;+ const cell = Math.floor(side * 0.075), glyphLeft = Math.round((size - cell * 5) / 2), glyphTop = Math.round((size - cell * 7) / 2);+ for (let y = 0; y < size; y += 1) {+ for (let x = 0; x < size; x += 1) {+ const dx = Math.max(inset + radius - (x + 0.5), x + 0.5 - (size - inset - radius), 0);+ const dy = Math.max(inset + radius - (y + 0.5), y + 0.5 - (size - inset - radius), 0);+ const coverage = Math.min(1, Math.max(0, radius - Math.hypot(dx, dy) + 0.5));+ if (coverage === 0) continue;+ const gx = Math.floor((x - glyphLeft) / cell), gy = Math.floor((y - glyphTop) / cell);+ const ink = glyph && x >= glyphLeft && y >= glyphTop && gx < 5 && gy < 7 && glyph[gy * 5 + gx] === "1";+ rgba.set(ink ? [255, 255, 255, Math.round(coverage * 255)] : [r, g, b, Math.round(coverage * 255)], (y * size + x) * 4);+ }+ }+ return encodePng(size, size, rgba);+}diff --git a/electron/app-install/installer.mjs b/electron/app-install/installer.mjsnew file mode 100644index 0000000000..f3752bc57f--- /dev/null+++ b/electron/app-install/installer.mjs@@ -0,0 +1,332 @@+// 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.+//+// 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.+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";++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)`.+ */+export function createAppInstaller(options) {+ const { platform, path, home, userData, fs, run = null, shell = {}, resizePng = null, log = () => {} } = options;+ const enabled = options.enabled !== false && ["darwin", "win32", "linux"].includes(platform) && Boolean(home && userData && path)+ && (platform !== "win32" || (Boolean(options.appData) && typeof shell.writeShortcutLink === "function"))+ && (platform === "darwin" || Boolean(options.executable));+ const stateDir = path.join(userData, "app-install");+ const manifestFile = path.join(stateDir, MANIFEST);+ 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 },+ linux: { launchers: path.join(dataHome, "applications"), icons: path.join(dataHome, "icons", "mausbot-apps") },+ }[platform] ?? {};++ const childOf = (dir, file) => {+ if (!dir) return false;+ 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);++ 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; } };++ async function readManifest() {+ const text = await readText(manifestFile);+ if (text === null) return { version: 1, apps: {} };+ try {+ const parsed = JSON.parse(text);+ if (parsed?.version === 1 && parsed.apps && typeof parsed.apps === "object") return parsed;+ } catch {}+ log("[app-install] the list of installed launchers was unreadable; starting it again");+ return { version: 1, apps: {} };+ }+ async function writeManifest(manifest) {+ await fs.mkdir(stateDir, { recursive: true });+ const temp = `${manifestFile}.${process.pid}.tmp`;+ await fs.writeFile(temp, JSON.stringify(manifest, null, 2));+ await fs.rename(temp, manifestFile);+ }++ /** Whether `file` is a launcher this installer wrote for `id`: the id is inside it, and it is no symbolic link. */+ async function ownedBy(id, file, kind) {+ const stat = await lstat(file);+ if (!stat || stat.isSymbolicLink()) return false;+ if (kind === "bundle") return stat.isDirectory() && macPlistAppId(await readText(path.join(file, "Contents", "Info.plist"))) === id;+ if (kind === "desktop-entry") return stat.isFile() && desktopEntryAppId(await readText(file)) === id;+ if (kind === "shortcut") {+ try { return stat.isFile() && String(shell.readShortcutLink?.(file)?.args ?? "").trim() === launcherLink(id); } catch { return false; }+ }+ if (kind === "icon") return stat.isFile() && path.basename(file).includes(appKey(id));+ return false;+ }++ /** The first free `<name><ext>` in `dir`: absent, or already this app's own launcher; another app's chosen name is+ * 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)))));+ return firstFreeName(base, async (candidate) => {+ const file = path.join(dir, `${candidate}${ext}`);+ if (others.has(nameKey(`${candidate}${ext}`))) return false;+ return !(await lstat(file)) || ownedBy(id, file, kind);+ });+ }++ async function removeOwned(id, file) {+ if (!allowed(file.path)) { log(`[app-install] left ${file.path}: outside the launcher folders`); return false; }+ if (!(await lstat(file.path))) return true;+ if (!(await ownedBy(id, file.path, file.kind))) { log(`[app-install] left ${file.path}: not a launcher this app wrote for ${id}`); return false; }+ if (file.kind === "bundle" && typeof shell.trashItem === "function") {+ try { await shell.trashItem(file.path); return true; } catch {}+ }+ await fs.rm(file.path, { recursive: file.kind === "bundle", force: true });+ return true;+ }++ function iconSource(id, name, iconPng, side) {+ if (pngSize(iconPng)) return Buffer.from(iconPng.buffer, iconPng.byteOffset, iconPng.byteLength);+ return letterTilePng({ id, name, size: side });+ }++ async function squareIcon(png, side) {+ if (!resizePng) return png;+ try { const out = await resizePng(png, side); return pngSize(out) ? Buffer.from(out) : png; } catch { return png; }+ }++ /** sips and iconutil ship with every macOS; when either fails the bundle simply has no icon of its own. */+ async function macIcon(id, png, out) {+ if (!run) return false;+ const work = path.join(stateDir, "work", appKey(id));+ const iconset = path.join(work, "icon.iconset");+ try {+ await fs.rm(work, { recursive: true, force: true });+ await fs.mkdir(iconset, { recursive: true });+ const source = path.join(work, "source.png");+ await fs.writeFile(source, png);+ for (const { file, px } of MAC_ICONSET) {+ const result = await run("/usr/bin/sips", ["-z", String(px), String(px), source, "--out", path.join(iconset, file)]);+ if (result?.code !== 0) return false;+ }+ const result = await run("/usr/bin/iconutil", ["-c", "icns", "-o", out, iconset]);+ return result?.code === 0 && Boolean(await lstat(out));+ } catch (error) {+ log(`[app-install] no icon for ${id}: ${error?.message ?? error}`);+ return false;+ } finally {+ await fs.rm(path.dirname(work), { recursive: true, force: true }).catch(() => {});+ }+ }++ 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);+ return { name: chosen, files: [{ path: bundle, kind: "bundle" }] };+ }++ async function writeShortcut(manifest, id, dir, name, iconPath) {+ 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`);+ const exists = Boolean(await lstat(file));+ if (!shell.writeShortcutLink(file, exists ? "replace" : "create", windowsShortcut({ id, name: chosen, executable: options.executable, iconPath }))) {+ throw new Error(`Windows did not write ${file}`);+ }+ return { name: chosen, file: { path: file, kind: "shortcut" } };+ }++ async function installWindows(manifest, { id, name, iconPng, desktopShortcut }) {+ const iconDir = path.join(stateDir, "icons");+ await fs.mkdir(iconDir, { recursive: true });+ const iconPath = path.join(iconDir, `${appKey(id)}.ico`);+ let icon = null;+ try {+ await fs.writeFile(iconPath, icoFromPng(await squareIcon(iconSource(id, name, iconPng, 256), 256)));+ icon = { path: iconPath, kind: "icon" };+ } 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 };+ }++ async function installLinux(manifest, { id, name, iconPng }) {+ await fs.mkdir(roots.launchers, { recursive: true });+ const file = path.join(roots.launchers, `mausbot-app-${id}.desktop`);+ if ((await lstat(file)) && !(await ownedBy(id, file, "desktop-entry"))) return { error: "taken" };+ let icon = null;+ try {+ await fs.mkdir(roots.icons, { recursive: true });+ const iconPath = path.join(roots.icons, `mausbot-app-${appKey(id)}.png`);+ await fs.writeFile(iconPath, await squareIcon(iconSource(id, name, iconPng, 256), 256));+ icon = { path: iconPath, kind: "icon" };+ } catch (error) { log(`[app-install] no icon for ${id}: ${error?.message ?? error}`); }+ await fs.writeFile(file, desktopEntry({ id, name, executable: options.executable, iconPath: icon?.path }), { mode: 0o644 });+ return { name, files: [{ path: file, kind: "desktop-entry" }, ...(icon ? [icon] : [])] };+ }++ let queue = Promise.resolve();+ const serial = (task) => {+ const next = queue.then(task);+ queue = next.catch(() => {});+ 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) });++ 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));+ }+ return out;+ }++ async function uninstallLocked(manifest, id) {+ const entry = manifest.apps[id];+ if (!entry) return { ok: true, removed: false };+ const left = [];+ for (const file of entry.files ?? []) if (!(await removeOwned(id, file).catch(() => false))) left.push(file.path);+ delete manifest.apps[id];+ await writeManifest(manifest);+ return { ok: true, removed: true, ...(left.length ? { left } : {}) };+ }++ 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. */+ installApp: (input) => serial(async () => {+ if (!enabled) return { ok: false, reason: "unavailable" };+ const id = input?.id;+ if (!validAppId(id)) return { ok: false, reason: "invalid-id" };+ const name = launcherName(input?.name);+ const iconPng = input?.iconPng instanceof Uint8Array ? input.iconPng : null;+ const manifest = await readManifest();+ const previous = manifest.apps[id];+ let written;+ try {+ const request = { id, name, iconPng, desktopShortcut: input?.desktopShortcut === true };+ written = platform === "darwin" ? await installMac(manifest, request)+ : platform === "win32" ? await installWindows(manifest, request) : await installLinux(manifest, request);+ } catch (error) {+ log(`[app-install] could not install ${id}: ${error?.message ?? error}`);+ 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)));+ 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 } : {}) };+ await writeManifest(manifest);+ return { ok: true, app: view(id, manifest.apps[id]) };+ }),++ /** Removes only this app's own launcher files; on macOS the bundle goes to the Trash when it can. */+ uninstallApp: (id) => serial(async () => {+ if (!validAppId(id)) return { ok: false, reason: "invalid-id" };+ return uninstallLocked(await readManifest(), id);+ }),++ /** The launchers still on disk as this app wrote them, `{ id, name, path }` 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,+ * icon and relaunch); null anywhere else or when it is not installed. */+ windowDetails: (id) => serial(async () => {+ if (!enabled || platform !== "win32" || !validAppId(id)) return null;+ const entry = (await readManifest()).apps[id];+ if (!entry) return null;+ const iconPath = entry.files?.find((f) => f.kind === "icon")?.path;+ return windowsWindowDetails({ id, name: entry.name, executable: options.executable, ...(iconPath ? { iconPath } : {}) });+ }),++ 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)));+ }),++ /** Removes the launchers of apps that no longer exist (`ids`: every saved app's id, an array; anything else, such as+ * a failed fetch of the list, removes nothing), and leftover work folders. */+ cleanup: (ids) => serial(async () => {+ if (!Array.isArray(ids)) return [];+ const keep = new Set(ids);+ const manifest = await readManifest();+ const removed = [];+ for (const id of Object.keys(manifest.apps)) {+ if (keep.has(id)) continue;+ await uninstallLocked(manifest, id);+ removed.push(id);+ }+ await fs.rm(path.join(stateDir, "work"), { recursive: true, force: true }).catch(() => {});+ if (platform === "darwin" && roots.launchers) {+ const names = await fs.readdir(roots.launchers).catch(() => []);+ for (const name of names) {+ if (/^\.mausbot-[0-9a-f]{16}\.staging$/.test(name)) await fs.rm(path.join(roots.launchers, name), { recursive: true, force: true }).catch(() => {});+ }+ }+ return removed;+ }),++ /** Windows and Linux launchers name MausBot's executable: after it moved (a new AppImage, another install folder)+ * each one is written again with the current one. */+ refreshTargets: () => serial(async () => {+ if (!enabled || platform === "darwin") return [];+ const manifest = await readManifest();+ const refreshed = [];+ 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 });+ else shell.writeShortcutLink(file.path, "replace", windowsShortcut({ id, name: entry.name, executable: options.executable, iconPath: icon }));+ }+ entry.target = options.executable;+ refreshed.push(id);+ }+ if (refreshed.length) await writeManifest(manifest);+ return refreshed;+ }),+ };+}diff --git a/electron/app-install/ipc.mjs b/electron/app-install/ipc.mjsnew file mode 100644index 0000000000..0f01e79bb4--- /dev/null+++ b/electron/app-install/ipc.mjs@@ -0,0 +1,62 @@+// The channels behind installing a saved app on this computer (`guard`: this computer's own page only, never a Cloud+// or server page). The page names the app; the installer checks the id and cleans the name itself.+import { execFile } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { createAppInstaller } from "./installer.mjs";++const MAX_NAME = 512;++export function installAppInstall({ ipcMain, guard, installer }) {+ ipcMain.handle("app-install:install", guard("app-install:install", (_event, input) => {+ const id = typeof input?.id === "string" ? input.id : "";+ const name = typeof input?.name === "string" ? input.name.slice(0, MAX_NAME) : "";+ const iconPng = input?.iconPng instanceof Uint8Array ? input.iconPng : undefined;+ 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: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. */+export function createDesktopAppInstaller({ app, shell, nativeImage, env, platform, log }) {+ const userData = app.getPath("userData");+ const executable = platform === "linux" ? env.APPIMAGE || process.execPath : process.execPath;+ const installer = createAppInstaller({+ platform,+ path,+ home: app.getPath("home"),+ userData,+ appData: platform === "win32" ? app.getPath("appData") : null,+ desktop: platform === "win32" ? app.getPath("desktop") : null,+ dataHome: env.XDG_DATA_HOME && path.isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : null,+ executable,+ hostBundleId: hostBundleId(platform),+ enabled: app.isPackaged,+ 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 }));+ }),+ resizePng: (png, side) => {+ const image = nativeImage.createFromBuffer(Buffer.from(png));+ return image.isEmpty() ? null : image.resize({ width: side, height: side, quality: "best" }).toPNG();+ },+ log,+ });+ if (installer.available()) void installer.refreshTargets().catch(() => {});+ return installer;+}++function hostBundleId(platform) {+ if (platform !== "darwin") return undefined;+ try {+ const plist = fs.readFileSync(path.resolve(process.execPath, "..", "..", "Info.plist"), "utf8");+ return /<key>CFBundleIdentifier<\/key>\s*<string>([A-Za-z0-9.-]+)<\/string>/.exec(plist)?.[1];+ } catch {+ return undefined;+ }+}diff --git a/electron/app-install/launchers.mjs b/electron/app-install/launchers.mjsnew file mode 100644index 0000000000..6e44c7a9e5--- /dev/null+++ b/electron/app-install/launchers.mjs@@ -0,0 +1,111 @@+// The text of each launcher: a macOS bundle's Info.plist and executable, a Linux desktop entry, and the options of a+// Windows shortcut. Every one names the app's id, which is how the installer recognises a launcher as its own.+import { launcherLink, launcherBundleId, validAppId, validBundleId, windowsAppUserModelId, HOST_BUNDLE_ID } from "./names.mjs";++export const MAC_ID_KEY = "OpenMausBotLocalApp";+export const LINUX_ID_KEY = "X-OpenMausBot-LocalApp";+export const MAC_EXECUTABLE = "launcher";+export const MAC_ICON = "AppIcon";++const xml = (value) => String(value).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);++/**+ * LSUIElement is true: the launcher is a shell script that hands the link to MausBot and exits at once, so it never+ * shows a Dock tile or menu bar of its own; the window that opens is MausBot's and sits under MausBot's Dock tile.+ */+export function macInfoPlist({ id, name, hostBundleId = HOST_BUNDLE_ID, icon = true }) {+ if (!validAppId(id)) throw new Error("invalid app id");+ const entries = [+ ["CFBundleDevelopmentRegion", "en"],+ ["CFBundleDisplayName", name],+ ["CFBundleExecutable", MAC_EXECUTABLE],+ ...(icon ? [["CFBundleIconFile", MAC_ICON]] : []),+ ["CFBundleIdentifier", launcherBundleId(id, hostBundleId)],+ ["CFBundleInfoDictionaryVersion", "6.0"],+ ["CFBundleName", name],+ ["CFBundlePackageType", "APPL"],+ ["CFBundleShortVersionString", "1.0"],+ ["CFBundleVersion", "1"],+ [MAC_ID_KEY, id],+ ];+ return [+ '<?xml version="1.0" encoding="UTF-8"?>',+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',+ '<plist version="1.0">',+ "<dict>",+ ...entries.map(([key, value]) => ` <key>${key}</key>\n <string>${xml(value)}</string>`),+ " <key>LSUIElement</key>\n <true/>",+ " <key>NSHighResolutionCapable</key>\n <true/>",+ "</dict>",+ "</plist>",+ "",+ ].join("\n");+}++/** The id a launcher's Info.plist names, or null. */+export function macPlistAppId(text) {+ const match = new RegExp(`<key>${MAC_ID_KEY}</key>\\s*<string>([A-Za-z0-9_-]+)</string>`).exec(String(text));+ return match ? match[1] : null;+}++const shellQuote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;++/**+ * `open -b` finds MausBot by bundle id wherever it is installed and starts it when it is not running, so the launcher+ * outlives updates and moves; plain `open` falls back to whichever app handles the link.+ */+export function macLauncherScript({ id, hostBundleId = HOST_BUNDLE_ID }) {+ const link = shellQuote(launcherLink(id));+ const host = shellQuote(validBundleId(hostBundleId) ? hostBundleId : HOST_BUNDLE_ID);+ return `#!/bin/sh\n/usr/bin/open -b ${host} ${link} 2>/dev/null || exec /usr/bin/open ${link}\n`;+}++const desktopString = (value) => String(value).replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\t/g, "\\t").replace(/\r/g, "\\r");+/** Desktop Entry Exec: each argument in double quotes with ", `, $ and \ escaped, % doubled, then the value's own+ * backslashes escaped like any string value of the file. */+const execArgument = (value) => `"${String(value).replace(/["`$\\]/g, (c) => `\\${c}`)}"`.replace(/%/g, "%%");++export function desktopEntry({ id, name, executable, iconPath }) {+ if (typeof executable !== "string" || !executable) throw new Error("no executable");+ return [+ "[Desktop Entry]",+ "Type=Application",+ "Version=1.0",+ `Name=${desktopString(name)}`,+ `Exec=${desktopString(`${execArgument(executable)} ${execArgument(launcherLink(id))}`)}`,+ ...(iconPath ? [`Icon=${desktopString(iconPath)}`] : []),+ "Terminal=false",+ "Categories=Utility;",+ `${LINUX_ID_KEY}=${id}`,+ "",+ ].join("\n");+}++export function desktopEntryAppId(text) {+ const match = new RegExp(`^${LINUX_ID_KEY}=([A-Za-z0-9_-]+)$`, "m").exec(String(text));+ return match ? match[1] : null;+}++/** Options for Electron's `shell.writeShortcutLink`: MausBot's own executable with the link as its one argument, which+ * reaches the running app through `second-instance` or a new one through `process.argv`. */+export function windowsShortcut({ id, name, executable, iconPath }) {+ if (typeof executable !== "string" || !executable) throw new Error("no executable");+ return {+ target: executable,+ args: launcherLink(id),+ description: name,+ ...(iconPath ? { icon: iconPath, iconIndex: 0 } : {}),+ appUserModelId: windowsAppUserModelId(id),+ };+}++/** For the app's own window (`BrowserWindow.setAppDetails` on Windows): a taskbar button of its own, with the app's+ * icon, that relaunches the app rather than MausBot. */+export function windowsWindowDetails({ id, name, executable, iconPath }) {+ return {+ appId: windowsAppUserModelId(id),+ ...(iconPath ? { appIconPath: iconPath, appIconIndex: 0 } : {}),+ relaunchCommand: `"${executable}" ${launcherLink(id)}`,+ relaunchDisplayName: name,+ };+}diff --git a/electron/app-install/names.mjs b/electron/app-install/names.mjsnew file mode 100644index 0000000000..15105d1628--- /dev/null+++ b/electron/app-install/names.mjs@@ -0,0 +1,68 @@+// Names and identities of a saved app's launcher on this computer: what its file is called, which bundle or taskbar+// identity it carries, and the link it opens.+import { createHash } from "node:crypto";++export { launcherLink, validAppId } from "../app-link.mjs";++export const FOLDER_NAME = "MausBot Apps";+export const HOST_BUNDLE_ID = "com.openmausbot.app";++const BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]{0,154}$/;++export const validBundleId = (id) => typeof id === "string" && BUNDLE_ID.test(id) && !id.includes("..");++export const appKey = (id) => createHash("sha256").update(`openmausbot-local-app\n${id}`).digest("hex").slice(0, 16);++export const launcherBundleId = (id, host = HOST_BUNDLE_ID) => `${validBundleId(host) ? host : HOST_BUNDLE_ID}.localapp.${appKey(id)}`;++/** Windows groups taskbar buttons and pinned shortcuts by this id; a window that sets it with `setAppDetails` gets a+ * button of its own. */+export const windowsAppUserModelId = (id) => `${HOST_BUNDLE_ID}.localapp.${appKey(id)}`;++const RESERVED_WINDOWS = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³]|conin\$|conout\$)$/i;+const MAX_GRAPHEMES = 64;+const MAX_BYTES = 180;+const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });++function shorten(name) {+ let out = "";+ let count = 0;+ for (const { segment } of segmenter.segment(name)) {+ if (count === MAX_GRAPHEMES || Buffer.byteLength(out + segment) > MAX_BYTES) break;+ out += segment;+ count += 1;+ }+ return out;+}++/**+ * One file name that every target file system accepts: no control, bidirectional-override or zero-width characters,+ * none of `\ / : * ? " < > |`, no leading dot (hidden), no trailing dot or space (Windows drops them), no reserved+ * Windows device name, at most 64 characters and 180 UTF-8 bytes. Never empty.+ */+export function launcherName(raw) {+ let name = (typeof raw === "string" ? raw : "").normalize("NFC")+ .replace(/[\t\n\v\f\r\u0085\u2028\u2029]/gu, " ")+ .replace(/[\p{Cc}\p{Cf}]/gu, "")+ .replace(/[\\/:*?"<>|]/g, " ")+ .replace(/\s+/gu, " ")+ .trim()+ .replace(/^[.\s]+/u, "");+ name = shorten(name).replace(/[.\s]+$/u, "");+ const dot = name.indexOf(".");+ const stem = dot === -1 ? name : name.slice(0, dot);+ if (RESERVED_WINDOWS.test(stem.trimEnd())) name = `${stem.trimEnd()}_${dot === -1 ? "" : name.slice(dot)}`;+ return name || "App";+}++/** macOS and Windows compare file names without case and, on macOS, without Unicode normalisation form. */+export const nameKey = (name) => name.normalize("NFD").toLocaleLowerCase("en-US");++/** `base`, then `base 2`, `base 3`… until `free(candidate)` says yes; null when none of 99 is free. */+export async function firstFreeName(base, free) {+ for (let n = 1; n < 100; n += 1) {+ const candidate = n === 1 ? base : `${base} ${n}`;+ if (await free(candidate)) return candidate;+ }+ return null;+}diff --git a/electron/app-launches.mjs b/electron/app-launches.mjsnew file mode 100644index 0000000000..fee125fca9--- /dev/null+++ b/electron/app-launches.mjs@@ -0,0 +1,49 @@+// A saved app opened from its launcher on this computer (openmausbot://app/<id>?window=1, by open-url on macOS or as an+// argument of a first or second launch elsewhere): held until the app and its server are up, then opened in the app's+// own window, never in the main one.+import { parseAppLink } from "./app-link.mjs";++const RETRY_MS = 500;+const MAX_PENDING = 20;++/** `later(run, ms)`: a timer that keeps nothing alive. */+export function createAppLaunches({ later = (run, ms) => setTimeout(run, ms).unref?.() } = {}) {+ const pending = [];+ let open = null;+ let waiting = false;++ function flush() {+ waiting = false;+ while (open && pending.length) {+ if (!open(pending[0])) {+ if (!waiting) { waiting = true; later(flush, RETRY_MS); }+ return;+ }+ pending.shift();+ }+ }++ /** True when `value` was a launcher's link: it is then this module's, and no chat link. */+ function take(value) {+ const link = parseAppLink(value);+ if (!link?.window) return false;+ if (!pending.includes(link.id) && pending.length < MAX_PENDING) pending.push(link.id);+ flush();+ return true;+ }++ return {+ fromUrl: take,+ fromArgs(argv) {+ let taken = false;+ for (const value of Array.isArray(argv) ? argv : []) taken = take(value) || taken;+ return taken;+ },+ /** `opener(id)`: opens the app's window and says true, or false while it can't yet (tried again shortly). */+ attach(opener) {+ open = opener;+ flush();+ },+ pending: () => [...pending],+ };+}diff --git a/electron/app-link.d.mts b/electron/app-link.d.mtsnew file mode 100644index 0000000000..2cc47aea82--- /dev/null+++ b/electron/app-link.d.mts@@ -0,0 +1,9 @@+export declare const APP_LINK_PREFIX: string;+export declare const LOCAL_APP_ID: RegExp;+export function validAppId(id: unknown): id is string;+export function appLink(id: string): string;+/** The link a launcher on this computer opens: the app in a window of its own. */+export function launcherLink(id: string): string;+/** `{ id, window }` for openmausbot://app/<id> (a trailing slash allowed, `?window=1` the only query), else null. */+export function parseAppLink(value: unknown): { id: string; window: boolean } | null;+export function appLinkFromCommandLine(argv: unknown): { id: string; window: boolean } | null;diff --git a/electron/app-link.mjs b/electron/app-link.mjsnew file mode 100644index 0000000000..8381e5a461--- /dev/null+++ b/electron/app-link.mjs@@ -0,0 +1,39 @@+// openmausbot://app/<id>: the one parser of a saved app's link, for main (open-url, argv), the launchers it writes and+// the page. A launcher's link adds `?window=1`: it opens the app in a window of its own, not in the main window.++export const APP_LINK_PREFIX = "openmausbot://app/";+/** Security invariant: an id reaches a shell script, a desktop entry's Exec line, a shortcut argument and a file name,+ * so only this shape passes. Must match LOCAL_APP_ID in shared/local-apps.ts (app-link.node-test.mjs checks). */+export const LOCAL_APP_ID = /^la_[A-Za-z0-9_-]{16}$/;+const MAX_LINK = 256;++export const validAppId = (id) => typeof id === "string" && LOCAL_APP_ID.test(id);++/** The link the page and the app use. */+export function appLink(id) {+ if (!validAppId(id)) throw new Error("invalid app id");+ return `${APP_LINK_PREFIX}${id}`;+}++/** The link a launcher on this computer opens. */+export function launcherLink(id) {+ return `${appLink(id)}?window=1`;+}++/** `{ id, window }` for openmausbot://app/<id>, a trailing slash allowed, `?window=1` the only query; null otherwise. */+export function parseAppLink(value) {+ if (typeof value !== "string" || value.length > MAX_LINK) return null;+ const link = value.trim();+ if (link.slice(0, APP_LINK_PREFIX.length).toLowerCase() !== APP_LINK_PREFIX) return null;+ const match = /^([^/?#]+)\/?(\?window=1)?$/.exec(link.slice(APP_LINK_PREFIX.length));+ return match && validAppId(match[1]) ? { id: match[1], window: Boolean(match[2]) } : null;+}++/** The first saved app's link among a launch's arguments. */+export function appLinkFromCommandLine(argv) {+ for (const value of Array.isArray(argv) ? argv : []) {+ const parsed = parseAppLink(value);+ if (parsed) return parsed;+ }+ return null;+}diff --git a/electron/app-link.node-test.mjs b/electron/app-link.node-test.mjsnew file mode 100644index 0000000000..f814e51924--- /dev/null+++ b/electron/app-link.node-test.mjs@@ -0,0 +1,58 @@+import assert from "node:assert/strict";+import test from "node:test";++import { appLink, appLinkFromCommandLine, launcherLink, parseAppLink, validAppId } from "./app-link.mjs";+import { createAppLaunches } from "./app-launches.mjs";+import { chatLinkFrom, chatLinkFromCommandLine } from "./chat-link.mjs";++const ID = "la_AbCdEfGhIjKlMnOp";++test("one parser for a saved app's link: the store's id shape, an optional slash, `?window=1` the only query", () => {+ assert.deepEqual(parseAppLink(appLink(ID)), { id: ID, window: false });+ assert.deepEqual(parseAppLink(launcherLink(ID)), { id: ID, window: true });+ assert.deepEqual(parseAppLink(` OpenMausBot://APP/${ID}/ `), { id: ID, window: false });+ assert.deepEqual(parseAppLink(`openmausbot://app/${ID}/?window=1`), { id: ID, window: true });+ for (const link of ["openmausbot://app/notes", "openmausbot://app/la_short", `openmausbot://app/${ID}x`, `openmausbot://app/${ID}?window=0`,+ `openmausbot://app/${ID}?window=1&x=2`, `openmausbot://app/${ID}#window=1`, `openmausbot://app/../${ID}`, `openmausbot://thread/${ID}`,+ `https://example.com/app/${ID}`, `openmausbot://app/${ID}`.padEnd(300, "/"), 7, null]) assert.equal(parseAppLink(link), null, String(link));+ assert.throws(() => appLink("../x"));+ assert.equal(validAppId(ID), true);+ assert.deepEqual(appLinkFromCommandLine(["/Applications/OpenMausBot.app", "--flag", launcherLink(ID)]), { id: ID, window: true });+ assert.equal(appLinkFromCommandLine(["exe"]), null);+});++test("an in-app app link is the page's; a launcher's is not a chat link at all", () => {+ assert.equal(chatLinkFrom(appLink(ID)), appLink(ID));+ assert.equal(chatLinkFrom(launcherLink(ID)), null);+ assert.equal(chatLinkFrom("openmausbot://app/notes"), null);+ assert.equal(chatLinkFrom("openmausbot://thread/t1?bot=b1"), "openmausbot://thread/t1?bot=b1");+ assert.equal(chatLinkFromCommandLine(["exe", launcherLink(ID)]), null);+});++function launches() {+ const timers = [];+ const queue = createAppLaunches({ later: (run) => { timers.push(run); } });+ return { queue, timers, tick: () => timers.splice(0).forEach((run) => run()) };+}++test("a launcher's link from open-url, a second launch or the first launch waits for the app, then opens its window", () => {+ const { queue, tick, timers } = launches();+ assert.equal(queue.fromArgs(["exe", launcherLink(ID)]), true);+ assert.equal(queue.fromUrl(appLink(ID)), false);+ assert.equal(queue.fromUrl(launcherLink(ID)), true);+ assert.deepEqual(queue.pending(), [ID]);+ let up = false;+ const opened = [];+ queue.attach((id) => { if (!up) return false; opened.push(id); return true; });+ assert.deepEqual(opened, []);+ assert.equal(timers.length, 1);+ tick();+ assert.equal(timers.length, 1);+ up = true;+ tick();+ assert.deepEqual(opened, [ID]);+ assert.deepEqual(queue.pending(), []);+ assert.equal(queue.fromArgs(["exe", "openmausbot://thread/t1?bot=b1"]), false);+ queue.fromUrl(launcherLink("la_0000000000000000"));+ assert.deepEqual(opened, [ID, "la_0000000000000000"]);+});diff --git a/electron/chat-link.mjs b/electron/chat-link.mjsindex 5d16f90b74..4879a32c1b 100644--- a/electron/chat-link.mjs+++ b/electron/chat-link.mjs@@ -1,5 +1,8 @@-// openmausbot://thread/<thread-id>?bot=<bot-id> and openmausbot://bot/<bot-id>. The page checks them strictly against-// its chats; opening one never sends, interrupts or creates anything.+// openmausbot://thread/<thread-id>?bot=<bot-id>, openmausbot://bot/<bot-id> and a saved app's openmausbot://app/<id>. The+// page checks them strictly against its chats; opening one never sends, interrupts or creates anything. A launcher's app+// link (`?window=1`) is not the page's: it opens the app's own window (app-launches.mjs).+import { parseAppLink } from "./app-link.mjs";+const CHAT_LINK_PREFIXES = ["openmausbot://thread/", "openmausbot://bot/"];const MAX_LINK_LENGTH = 1024;@@ -7,7 +10,9 @@ export function chatLinkFrom(value) {const link = typeof value === "string" ? value.trim() : "";if (link.length > MAX_LINK_LENGTH) return null;const lower = link.toLowerCase();- return CHAT_LINK_PREFIXES.some((prefix) => lower.startsWith(prefix)) ? link : null;+ if (CHAT_LINK_PREFIXES.some((prefix) => lower.startsWith(prefix))) return link;+ const app = parseAppLink(link);+ return app && !app.window ? link : null;}export function chatLinkFromCommandLine(argv) {diff --git a/electron/local-app-windows.mjs b/electron/local-app-windows.mjsnew file mode 100644index 0000000000..d9c0fc275d--- /dev/null+++ b/electron/local-app-windows.mjs@@ -0,0 +1,166 @@+// A saved app in a window of its own: the app's page of the server the asking window shows (/local-app?id=…), with the+// main window's preload and the same guards, and its size remembered per app. Closing it leaves the app running.+import fs from "node:fs";+import path from "node:path";++import { appFrameNavigationAllowed } from "./app-frame-guard.mjs";+import { validAppId } from "./app-link.mjs";+import { chatLinkFrom } from "./chat-link.mjs";++export const APP_WINDOW_SIZE = { width: 1100, height: 760 };+export const APP_WINDOW_MIN = { width: 420, height: 360 };+const SIZES_KEPT = 100;++const appWindowSet = new WeakSet();++/** True for a saved app's own window: it is never the window a link, the Dock or a quit check means. */+export function isLocalAppWindow(win) {+ return Boolean(win) && appWindowSet.has(win);+}++export function appIdFrom(value) {+ return validAppId(value) ? value : null;+}++/** The address of the app's own page on `origin`, or null for anything but an http(s) origin. */+export function appWindowUrl(origin, id) {+ if (!appIdFrom(id) || typeof origin !== "string") return null;+ let parsed;+ try { parsed = new URL(origin); } catch { return null; }+ if ((parsed.protocol !== "http:" && parsed.protocol !== "https:") || parsed.origin !== origin) return null;+ return `${origin}/local-app?id=${encodeURIComponent(id)}`;+}++/** The size an app's window opens at: the one it last had, within the largest screen, else the default. */+export function appWindowSize(saved, workAreas = []) {+ const widest = workAreas.length ? Math.max(APP_WINDOW_MIN.width, ...workAreas.map((area) => area.width)) : Infinity;+ const tallest = workAreas.length ? Math.max(APP_WINDOW_MIN.height, ...workAreas.map((area) => area.height)) : Infinity;+ const fits = (value, min, max) => Number.isFinite(value) ? Math.round(Math.min(max, Math.max(min, value))) : null;+ const width = fits(saved?.width, APP_WINDOW_MIN.width, widest), height = fits(saved?.height, APP_WINDOW_MIN.height, tallest);+ return width !== null && height !== null ? { width, height } : { width: Math.min(APP_WINDOW_SIZE.width, widest), height: Math.min(APP_WINDOW_SIZE.height, tallest) };+}++/** Each app's last window size by its id, newest last, at most SIZES_KEPT. */+export function createAppWindowSizes({ file, log = () => {} }) {+ const read = () => {+ try {+ const parsed = JSON.parse(fs.readFileSync(file(), "utf8"));+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};+ } catch {+ return {};+ }+ };+ return {+ get: (id) => read()[id] ?? null,+ set(id, size) {+ if (!appIdFrom(id)) return;+ const sizes = read();+ delete sizes[id];+ sizes[id] = { width: Math.round(size.width), height: Math.round(size.height) };+ const kept = Object.fromEntries(Object.entries(sizes).slice(-SIZES_KEPT));+ const target = file(), temporary = `${target}.${process.pid}.tmp`;+ try {+ fs.mkdirSync(path.dirname(target), { recursive: true });+ fs.writeFileSync(temporary, JSON.stringify(kept), { mode: 0o600 });+ fs.renameSync(temporary, target);+ } catch (error) {+ try { fs.rmSync(temporary, { force: true }); } catch {}+ log(`app window size save failed: ${error?.message ?? error}`);+ }+ },+ };+}++function originOf(url) {+ try { return new URL(url).origin; } catch { return null; }+}++/**+ * `guard(channel, handler)`: who may open one (this computer's page or My Cloud's own); `senderOrigin(event)`: the+ * server the asking page shows; `webPreferences()`: the main window's; `openChat(link)`: main's chat link queue, which+ * brings the main window up; `openExternal(url)`: the person's browser. `launches` (app-launches.mjs): the apps opened+ * from their launchers, opened on `launchOrigin()` (this computer's server) once `ready()`. `windowDetails(id)`: on+ * Windows, the installed launcher's taskbar details for the app's window, or null.+ */+export function installLocalAppWindows({+ ipcMain, guard, BrowserWindow, senderOrigin, webPreferences, openChat, openExternal, sizes, workAreas = () => [], icon, background = () => undefined, log = () => {},+ launches, ready = () => true, launchOrigin = () => null, windowDetails = async () => null,+}) {+ const open = new Map();++ function openWindow(origin, id) {+ const url = appWindowUrl(origin, id);+ if (!url) return false;+ const key = `${origin}\n${id}`;+ const existing = open.get(key);+ if (existing && !existing.isDestroyed()) {+ if (existing.isMinimized()) existing.restore();+ existing.show();+ existing.focus();+ return true;+ }+ const win = new BrowserWindow({+ ...appWindowSize(sizes.get(id), workAreas()),+ minWidth: APP_WINDOW_MIN.width,+ minHeight: APP_WINDOW_MIN.height,+ show: false,+ ...(icon ? { icon } : {}),+ backgroundColor: background(),+ autoHideMenuBar: true,+ webPreferences: webPreferences(),+ });+ appWindowSet.add(win);+ open.set(key, win);+ const remember = () => {+ if (!win.isDestroyed() && !win.isMaximized() && !win.isFullScreen()) sizes.set(id, win.getNormalBounds?.() ?? win.getBounds());+ };+ win.on("resize", remember);+ win.on("close", remember);+ win.once("closed", () => { if (open.get(key) === win) open.delete(key); });+ win.once("ready-to-show", () => { if (!win.isDestroyed()) { win.show(); win.focus(); } });+ void Promise.resolve().then(() => windowDetails(id)).then((details) => {+ if (details && !win.isDestroyed()) win.setAppDetails?.(details);+ }).catch(() => {});++ win.webContents.setWindowOpenHandler(({ url: target }) => {+ if (/^https?:\/\//i.test(target)) void Promise.resolve(openExternal(target)).catch(() => {});+ return { action: "deny" };+ });+ // The window only ever shows its own app's page: anything else is refused, and a web link goes to the browser.+ const guardNavigation = (event, target) => {+ if (target === url) return;+ event.preventDefault();+ if (/^https?:\/\//i.test(target) && originOf(target) !== origin) void Promise.resolve(openExternal(target)).catch(() => {});+ log(`app window: blocked navigation to ${originOf(target) ?? "an invalid address"}`);+ };+ win.webContents.on("will-navigate", guardNavigation);+ win.webContents.on("will-redirect", guardNavigation);+ // No page may embed the server itself in this preload-bearing window, and an app's frame may only load its own document.+ win.webContents.on("will-frame-navigate", (details) => {+ if (details.isMainFrame) return;+ if (!appFrameNavigationAllowed(details)) return void details.preventDefault();+ if (originOf(details.url) === origin) details.preventDefault();+ });+ void win.loadURL(url).catch((error) => log(`app window failed to load: ${error?.message ?? error}`));+ return true;+ }++ ipcMain.handle("local-apps:open-window", guard("local-apps:open-window", (event, id) => {+ const origin = senderOrigin(event);+ return Boolean(origin && appIdFrom(id)) && openWindow(origin, id);+ }));+ // Only an app's own window asks this, and only for a chat link: the main window comes up on that chat.+ ipcMain.handle("local-apps:open-chat", (event, link) => {+ const sender = [...open.values()].find((win) => !win.isDestroyed() && win.webContents === event?.sender);+ const chat = chatLinkFrom(link);+ if (!sender || !chat || !/^openmausbot:\/\/(?:thread|bot)\//i.test(chat)) return false;+ return Boolean(openChat(chat));+ });++ launches?.attach((id) => {+ const origin = ready() ? launchOrigin() : null;+ return Boolean(origin) && openWindow(origin, id);+ });++ return { openWindow, windows: () => [...open.values()].filter((win) => !win.isDestroyed()) };+}diff --git a/electron/local-app-windows.node-test.mjs b/electron/local-app-windows.node-test.mjsnew file mode 100644index 0000000000..186a01c5e5--- /dev/null+++ b/electron/local-app-windows.node-test.mjs@@ -0,0 +1,204 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import test from "node:test";++import { chatLinkFrom } from "./chat-link.mjs";+import {+ APP_WINDOW_MIN, APP_WINDOW_SIZE, appIdFrom, appWindowSize, appWindowUrl, createAppWindowSizes, installLocalAppWindows, isLocalAppWindow,+} from "./local-app-windows.mjs";++const ID = "la_AbCdEfGhIjKlMnOp";+const OTHER = "la_0000000000000000";++test("an app's own page is on the asking server, for a well-formed id only", () => {+ assert.equal(appWindowUrl("http://127.0.0.1:8799", ID), `http://127.0.0.1:8799/local-app?id=${ID}`);+ assert.equal(appWindowUrl("https://ada.mausbot.cloud", ID), `https://ada.mausbot.cloud/local-app?id=${ID}`);+ for (const [origin, id] of [["http://127.0.0.1:8799", "la_short"], ["http://127.0.0.1:8799", `${ID}/../x`], ["file:///", ID], ["javascript:alert(1)", ID],+ ["http://127.0.0.1:8799/path", ID], [null, ID]]) assert.equal(appWindowUrl(origin, id), null, `${origin} ${id}`);+ assert.equal(appIdFrom(ID), ID);+ assert.equal(appIdFrom({ id: ID }), null);+});++test("openmausbot://app/<id> reaches the page as a chat link", () => {+ assert.equal(chatLinkFrom(`openmausbot://app/${ID}`), `openmausbot://app/${ID}`);+ assert.equal(chatLinkFrom(`OPENMAUSBOT://APP/${ID}`), `OPENMAUSBOT://APP/${ID}`);+ assert.equal(chatLinkFrom("openmausbot://apps/x"), null);+ assert.equal(chatLinkFrom(`openmausbot://app/${"x".repeat(2000)}`), null);+});++test("a window opens at its remembered size, within the largest screen", () => {+ assert.deepEqual(appWindowSize(null, [{ width: 1440, height: 900 }]), APP_WINDOW_SIZE);+ assert.deepEqual(appWindowSize(null, [{ width: 800, height: 600 }]), { width: 800, height: 600 });+ assert.deepEqual(appWindowSize({ width: 900.4, height: 500 }, [{ width: 1440, height: 900 }]), { width: 900, height: 500 });+ assert.deepEqual(appWindowSize({ width: 5000, height: 10 }, [{ width: 1440, height: 900 }, { width: 2560, height: 1400 }]), { width: 2560, height: APP_WINDOW_MIN.height });+ assert.deepEqual(appWindowSize({ width: "big" }, []), { width: APP_WINDOW_SIZE.width, height: APP_WINDOW_SIZE.height });+});++test("sizes are kept per app, the newest hundred", () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "omb-app-windows-"));+ const sizes = createAppWindowSizes({ file: () => path.join(dir, "app-windows.json") });+ sizes.set(ID, { width: 900.6, height: 700 });+ sizes.set("not an id", { width: 1, height: 1 });+ assert.deepEqual(sizes.get(ID), { width: 901, height: 700 });+ for (let n = 0; n < 120; n += 1) sizes.set(`la_${String(n).padStart(16, "0")}`, { width: 500, height: 500 });+ assert.equal(sizes.get(ID), null);+ assert.equal(Object.keys(JSON.parse(fs.readFileSync(path.join(dir, "app-windows.json"), "utf8"))).length, 100);+});++class FakeContents extends EventEmitter {+ constructor() { super(); this.opener = null; }+ setWindowOpenHandler(handler) { this.opener = handler; }+}+class FakeWindow extends EventEmitter {+ static made = [];+ constructor(options) {+ super();+ this.options = options;+ this.webContents = new FakeContents();+ this.destroyed = false;+ this.loaded = null;+ this.focused = 0;+ this.bounds = { x: 0, y: 0, width: options.width, height: options.height };+ FakeWindow.made.push(this);+ }+ loadURL(url) { this.loaded = url; return Promise.resolve(); }+ isDestroyed() { return this.destroyed; }+ isMinimized() { return false; }+ isMaximized() { return false; }+ isFullScreen() { return false; }+ restore() {}+ show() {}+ focus() { this.focused += 1; }+ getNormalBounds() { return this.bounds; }+ setAppDetails(details) { this.appDetails = details; }+ close() { this.emit("close"); this.destroyed = true; this.emit("closed"); }+}++function install(overrides = {}) {+ FakeWindow.made = [];+ const handlers = new Map();+ const saved = new Map();+ const external = [], chats = [], refused = [];+ const ipcMain = { handle: (channel, handler) => handlers.set(channel, handler) };+ const result = installLocalAppWindows({+ ipcMain,+ guard: (channel, handler) => (event, ...args) => {+ if (event.page === "other") { refused.push(channel); throw new Error("refused"); }+ return handler(event, ...args);+ },+ BrowserWindow: FakeWindow,+ senderOrigin: (event) => event.origin,+ webPreferences: () => ({ contextIsolation: true, preload: "/app/preload.cjs", additionalArguments: ["--omb-app-version=1"] }),+ openChat: (link) => { chats.push(link); return true; },+ openExternal: async (url) => { external.push(url); },+ sizes: { get: (id) => saved.get(id) ?? null, set: (id, size) => saved.set(id, size) },+ workAreas: () => [{ width: 1440, height: 900 }],+ ...overrides,+ });+ const call = (channel, event, ...args) => handlers.get(channel)(event, ...args);+ return { result, call, saved, external, chats, refused };+}++const fromMain = { origin: "http://127.0.0.1:8799" };++test("opens one window per app, with the main window's preload, and focuses it again", async () => {+ const { call, result } = install();+ assert.equal(await call("local-apps:open-window", fromMain, ID), true);+ const [win] = FakeWindow.made;+ assert.equal(win.loaded, `http://127.0.0.1:8799/local-app?id=${ID}`);+ assert.deepEqual(win.options.webPreferences, { contextIsolation: true, preload: "/app/preload.cjs", additionalArguments: ["--omb-app-version=1"] });+ assert.equal(win.options.show, false);+ assert.ok(isLocalAppWindow(win));+ assert.equal(await call("local-apps:open-window", fromMain, ID), true);+ assert.equal(FakeWindow.made.length, 1);+ assert.equal(win.focused, 1);+ await call("local-apps:open-window", fromMain, OTHER);+ assert.equal(FakeWindow.made.length, 2);+ assert.equal(result.windows().length, 2);+});++test("refuses a bad id, an unknown origin and a page the guard turns away", async () => {+ const { call, refused } = install();+ assert.equal(await call("local-apps:open-window", fromMain, "la_x"), false);+ assert.equal(await call("local-apps:open-window", { origin: null }, ID), false);+ assert.throws(() => call("local-apps:open-window", { page: "other", origin: "https://evil.example" }, ID));+ assert.deepEqual(refused, ["local-apps:open-window"]);+ assert.equal(FakeWindow.made.length, 0);+});++test("remembers the window's size as it closes, and closing it closes nothing else", async () => {+ const { call, saved } = install();+ await call("local-apps:open-window", fromMain, ID);+ const [win] = FakeWindow.made;+ win.bounds = { x: 10, y: 10, width: 820, height: 640 };+ win.close();+ assert.deepEqual(saved.get(ID), { x: 10, y: 10, width: 820, height: 640 });+ await call("local-apps:open-window", fromMain, ID);+ assert.equal(FakeWindow.made.length, 2);+ assert.equal(FakeWindow.made[1].options.width, 820);+});++test("its page can't navigate, open windows or frame the server; web links go to the browser", async () => {+ const { call, external } = install();+ await call("local-apps:open-window", fromMain, ID);+ const { webContents } = FakeWindow.made[0];+ assert.deepEqual(webContents.opener({ url: "https://example.com/" }), { action: "deny" });+ assert.deepEqual(webContents.opener({ url: "file:///etc/passwd" }), { action: "deny" });+ let prevented = 0;+ const event = { preventDefault: () => { prevented += 1; } };+ webContents.emit("will-navigate", event, "http://127.0.0.1:8799/");+ webContents.emit("will-navigate", event, "https://elsewhere.example/");+ webContents.emit("will-redirect", event, "http://127.0.0.1:8799/settings");+ webContents.emit("will-navigate", event, `http://127.0.0.1:8799/local-app?id=${ID}`);+ assert.equal(prevented, 3);+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(external, ["https://example.com/", "https://elsewhere.example/"]);+ let frames = 0;+ const frame = (details) => webContents.emit("will-frame-navigate", { ...details, preventDefault: () => { frames += 1; } });+ frame({ isMainFrame: false, url: "about:srcdoc", frame: { origin: "null" } });+ frame({ isMainFrame: false, url: "https://example.com/", frame: { origin: "null" } });+ frame({ isMainFrame: false, url: "http://127.0.0.1:8799/api/bots", frame: { origin: "http://127.0.0.1:8799" } });+ assert.equal(frames, 2);+});++test("only an app's own window may bring up the main window, and only on a chat", async () => {+ const { call, chats } = install();+ await call("local-apps:open-window", fromMain, ID);+ const own = { sender: FakeWindow.made[0].webContents };+ assert.equal(await call("local-apps:open-chat", own, "openmausbot://thread/t1?bot=b1"), true);+ assert.equal(await call("local-apps:open-chat", own, `openmausbot://app/${ID}`), false);+ assert.equal(await call("local-apps:open-chat", own, "https://example.com"), false);+ assert.equal(await call("local-apps:open-chat", { sender: new FakeContents() }, "openmausbot://thread/t1?bot=b1"), false);+ assert.deepEqual(chats, ["openmausbot://thread/t1?bot=b1"]);+});++test("a launcher's app opens in its own window on this computer's server once it is up, never in the main window", async () => {+ const { createAppLaunches } = await import("./app-launches.mjs");+ const later = [];+ const launches = createAppLaunches({ later: (run) => { later.push(run); } });+ launches.fromUrl(`openmausbot://app/${ID}?window=1`);+ let up = false;+ install({ launches, ready: () => up, launchOrigin: () => "http://127.0.0.1:8799" });+ assert.equal(FakeWindow.made.length, 0);+ up = true;+ later.splice(0).forEach((run) => run());+ assert.equal(FakeWindow.made.length, 1);+ assert.equal(FakeWindow.made[0].loaded, `http://127.0.0.1:8799/local-app?id=${ID}`);+ launches.fromArgs(["exe", `openmausbot://app/${ID}?window=1`]);+ assert.equal(FakeWindow.made.length, 1);+ assert.equal(FakeWindow.made[0].focused, 1);+});++test("on Windows an installed app's window takes its launcher's taskbar details", async () => {+ const details = { appId: "com.openmausbot.app.localapp.0123456789abcdef", relaunchCommand: "x", relaunchDisplayName: "Board" };+ const { call } = install({ windowDetails: async (id) => (id === ID ? details : null) });+ await call("local-apps:open-window", fromMain, ID);+ await call("local-apps:open-window", fromMain, OTHER);+ await new Promise((resolve) => setImmediate(resolve));+ assert.deepEqual(FakeWindow.made[0].appDetails, details);+ assert.equal(FakeWindow.made[1].appDetails, undefined);+});+diff --git a/electron/main.mjs b/electron/main.mjsindex 46e4eda285..598ed71d89 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -87,7 +87,7 @@ import {} from "./companion-account-service.mjs";import capabilitiesModule from "./capabilities.cjs";import environmentsModule from "./environments.cjs";-import { pairingPageUrl, vouchForPlainHttpServers } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { createTailnetShare, remotePolicyAllows } from "./tailnet-share.mjs"; import { checkTailscale } from "./tailscale-check.mjs"; import { onTailnet } from "./tailnet.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs"; import { installUpdateAll } from "./update-all.mjs";+import { pairingPageUrl, vouchForPlainHttpServers } from "./server-address.mjs"; import { createServerConnect } from "./server-probe.mjs"; import { createTailnetShare, remotePolicyAllows } from "./tailnet-share.mjs"; import { checkTailscale } from "./tailscale-check.mjs"; import { onTailnet } from "./tailnet.mjs"; import { checkServer, createServerStatus, installServerStatus } from "./server-status.mjs"; import { installUpdateAll } from "./update-all.mjs"; import { createAppWindowSizes, installLocalAppWindows, isLocalAppWindow } from "./local-app-windows.mjs"; import { createDesktopAppInstaller, installAppInstall } from "./app-install/ipc.mjs"; import { createAppLaunches } from "./app-launches.mjs";import localOriginModule from "./local-origin.cjs";import { buildApplicationMenu } from "./menu.mjs";import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs"; import { installServerLending } from "./server-lending.mjs"; import { ownEnvironmentIds } from "./lent-mcp.mjs";@@ -142,7 +142,7 @@ let desktopWorkspaceManager = null;let desktopWorkspaceOwner = null;let pendingOrganizationEntry = takeOrganizationDeepLink(process.argv);function appWindows() {- return BrowserWindow.getAllWindows().filter((win) => !isTalkPanel(win));+ return BrowserWindow.getAllWindows().filter((win) => !isTalkPanel(win) && !isLocalAppWindow(win));}const cloudEntry = createCloudEntry({reveal: () => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); },@@ -154,7 +154,7 @@ const cloudEntry = createCloudEntry({});cloudEntry.fromLaunch(process.argv); const teamLinks = installTeamJoin({ argv: process.argv, account: () => (app.isPackaged && !desktopRemoteAccess ? ensureCloudAccount() : null), addAccount: () => accountRing()?.addBrowser() ?? Promise.resolve(), openTeam: team => workspaceMenuAction(async () => { homeWindow.cancel(); await showHome({ place: { team: team.id, name: team.name } }); }), confirm: async (message, detail, button) => (await dialog.showMessageBox({ type: "question", buttons: [button, nativeT("native.common.cancel")], defaultId: 0, cancelId: 1, message, detail })).response === 0, t: (key, params) => nativeT(key, params), reveal: () => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); }, store: jsonFile(path.join(app.getPath("userData"), "team-landing.json")), ownPlace: () => Boolean(homeWindow.cloudOrigin()) || Boolean(homePlaces.remembered()), log: line => slog(line) });let pendingPackageInstallUrl = pendingOrganizationEntry ? null : packageUrlFromCommandLine(process.argv);-let pendingChatLink = pendingOrganizationEntry ? null : chatLinkFromCommandLine(process.argv);+let pendingChatLink = pendingOrganizationEntry ? null : chatLinkFromCommandLine(process.argv); const appLaunches = createAppLaunches(); appLaunches.fromArgs(process.argv);let organizationEntryReady = false;let mainWindow = null; const browserPanes = createBrowserPanes({ createView: (options) => new WebContentsView(options), createPopup: (options) => new BrowserWindow(options), createParking: () => new BrowserWindow({ show: false, width: 1280, height: 800, skipTaskbar: true, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false } }), keepsRunning: () => process.platform === "darwin" || hiddenStart || alwaysOnHome.on(), quitting: () => desktopShutdownStarted, fromPartition: (name) => session.fromPartition(name), owner: () => (mainWindow && !mainWindow.isDestroyed() ? mainWindow : null), chromeVersion: process.versions.chrome, log: (line) => slog(line) });const serverUnavailableWindows = new WeakSet();@@ -243,7 +243,7 @@ function queueChatLink(rawLink) {}app.on("open-url", (event, url) => {- if (!teamLinks.fromUrl(url) && !queueOrganizationEntry(url) && !cloudEntry.fromUrl(url) && !queuePackageInstall(url) && !queueChatLink(url)) return;+ if (!teamLinks.fromUrl(url) && !queueOrganizationEntry(url) && !cloudEntry.fromUrl(url) && !queuePackageInstall(url) && !appLaunches.fromUrl(url) && !queueChatLink(url)) return;event.preventDefault();});@@ -252,7 +252,7 @@ app.on("second-instance", (_event, commandLine) => {queueOrganizationEntry("openmausbot://organization");return;}- if (cloudEntry.fromArgs(commandLine)) return; if (teamLinks.fromArgs(commandLine)) return;+ if (cloudEntry.fromArgs(commandLine)) return; if (teamLinks.fromArgs(commandLine)) return; if (appLaunches.fromArgs(commandLine)) return;const packageUrl = packageUrlFromCommandLine(commandLine);if (packageUrl) pendingPackageInstallUrl = packageUrl;const chatLink = chatLinkFromCommandLine(commandLine);@@ -2669,7 +2669,7 @@ ipcMain.handle("environments:add-from-link", localWorkspaceOnly("environments:adipcMain.handle("environments:forget", localWorkspaceOnly("environments:forget", (_event, id, purge) => forgetEnvironment(typeof id === "string" ? id : "", purge === true)));const savedServerStatus = createServerStatus({ entries: () => environmentsState.environments.filter((e) => e.kind === "remote" && !e.home && !e.team && !e.cloud), check: (origin) => checkServer(origin, (...args) => session.defaultSession.fetch(...args)),appVersion: app.getVersion(), onChange: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("environments:status-changed"); } });-installServerStatus({ ipcMain, guard: localWorkspaceOnly, status: savedServerStatus, app, powerMonitor, online: () => net.isOnline() }); installUpdateAll({ ipcMain, guard: localWorkspaceOnly, servers: savedServerStatus.saved, fetch: (...args) => session.defaultSession.fetch(...args), send: (channel, view) => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send(channel, view); } });+installServerStatus({ ipcMain, guard: localWorkspaceOnly, status: savedServerStatus, app, powerMonitor, online: () => net.isOnline() }); installUpdateAll({ ipcMain, guard: localWorkspaceOnly, servers: savedServerStatus.saved, fetch: (...args) => session.defaultSession.fetch(...args), send: (channel, view) => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send(channel, view); } }); const appInstaller = createDesktopAppInstaller({ app, shell, nativeImage, env: process.env, platform: process.platform, log: slog }); installAppInstall({ ipcMain, guard: localWorkspaceOnly, installer: appInstaller }); installLocalAppWindows({ ipcMain, guard: localOrHome, BrowserWindow, senderOrigin: (event) => { try { return new URL(event.senderFrame.url).origin; } catch { return null; } }, webPreferences: () => ({ contextIsolation: true, preload: path.join(__dirname, "preload.cjs"), additionalArguments: [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`, ...(linuxSoftwareRendering ? [SOFTWARE_RENDERING_ARG] : [])] }), openChat: queueChatLink, openExternal: (url) => shell.openExternal(externalLinkUrl(url)), sizes: createAppWindowSizes({ file: () => path.join(app.getPath("userData"), "app-windows.json"), log: slog }), workAreas: () => screen.getAllDisplays().map((display) => display.workArea), icon: APP_ICON, background: () => windowBackground(nativeTheme.shouldUseDarkColors), log: slog, launches: appLaunches, ready: () => app.isReady() && serverReady, launchOrigin: () => rendererOrigin(), windowDetails: (id) => appInstaller.windowDetails(id) });// A cloud page may open the native chooser, never choose a destination or edit the saved list.// Once My Cloud is home the switcher lists only whole places, and shows only when there is more than My Cloud.diff --git a/electron/preload.cjs b/electron/preload.cjsindex 09235d8713..15874ba566 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -90,9 +90,11 @@ function railKeepsItsSize() {if (typeof window !== "undefined") {for (const type of ["resize", "DOMContentLoaded"]) window.addEventListener(type, () => { leaveRailRoom(); railKeepsItsSize(); });}+/** A page's typed array can arrive from another realm, where `instanceof Uint8Array` is false. */+const iconBytes = (value) => (ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : undefined);const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "placesTogether", "accountSheet", "desktopNotices", "desktopNotifications", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame", "softwareRendering", "appUpdate", "lendComputer"]);/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */-const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "exportDiagnostics", "openLogsFolder", "openAtLogin", "callActive"];+const HOME_PAGE = ["home", "onChatLink", "localApps", "onPackageInstall", "exportDiagnostics", "openLogsFolder", "openAtLogin", "callActive"];function updaterOffered() {try { return ipcRenderer.sendSync("update:offered") === true; } catch { return false; }}@@ -414,6 +416,10 @@ const bridge = {}return () => chatLinkListeners.delete(cb);},+ localApps: {+ openWindow: (id) => ipcRenderer.invoke("local-apps:open-window", id),+ openChat: (link) => ipcRenderer.invoke("local-apps:open-chat", link),+ },setUnreadCount: (count) => ipcRenderer.send("desktop:unread-count", count),desktopViewer: {open: (url, title, contextId) => ipcRenderer.invoke("desktop-viewer:open", url, title, contextId),@@ -507,6 +513,17 @@ 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). */+ 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),+ list: () => ipcRenderer.invoke("app-install:list"),+ cleanup: (ids) => ipcRenderer.invoke("app-install:cleanup", Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : null),+ },+/** A remote page may read the list but never change where this window goes. */environments: {state: () => ipcRenderer.invoke("environments:state"),diff --git a/electron/preload.node-test.mjs b/electron/preload.node-test.mjsindex f2c01d109d..b91ef8bf49 100644--- a/electron/preload.node-test.mjs+++ b/electron/preload.node-test.mjs@@ -89,6 +89,29 @@ test("the talk bridge asks main over its own channels with only what it understaassert.deepEqual(invocations.slice(before), [["talk-shortcut:state"], ["talk-shortcut:set", { enabled: false, key: "ctrl-shift-space" }], ["call:active", true], ["call:active", false]]);});+test("appInstall asks main over its own channels with only the fields it understands, and stays off remote pages", async () => {+ const before = invocations.length;+ const icon = new Uint8Array([1, 2, 3]);+ await exposed.api.appInstall.install({ id: "notes", name: "Notes", iconPng: icon, desktopShortcut: "yes", path: "/etc" });+ await exposed.api.appInstall.install({ id: "notes", name: "Notes", iconPng: "not bytes" });+ 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.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:list"],+ ]);+ const source = (await import("node:fs")).readFileSync(new URL("./preload.cjs", import.meta.url), "utf8");+ for (const list of ["REMOTE_SAFE", "HOME_PAGE"]) {+ const listed = new RegExp(`const ${list} = (?:new Set\\()?\\[([^\\]]*)\\]`).exec(source)?.[1] ?? "";+ assert.equal(listed.includes('"appInstall"'), false, `appInstall must stay out of ${list}`);+ }+});+test("account prepare asks for the secure address over its own channel and sends nothing from the page", async () => {const before = invocations.length;await exposed.api.companionAccount.prepare({ endpoint: "https://evil.example.test" });diff --git a/electron/talk-main.node-test.mjs b/electron/talk-main.node-test.mjsindex 3ecd1fb904..adaee7cf93 100644--- a/electron/talk-main.node-test.mjs+++ b/electron/talk-main.node-test.mjs@@ -80,7 +80,7 @@ function harness({ packaged = true, appleSpeech = true, windowsSpeech = false, rtest("every list of the app's windows leaves the talk box out", () => {assert.equal(main.match(/BrowserWindow\.getAllWindows\(\)/g).length, 1);- assert.match(main, /function appWindows\(\) \{\s*return BrowserWindow\.getAllWindows\(\)\.filter\(\(win\) => !isTalkPanel\(win\)\);/);+ assert.match(main, /function appWindows\(\) \{\s*return BrowserWindow\.getAllWindows\(\)\.filter\(\(win\) => !isTalkPanel\(win\) && !isLocalAppWindow\(win\)\);/);assert.match(main, /if \(appWindows\(\)\.length === 0\) openWindowForLink\(\);/);assert.match(main, /allWindows: \(\) => appWindows\(\)/);});diff --git a/local-apps-preview.html b/local-apps-preview.htmlnew file mode 100644index 0000000000..2b216d15fb--- /dev/null+++ b/local-apps-preview.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Local Apps Preview</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/local-apps-preview.tsx"></script>+ </body>+</html>diff --git a/server/index.ts b/server/index.tsindex 8e12e899e1..dda759277f 100644--- a/server/index.ts+++ b/server/index.ts@@ -468,7 +468,7 @@ import { createAgentCard } from "./chat-widgets.ts";import { botApproval, createChatAppRoutes, createChatApps, createChatAppsMcp, createConnectorGate, createConnectorGateApps } from "./routes/chat-apps.ts";import { buildBotOverview, type BotOverview, connectedAppsFacts } from "./bot-overview.ts";import { ProfileRequestService } from "./profile-requests.ts"; import { browserProfileLabel } from "./bot-browser-profile.ts";-import { ModelRequestService } from "./model-requests.ts";+import { ModelRequestService } from "./model-requests.ts"; import { createLocalAppsRoutes } from "./routes/local-apps.ts"; import { createLocalApps } from "./local-apps/service.ts"; import { withLocalAppDocs } from "./local-apps/store.ts";import { TeamSetupError, TeamSetupRequestService } from "./team-setup-requests.ts";import { startsWithoutCloudComputer, teamSetupDecisionText as decisionText, type TeamSetupRequest } from "../shared/team-setup.ts";import { profileRevision, profileSnapshot } from "./profile-revision.ts";@@ -11936,8 +11936,8 @@ ROUTES.push(createBotMessageRoutes({relayedReaction: (threadId, messageId, person, emoji) => void store.setReaction(threadId, messageId, relayedPersonKey(person),{ emoji, name: person.name ?? person.email, at: Date.now() }),}));-const liveRoots = (threadId: string, botId: string | undefined) => { const bot = botId ? store.bot(botId) : store.botByThread(threadId); return bot ? messageFileRootsForThread(bot.id, threadId).filter((root) => root !== ATTACHMENTS_DIR) : null; }; const chatApps = createChatApps({ store, dataDir: DATA_DIR, liveRows: liveAppRows, liveRoots, paused: () => workspaceMaintenance.active || moveFreeze.frozen() });-const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, keys: mcpKeys, storedServers: () => cfg.mcpServers ?? {}, mountedServers: (bot) => teamConnections.engineMcp(bot), personMcp: teamConnections.personMcp, probeAs: (server) => mcpServersHost.probeAs(server), oauth: mcpOAuth });+const liveRoots = (threadId: string, botId: string | undefined) => { const bot = botId ? store.bot(botId) : store.botByThread(threadId); return bot ? messageFileRootsForThread(bot.id, threadId).filter((root) => root !== ATTACHMENTS_DIR) : null; }; const chatApps = createChatApps({ store, dataDir: DATA_DIR, references: withLocalAppDocs(DATA_DIR), liveRows: liveAppRows, liveRoots, paused: () => workspaceMaintenance.active || moveFreeze.frozen() });+const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, keys: mcpKeys, storedServers: () => cfg.mcpServers ?? {}, mountedServers: (bot) => teamConnections.engineMcp(bot), personMcp: teamConnections.personMcp, probeAs: (server) => mcpServersHost.probeAs(server), oauth: mcpOAuth }); const localApps = createLocalApps({ chat: store, docs: chatApps.docs, dataDir: DATA_DIR, sweep: () => void chatApps.sweep() }); ROUTES.push(createLocalAppsRoutes({ apps: localApps, store, visibleFor: (auth) => visibleTo(viewerFor(auth)), threadRefusal: cloudThreadRefusal, live: (auth) => auth.kind !== "session" || sessions.isLive(auth.session.id) }));const pageConnectors = { gate: createConnectorGate({ bot: (id) => store.bot(id) ?? undefined, apps: createConnectorGateApps({ cfg: () => cfg, composio, personApps: () => teamConnections.personApps(), appsAccess: (person) => teamConnections.people.appsAccess(person), policyRefusal: (slugs, serviceSlugs) => managedPolicy.appsCallRefusal(slugs.map((slug) => ({ slug })), serviceSlugs) }), servers: { open: chatAppsMcp.openServer }, decide: (row) => appendDecision(DATA_DIR, row) }), person: (auth: RequestAuth) => (CLOUD_TEAM && auth.kind === "session" ? personKey(auth.session) : null), mayAct: (auth: RequestAuth, botId: string) => ["chat", "edit"].includes(levelOf(auth, botId)), fullAccess: (botId: string, threadId: string) => botApproval(store, botId, threadId) === "full", confined: (threadId: string) => cloudGuestDriven(threadId) || proactive.fence.confines(threadId) }; ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, data: dataEngine, dataOff: (botId) => serverTurnedOff(store.bot(botId)?.toolsOff, "data"), threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId), connectors: pageConnectors }));const roomReactionNotes = createRoomReactionNotes({ store }), { react } = createReactions({store, noted: roomReactionNotes.noted, inboxAnswer: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }), reply: (input) => personReplies.deliver({ ...input, about: "message" }),@@ -12434,7 +12434,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {}if (await emailSignInRoute({ cloudHome: Boolean(CLOUD_HOME), emailSignIn, sessions, cookieName: SESSION_COOKIE, target: (r) => signInMailTarget(publicUrl(), requestOrigin(r)),environment: () => environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED, emailSignIn: true, sharedComputers: lendingEnabled() }) }, req, res, path, method)) return;- if ((cloudSigned && await cloudSigned({ req, res, url, path, method })) || chatApps.serveFile(req, res, path, method) || await cliLogin.open(req, res, path, method)) return;+ if ((cloudSigned && await cloudSigned({ req, res, url, path, method })) || chatApps.serveFile(req, res, path, method) || localApps.serveFile(req, res, path, method) || await cliLogin.open(req, res, path, method)) return;if (method === "POST" && path === "/api/auth/pair") {// JSON only: a cross-site HTML form cannot send this content type without a preflight, so no unused code is planted as a session.if (!/^application\/json\b/i.test(String(req.headers["content-type"] ?? ""))) {diff --git a/server/local-apps.e2e.test.ts b/server/local-apps.e2e.test.tsnew file mode 100644index 0000000000..b7dfdc96cb--- /dev/null+++ b/server/local-apps.e2e.test.ts@@ -0,0 +1,72 @@+// End to end on the fakes: a scripted bot on a real server shows a folder page, the person saves it as an app through the+// real routes and sign-in gate, the bot replaces the page and the app follows, and the app and its files outlive the chat.+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";++let fixture: Awaited<ReturnType<typeof launchVerificationServer>>;++beforeAll(async () => {+ fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });+}, 90_000);+afterAll(async () => { await fixture?.close(); });++it("saves a shown page as an app that follows its newest version and outlives its chat, files and all", async () => {+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: fixture.info.url } }) as Promise<any>;+ const api = async (path: string, init: RequestInit = {}) => {+ const response = await fetch(`${fixture.info.url}${path}`, { ...init, headers: { "content-type": "application/json" } });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ };+ const planPath = join(fixture.info.dataDir, "room-plan.json");+ const bot = (await cli("new-bot", "--name", "Builder")).bot;+ const threadId = (await api(`/api/bots/${bot.id}/tasks`, { method: "POST", body: JSON.stringify({ title: "Dashboards" }) })).body?.task?.threadId+ ?? bot.activeTaskId as string;+ const folder = join(fixture.info.dataDir, "workspaces", bot.id, "dash");+ mkdirSync(folder, { recursive: true });+ writeFileSync(join(folder, "index.html"), "<h1>Sales</h1><script src=\"app.js\"></script>");+ writeFileSync(join(folder, "data.csv"), "region,total\nNorth,12");+ const plan = (steps: Array<{ tool: string; arguments: unknown }>) => writeFileSync(planPath, JSON.stringify({ [bot.id]: { steps, reply: "Done." } }));+ const settled = async () => expect((await cli("wait", "--bot", bot.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");++ plan([{ tool: "show_html", arguments: { html: "<h1>Sales v1</h1>", title: "Sales board" } }]);+ await cli("send", "--bot", bot.id, "--task", threadId, "--text", "Make me a sales board.");+ await settled();+ const messages = (await api(`/api/threads/${threadId}/messages?limit=50`)).body.messages as any[];+ const page = messages.find((message) => message.kind === "app");+ expect(page?.app?.title).toBe("Sales board");++ const saved = await api("/api/local-apps", { method: "POST", body: JSON.stringify({ botId: bot.id, threadId, messageId: page.id }) });+ expect(saved.status, JSON.stringify(saved.body)).toBe(201);+ const id = saved.body.app.id as string;+ expect((await api("/api/local-apps")).body.apps.map((app: any) => app.id)).toEqual([id]);++ plan([{ tool: "update_html", arguments: { app_id: page.id, html: "<h1>Sales v2</h1>" } }]);+ await cli("send", "--bot", bot.id, "--task", threadId, "--text", "Bigger heading please.");+ await settled();+ const followed = await api(`/api/local-apps/${id}`);+ expect(followed.body.app).toMatchObject({ rev: 1, versions: [{ rev: 0 }, { rev: 1 }] });+ expect((await api(`/api/local-apps/${id}/app`)).body.srcdoc).toContain("Sales v2");++ plan([{ tool: "show_html", arguments: { path: folder, title: "Dash" } }]);+ await cli("send", "--bot", bot.id, "--task", threadId, "--text", "Now from the folder.");+ await settled();+ const dash = ((await api(`/api/threads/${threadId}/messages?limit=50`)).body.messages as any[]).find((message) => message.kind === "app" && message.app.title === "Dash");+ expect(dash).toBeTruthy();+ {+ const folderApp = (await api("/api/local-apps", { method: "POST", body: JSON.stringify({ botId: bot.id, threadId, messageId: dash.id }) })).body.app.id as string;+ const doc = (await api(`/api/local-apps/${folderApp}/app?origin=${encodeURIComponent(fixture.info.url)}`)).body;+ const files = /<base href="([^"]+)"/.exec(doc.srcdoc)?.[1];+ expect(files).toMatch(/\/api\/local-app-files\/[\w-]{43}\/$/);+ const csv = await fetch(`${files}data.csv`);+ expect(csv.status).toBe(200);+ expect(await csv.text()).toContain("North,12");+ }++ expect((await api(`/api/bots/${bot.id}/tasks/${threadId}`, { method: "DELETE" })).status).toBeLessThan(300);+ const after = await api(`/api/local-apps/${id}`);+ expect(after.body.app).toMatchObject({ id, chat: false });+ expect((await api(`/api/local-apps/${id}/app`)).body.srcdoc).toContain("Sales v2");+ expect((await api(`/api/local-apps/${id}`, { method: "DELETE" })).body).toEqual({ ok: true });+ expect((await api(`/api/local-apps/${id}`)).status).toBe(404);+}, 120_000);diff --git a/server/local-apps/service.ts b/server/local-apps/service.tsnew file mode 100644index 0000000000..a3640f5267--- /dev/null+++ b/server/local-apps/service.ts@@ -0,0 +1,179 @@+import type { IncomingMessage, ServerResponse } from "node:http";++import { APP_USES, appUsesList, oneLine, type AppConnectorUse, type AppDocument, type AppPayload, type AppUse } from "../../shared/app.ts";+import { botHtmlDocument } from "../../shared/app-frame/document.ts";+import { LOCAL_APP_NAME_MAX, type LocalApp, type LocalAppManifest } from "../../shared/local-apps.ts";+import type { AppDocs } from "../app-docs.ts";+import { appRow } from "../chat-apps.ts";+import { createPageFiles, PAGE_FILES_PREFIX, type PageFilesViewer } from "../page-files.ts";+import type { Message, StoreChange } from "../store.ts";+import type { MausColor } from "../../shared/wire.ts";+import { LocalAppsStore, type LocalAppRecord, type LocalAppVersion } from "./store.ts";++/** Where a saved folder page's files load from. They answer while the app still keeps that version, whatever became of+ * the chat it came from. */+export const LOCAL_APP_FILES_PREFIX = "/api/local-app-files/";++export interface LocalAppsChat {+ bot?(id: string): { name: string; color: MausColor } | null | undefined;+ messagesFor(threadId: string): Message[];+ botByThread(threadId: string): { id: string } | null;+ groupByThread(threadId: string): unknown;+ taskByThread(botId: string, threadId: string): unknown;+ onChange?(listener: (change: StoreChange) => void): () => void;+}++export type SaveRefusal = { ok: false; status: 404 | 409 | 507; error: string };++const NOT_HERE = "That page is not in this conversation.";++/** What a stored version of the page declared (show_html `uses`), as the chat reads it: data and state, and connector+ * tools. */+function docUses(docs: AppDocs, doc: string): { uses: AppUse[]; connectors: AppConnectorUse[] } {+ const data = docs.read(doc)?.data;+ const uses = Array.isArray(data?.uses) ? data.uses.filter((use): use is AppUse => (APP_USES as readonly string[]).includes(use)) : [];+ return { uses, connectors: Array.isArray(data?.connectors) ? data.connectors : [] };+}++/** The manifest says what the newest version declared, each connector tool as "gmail:TOOL" or "mcp:server:TOOL". */+function withUses(manifest: LocalAppManifest, declared: ReturnType<typeof docUses>): LocalAppManifest {+ const { uses: _was, ...rest } = manifest;+ const uses = appUsesList(declared.uses, declared.connectors);+ return uses.length ? { ...rest, uses } : rest;+}++/** The versions a page's row still keeps, oldest first. */+function rowVersions(app: AppPayload, now: number): LocalAppVersion[] {+ const current = app.rev ?? 0;+ const history = app.history ?? [];+ const earlier = history.map((doc, index) => ({ rev: current - (history.length - index), doc, at: now })).filter((version) => version.rev >= 0);+ return [...earlier, ...(app.doc ? [{ rev: current, doc: app.doc, at: now }] : [])];+}++export function nameOf(text: string): string {+ return oneLine(text).slice(0, LOCAL_APP_NAME_MAX);+}++export interface LocalApps {+ list(): readonly LocalAppRecord[];+ get(id: string): LocalAppRecord | null;+ view(record: LocalAppRecord): LocalApp;+ save(args: { botId: string; threadId: string; messageId: string; owner?: string }): { ok: true; app: LocalAppRecord; created: boolean } | SaveRefusal;+ rename(id: string, name: string): LocalAppRecord | null;+ /** null follows the newest version again. */+ pin(id: string, rev: number | null): LocalAppRecord | null;+ remove(id: string): boolean;+ /** The app's page, built exactly as the chat builds it, for one of the versions it keeps. */+ document(id: string, rev?: number, origin?: string, viewer?: PageFilesViewer): AppDocument | null;+ serveFile(req: IncomingMessage, res: ServerResponse, path: string, method: string): boolean;+ close(): void;+}++export function createLocalApps(deps: {+ chat: LocalAppsChat;+ docs: AppDocs;+ dataDir: string;+ /** Asked soon after an app is removed, so the versions only it kept are cleared. */+ sweep?(): void;+ now?(): number;+}): LocalApps {+ const store = new LocalAppsStore(deps.dataDir);+ const now = deps.now ?? Date.now;+ const files = createPageFiles({ docs: deps.docs });+ let sweepTimer: ReturnType<typeof setTimeout> | null = null;++ const chatHas = (threadId: string) => Boolean(deps.chat.botByThread(threadId) || deps.chat.groupByThread(threadId));+ const pageRow = (threadId: string, messageId: string) => (chatHas(threadId) ? appRow(deps.chat, threadId, messageId) : undefined);++ const follow = (threadId: string, message: Message) => {+ const app = message.kind === "app" ? message.app : undefined;+ if (!app || app.source !== "html" || !app.doc) return;+ for (const record of store.savedFrom(threadId, message.id)) {+ const known = new Set(record.versions.map((version) => version.rev));+ const added = rowVersions(app, now()).filter((version) => !known.has(version.rev) && version.rev > Math.max(...known));+ if (added.length) {+ const uses = docUses(deps.docs, added.at(-1)!.doc);+ store.update(record.id, (was) => ({ ...was, versions: [...was.versions, ...added], manifest: withUses(was.manifest, uses) }), now());+ }+ }+ };+ const followRow = (record: LocalAppRecord) => {+ const row = pageRow(record.threadId, record.messageId);+ if (row) follow(record.threadId, row);+ return store.get(record.id) ?? record;+ };+ const unsubscribe = deps.chat.onChange?.((change) => {+ if ((change.type === "message.patch" || change.type === "message") && store.savedFrom(change.threadId, change.message.id).length) follow(change.threadId, change.message);+ });++ const botOf = (id: string) => {+ const bot = deps.chat.bot?.(id);+ return bot ? { name: bot.name, color: bot.color } : null;+ };+ const shownRev = (record: LocalAppRecord) => record.pinnedRev ?? record.versions.at(-1)!.rev;+ const keeps = (id: string, doc: string) => Boolean(store.get(id)?.versions.some((version) => version.doc === doc));++ return {+ list: () => store.list(),+ get: (id) => {+ const record = store.get(id);+ return record ? followRow(record) : null;+ },+ view: (record) => ({+ id: record.id, name: record.name, ...(record.icon ? { icon: record.icon } : {}), botId: record.botId, bot: botOf(record.botId), threadId: record.threadId, messageId: record.messageId,+ versions: record.versions.map(({ rev, at }) => ({ rev, at })), rev: shownRev(record), ...(record.pinnedRev !== undefined ? { pinnedRev: record.pinnedRev } : {}),+ createdAt: record.createdAt, updatedAt: record.updatedAt, manifest: record.manifest, chat: chatHas(record.threadId),+ }),+ save({ botId, threadId, messageId, owner }) {+ const row = pageRow(threadId, messageId);+ if (!row || (row.from && row.from.botId !== botId)) return { ok: false, status: 404, error: NOT_HERE };+ if (row.app.source !== "html") return { ok: false, status: 409, error: "Only a page a bot made can be saved as an app." };+ if (!row.app.doc) return { ok: false, status: 409, error: "This page isn't stored, so it can't be saved as an app." };+ const existing = store.fromPage(threadId, messageId, owner);+ if (existing) return { ok: true, app: followRow(existing), created: false };+ if (store.full()) return { ok: false, status: 507, error: "There are too many saved apps here. Remove one first." };+ const name = nameOf(row.app.title) || "App";+ const manifest = withUses({ name }, docUses(deps.docs, row.app.doc));+ const app = store.add({ name, botId, threadId, messageId, ...(owner ? { owner } : {}), versions: rowVersions(row.app, now()), manifest }, now());+ return { ok: true, app, created: true };+ },+ rename: (id, name) => store.update(id, (record) => ({ ...record, name, manifest: { ...record.manifest, name } }), now()),+ pin(id, rev) {+ const record = store.get(id);+ if (!record || (rev !== null && !record.versions.some((version) => version.rev === rev))) return null;+ return store.update(id, ({ pinnedRev: _was, ...rest }) => ({ ...rest, ...(rev === null ? {} : { pinnedRev: rev }) }), now());+ },+ remove(id) {+ if (!store.remove(id)) return false;+ if (deps.sweep && !sweepTimer) {+ sweepTimer = setTimeout(() => { sweepTimer = null; deps.sweep?.(); }, 2_000);+ sweepTimer.unref?.();+ }+ return true;+ },+ document(id, rev, origin, viewer) {+ const record = store.get(id);+ if (!record) return null;+ const version = record.versions.find((one) => one.rev === (rev ?? shownRev(record)));+ const stored = version ? deps.docs.read(version.doc) : null;+ if (!version || !stored || stored.source !== "html") return null;+ const target = { threadId: record.threadId, messageId: record.messageId, doc: version.doc };+ const folder = stored.data?.folder && origin+ ? files.folder(target, { key: viewer?.key ?? "", allowed: () => keeps(id, version.doc) && (viewer?.allowed() ?? true) }) : undefined;+ const filesAt = folder ? `${origin}${LOCAL_APP_FILES_PREFIX}${folder.slice(PAGE_FILES_PREFIX.length)}` : undefined;+ const { uses, connectors } = docUses(deps.docs, version.doc);+ return botHtmlDocument({ messageId: record.messageId, rev: version.rev, html: stored.html, title: record.name,+ ...(stored.data?.format === "jsx" ? { format: "jsx" as const } : {}), ...(filesAt ? { files: filesAt } : {}),+ ...(uses.length ? { uses } : {}), ...(connectors.length ? { connectors } : {}) });+ },+ serveFile(req, res, path, method) {+ if (!path.startsWith(LOCAL_APP_FILES_PREFIX)) return false;+ return files.serve(req, res, `${PAGE_FILES_PREFIX}${path.slice(LOCAL_APP_FILES_PREFIX.length)}`, method);+ },+ close() {+ unsubscribe?.();+ if (sweepTimer) clearTimeout(sweepTimer);+ sweepTimer = null;+ },+ };+}diff --git a/server/local-apps/store.test.ts b/server/local-apps/store.test.tsnew file mode 100644index 0000000000..1c3769430f--- /dev/null+++ b/server/local-apps/store.test.ts@@ -0,0 +1,38 @@+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { LOCAL_APP_VERSIONS } from "../../shared/local-apps.ts";+import { keptVersions, localAppDocRefs, localAppsFile, LocalAppsStore } from "./store.ts";++const doc = (n: number) => n.toString(16).padStart(64, "0");+const versions = (count: number) => Array.from({ length: count }, (_, rev) => ({ rev, doc: doc(rev + 1), at: rev }));++describe("local apps store", () => {+ it("keeps the newest versions, and the pinned one among them", () => {+ expect(keptVersions(versions(LOCAL_APP_VERSIONS + 5)).map((one) => one.rev)).toEqual(Array.from({ length: LOCAL_APP_VERSIONS }, (_, at) => at + 5));+ const pinned = keptVersions(versions(LOCAL_APP_VERSIONS + 5), 2);+ expect(pinned).toHaveLength(LOCAL_APP_VERSIONS);+ expect(pinned[0]!.rev).toBe(2);+ expect(pinned.at(-1)!.rev).toBe(LOCAL_APP_VERSIONS + 4);+ });++ it("writes one file another store reads back, and names every kept document", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-local-apps-"));+ const store = new LocalAppsStore(dir);+ const app = store.add({ name: "Board", botId: "b1", threadId: "t1", messageId: "m1", versions: versions(2), manifest: { name: "Board" } });+ expect(new LocalAppsStore(dir).get(app.id)).toMatchObject({ name: "Board", versions: [{ rev: 0 }, { rev: 1 }] });+ expect(localAppDocRefs(dir)).toEqual([doc(1), doc(2)]);+ const pinned = store.update(app.id, (record) => ({ ...record, pinnedRev: 7 }));+ expect(pinned?.pinnedRev).toBeUndefined();+ });++ it("starts empty on a file it can't read", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-local-apps-"));+ writeFileSync(localAppsFile(dir), "{not json");+ expect(new LocalAppsStore(dir).list()).toEqual([]);+ writeFileSync(localAppsFile(dir), JSON.stringify({ version: 1, apps: [{ id: "la_short", name: "x" }] }));+ expect(localAppDocRefs(dir)).toEqual([]);+ });+});diff --git a/server/local-apps/store.ts b/server/local-apps/store.tsnew file mode 100644index 0000000000..834de3a30b--- /dev/null+++ b/server/local-apps/store.ts@@ -0,0 +1,126 @@+import { randomBytes } from "node:crypto";+import { mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { LOCAL_APP_ID, LOCAL_APP_VERSIONS, LOCAL_APPS_MAX, type LocalAppManifest } from "../../shared/local-apps.ts";+import { writeFileAtomic } from "../atomic.ts";+import { appDocRefs } from "../message-db.ts";++const DOC = /^[0-9a-f]{64}$/;++export interface LocalAppVersion {+ rev: number;+ /** The content id of the stored document under app-docs. */+ doc: string;+ at: number;+}++export interface LocalAppRecord {+ id: string;+ name: string;+ icon?: string;+ botId: string;+ threadId: string;+ messageId: string;+ /** Who saved it, as a person key; absent when it was saved on this computer. */+ owner?: string;+ versions: LocalAppVersion[];+ pinnedRev?: number;+ createdAt: number;+ updatedAt: number;+ manifest: LocalAppManifest;+}++export const localAppsFile = (dataDir: string) => join(dataDir, "local-apps.json");++function readRecords(file: string): LocalAppRecord[] {+ try {+ const parsed = JSON.parse(readFileSync(file, "utf8")) as { version?: unknown; apps?: unknown };+ if (parsed.version !== 1 || !Array.isArray(parsed.apps)) return [];+ return parsed.apps.filter((app): app is LocalAppRecord => typeof app?.id === "string" && LOCAL_APP_ID.test(app.id) &&+ typeof app.name === "string" && typeof app.botId === "string" && typeof app.threadId === "string" && typeof app.messageId === "string" &&+ Array.isArray(app.versions) && app.versions.length > 0 && app.versions.every((version: LocalAppVersion) => typeof version?.doc === "string" && DOC.test(version.doc) && Number.isInteger(version.rev)));+ } catch {+ return [];+ }+}++/** Every document a saved app keeps, read from its file: the app-docs sweep keeps them however the chat changed. */+export function localAppDocRefs(dataDir: string): string[] {+ return readRecords(localAppsFile(dataDir)).flatMap((app) => app.versions.map((version) => version.doc));+}++/** The chat's documents and the saved apps' together: what the app-docs sweep must keep. */+export const withLocalAppDocs = (dataDir: string) => (): string[] => [...appDocRefs(), ...localAppDocRefs(dataDir)];++/** The newest versions, the pinned one always among them. */+export function keptVersions(versions: readonly LocalAppVersion[], pinnedRev?: number): LocalAppVersion[] {+ const sorted = [...versions].sort((a, b) => a.rev - b.rev);+ const newest = sorted.slice(-LOCAL_APP_VERSIONS);+ const pinned = pinnedRev === undefined ? undefined : sorted.find((version) => version.rev === pinnedRev);+ return pinned && !newest.includes(pinned) ? [pinned, ...newest.slice(1)] : newest;+}++/** The apps saved on this server, in one small JSON file in the data folder. */+export class LocalAppsStore {+ private records: LocalAppRecord[];+ private readonly file: string;++ constructor(dataDir: string) {+ this.file = localAppsFile(dataDir);+ this.records = readRecords(this.file);+ }++ private save(): void {+ mkdirSync(dirname(this.file), { recursive: true });+ writeFileAtomic(this.file, JSON.stringify({ version: 1, apps: this.records }), { mode: 0o600 });+ }++ list(): readonly LocalAppRecord[] {+ return this.records;+ }++ get(id: string): LocalAppRecord | null {+ return this.records.find((record) => record.id === id) ?? null;+ }++ fromPage(threadId: string, messageId: string, owner: string | undefined): LocalAppRecord | null {+ return this.records.find((record) => record.threadId === threadId && record.messageId === messageId && record.owner === owner) ?? null;+ }++ savedFrom(threadId: string, messageId: string): LocalAppRecord[] {+ return this.records.filter((record) => record.threadId === threadId && record.messageId === messageId);+ }++ full(): boolean {+ return this.records.length >= LOCAL_APPS_MAX;+ }++ add(input: Omit<LocalAppRecord, "id" | "createdAt" | "updatedAt">, now = Date.now()): LocalAppRecord {+ const record: LocalAppRecord = { ...input, id: `la_${randomBytes(12).toString("base64url")}`, versions: keptVersions(input.versions), createdAt: now, updatedAt: now };+ this.records = [record, ...this.records];+ this.save();+ return record;+ }++ update(id: string, change: (record: LocalAppRecord) => LocalAppRecord, now = Date.now()): LocalAppRecord | null {+ const index = this.records.findIndex((record) => record.id === id);+ if (index === -1) return null;+ const changed = change(this.records[index]!);+ const versions = keptVersions(changed.versions, changed.pinnedRev);+ const { pinnedRev, ...rest } = changed;+ const pinned = pinnedRev !== undefined && versions.some((version) => version.rev === pinnedRev) ? { pinnedRev } : {};+ const record: LocalAppRecord = { ...rest, ...pinned, versions, updatedAt: now };+ this.records = this.records.map((one, at) => (at === index ? record : one));+ this.save();+ return record;+ }++ remove(id: string): boolean {+ const before = this.records.length;+ this.records = this.records.filter((record) => record.id !== id);+ if (this.records.length === before) return false;+ this.save();+ return true;+ }+}diff --git a/server/request-auth.ts b/server/request-auth.tsindex 333e5be2d6..fb90caec59 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -507,6 +507,10 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg// what the viewer's own bots put online, from conversations they can read; the handler deletes only what is theirs{ methods: ["GET"], path: /^\/api\/published-apps(?:\/framing)?$/ },{ methods: ["POST"], path: /^\/api\/published-apps\/delete$/ },+ // the apps a person saved from bots' pages: the handler shows and changes only their own, from conversations they read+ { methods: ["GET", "POST"], path: /^\/api\/local-apps$/ },+ { methods: ["GET", "PATCH", "DELETE"], path: /^\/api\/local-apps\/la_[A-Za-z0-9_-]{16}$/ },+ { methods: ["GET"], path: /^\/api\/local-apps\/la_[A-Za-z0-9_-]{16}\/app$/ },// a Team Cloud's shared folder: every member reads and adds; the handler lets a member delete or rename only what they// uploaded (routes/team-files.ts); off a Team Cloud they answer 404{ methods: ["GET"], path: /^\/api\/team-files(?:\/file)?$/ },diff --git a/server/routes/local-apps-page-rpc.test.ts b/server/routes/local-apps-page-rpc.test.tsnew file mode 100644index 0000000000..c77b009a36--- /dev/null+++ b/server/routes/local-apps-page-rpc.test.ts@@ -0,0 +1,132 @@+// A saved app whose page declared data and state, opened from its own document route and calling the page rpc route+// exactly as the app view does (its bot, the source conversation and the page's message), against a real DuckDB database.+import { mkdtempSync, rmSync } from "node:fs";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";++import { createChatApps, type ChatApps } from "../chat-apps.ts";+import { DATA_DIR } from "../config.ts";+import type { ModelSelection } from "../contracts.ts";+import { createDataEngine } from "../data/engine.ts";+import { json, readBody } from "../harness/http.ts";+import { createLocalApps, type LocalApps } from "../local-apps/service.ts";+import { withLocalAppDocs } from "../local-apps/store.ts";+import type { RequestAuth } from "../request-auth.ts";+import { Store } from "../store.ts";+import { createChatAppRoutes } from "./chat-apps.ts";+import { createLocalAppsRoutes } from "./local-apps.ts";+import { dispatchRoutes } from "./table.ts";++const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };+const servers: Server[] = [];+const closers: Array<{ close(): void }> = [];+const root = mkdtempSync(join(tmpdir(), "omb-local-app-rpc-"));+const engine = createDataEngine({ botFolder: (botId) => join(root, "bots", botId), dataDir: join(root, "data") });++beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));+afterEach(async () => {+ for (const one of closers.splice(0)) one.close();+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});+afterAll(async () => { await engine.closeAll(); });++async function fixture() {+ const store = new Store(() => sonnet);+ const bot = store.createBot({ name: "Scout" });+ const chatApps: ChatApps = createChatApps({ store, dataDir: DATA_DIR, sweeps: false, references: withLocalAppDocs(DATA_DIR) });+ const localApps: LocalApps = createLocalApps({ chat: store, docs: chatApps.docs, dataDir: DATA_DIR });+ closers.push(chatApps, localApps);+ const everything = { everything: true, thread: () => true };+ const routes = [+ createLocalAppsRoutes({ apps: localApps, store, visibleFor: () => everything }),+ createChatAppRoutes({ store, apps: chatApps, data: engine, dataOff: () => false, threadVisible: () => true }),+ ];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ const auth = { kind: "loopback", scopes: ["admin", "client"] } as RequestAuth;+ try {+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, { from: "inline routes" });+ } catch (error) {+ json(res, 500, { error: error instanceof Error ? error.message : String(error) });+ }+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const call = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { status: response.status, body: await response.json() as Record<string, any> };+ };+ const db = await engine.forBot(bot.id);+ await db.run("CREATE OR REPLACE TABLE sales AS SELECT i AS id, ['north', 'south'][1 + i % 2] AS region, (i * 10)::BIGINT AS amount FROM range(1, 11) t(i)", { connection: "bot" });+ const thread = store.createTask(bot.id, "Dashboards")!.threadId!;+ const show = (input: Record<string, unknown>) => {+ const result = chatApps.createAppCard({ bot, threadId: thread, input: { tool: "show_html", html: "<p>Dash</p>", title: "Sales board", ...input } });+ if (result instanceof Promise || !result.ok) throw new Error("not shown");+ return result.messageId;+ };+ /** The app view's bridge call: its app's bot, source conversation and the document's message. */+ const rpc = (app: { botId: string; threadId: string }, messageId: string, method: string, params?: unknown) =>+ call("POST", `/api/bots/${app.botId}/apps/${messageId}/rpc`, { threadId: app.threadId, method, ...(params === undefined ? {} : { params }) });+ const save = async (messageId: string) => {+ const saved = await call("POST", "/api/local-apps", { botId: bot.id, threadId: thread, messageId });+ if (saved.status !== 201) throw new Error(JSON.stringify(saved.body));+ return saved.body.app as { id: string; botId: string; threadId: string; manifest: { name: string; uses?: string[] } };+ };+ return { store, bot, thread, chatApps, call, show, rpc, save };+}++describe("a saved app that reads its bot's data and keeps state", () => {+ it("gets data and state in its own document, and its queries and state reach the page rpc route", async () => {+ const { call, show, rpc, save } = await fixture();+ const messageId = show({ uses: ["data", "state"] });+ const app = await save(messageId);+ expect(app.manifest).toEqual({ name: "Sales board", uses: ["data", "state"] });+ const doc = (await call("GET", `/api/local-apps/${app.id}/app`)).body;+ expect(doc).toMatchObject({ messageId, can: { data: true, state: true, message: true } });+ const rows = await rpc(app, doc.messageId, "mausbot/data/query", { sql: "SELECT region, sum(amount) AS total FROM sales GROUP BY 1 ORDER BY 1" });+ expect(rows).toMatchObject({ status: 200, body: { rows: [{ region: "north", total: 300 }, { region: "south", total: 250 }], truncated: false } });+ expect(await rpc(app, doc.messageId, "mausbot/state/set", { key: "filter", value: { region: "north" } })).toEqual({ status: 200, body: {} });+ expect(await rpc(app, doc.messageId, "mausbot/state/get", { key: "filter" })).toEqual({ status: 200, body: { value: { region: "north" } } });+ });++ it("keeps the declared abilities when the bot replaces the page without saying, and a page without them gets none", async () => {+ const { call, show, chatApps, bot, thread, save } = await fixture();+ const messageId = show({ uses: ["data"] });+ const app = await save(messageId);+ chatApps.createAppCard({ bot, threadId: thread, input: { tool: "update_html", app_id: messageId, html: "<p>Dash 2</p>" } });+ const followed = (await call("GET", `/api/local-apps/${app.id}`)).body.app;+ expect(followed).toMatchObject({ rev: 1, manifest: { uses: ["data"] } });+ expect((await call("GET", `/api/local-apps/${app.id}/app`)).body.can).toMatchObject({ data: true });+ const plain = await save(show({ title: "Plain" }));+ expect(plain.manifest.uses).toBeUndefined();+ const can = (await call("GET", `/api/local-apps/${plain.id}/app`)).body.can;+ expect(can.data ?? false).toBe(false);+ expect(can.state ?? false).toBe(false);+ });++ it("can no longer read live data once its chat is deleted: the route refuses, the app still opens", async () => {+ const { call, show, rpc, store, bot, thread, save } = await fixture();+ const messageId = show({ uses: ["data", "state"] });+ const app = await save(messageId);+ store.deleteTask(bot.id, thread);+ expect((await call("GET", `/api/local-apps/${app.id}`)).body.app.chat).toBe(false);+ expect((await call("GET", `/api/local-apps/${app.id}/app`)).status).toBe(200);+ expect((await rpc(app, messageId, "mausbot/data/query", { sql: "SELECT 1 AS one" })).status).toBe(404);+ expect((await rpc(app, messageId, "mausbot/state/keys")).status).toBe(404);+ });++ it("carries the connector tools a page declared into its document and manifest", async () => {+ const { call, show, save } = await fixture();+ const messageId = show({ uses: ["data", "gmail:GMAIL_FETCH_EMAILS", "gmail:GMAIL_TRASH_MESSAGE"] });+ const app = await save(messageId);+ expect(app.manifest.uses).toEqual(["data", "gmail:GMAIL_FETCH_EMAILS", "gmail:GMAIL_TRASH_MESSAGE"]);+ const { can } = (await call("GET", `/api/local-apps/${app.id}/app`)).body;+ expect(can).toMatchObject({ data: true, connectors: [{ connector: "gmail", tools: ["GMAIL_FETCH_EMAILS", "GMAIL_TRASH_MESSAGE"] }] });+ expect(can.state ?? false).toBe(false);+ });+});+diff --git a/server/routes/local-apps.test.ts b/server/routes/local-apps.test.tsnew file mode 100644index 0000000000..746ae17539--- /dev/null+++ b/server/routes/local-apps.test.ts@@ -0,0 +1,255 @@+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createServer, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { APP_DOCS_SWEEP_GRACE_MS } from "../app-docs.ts";+import { createChatApps, type ChatApps } from "../chat-apps.ts";+import { DATA_DIR } from "../config.ts";+import type { ModelSelection } from "../contracts.ts";+import { json, readBody } from "../harness/http.ts";+import { createLocalApps, type LocalApps } from "../local-apps/service.ts";+import { localAppDocRefs, localAppsFile } from "../local-apps/store.ts";+import { appDocRefs } from "../message-db.ts";+import type { RequestAuth } from "../request-auth.ts";+import { Store } from "../store.ts";+import { createLocalAppsRoutes } from "./local-apps.ts";+import { dispatchRoutes } from "./table.ts";++const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };+const servers: Server[] = [];+const closers: Array<{ close(): void }> = [];++beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));+afterEach(async () => {+ for (const one of closers.splice(0)) one.close();+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));+});++/** `seen`: which conversations a paired person (x-session) can read; the owner on this computer sees everything. */+async function fixture(seen: (person: string, threadId: string) => boolean = () => true, options: { everything?: boolean; live?: (person: string) => boolean } = {}) {+ const store = new Store(() => sonnet);+ const bot = store.createBot({ name: "Scout" });+ const other = store.createBot({ name: "Other" });+ const chatApps: ChatApps = createChatApps({ store, dataDir: DATA_DIR, sweeps: false, references: () => [...appDocRefs(), ...localAppDocRefs(DATA_DIR)] });+ const localApps: LocalApps = createLocalApps({ chat: store, docs: chatApps.docs, dataDir: DATA_DIR });+ closers.push(chatApps, localApps);+ const routes = [createLocalAppsRoutes({+ apps: localApps, store,+ visibleFor: (auth) => auth.kind === "session"+ ? { everything: options.everything === true, thread: (threadId) => seen(auth.session.id, threadId) }+ : { everything: true, thread: () => true },+ live: (auth) => auth.kind !== "session" || (options.live?.(auth.session.id) ?? true),+ threadRefusal: (auth, threadId) => (auth.kind === "session" && auth.session.id === "guest" && threadId === bot.threadId ? "Guests change only their own conversations." : null),+ })];+ const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://localhost");+ try {+ if (localApps.serveFile(req, res, url.pathname, req.method ?? "GET")) return;+ const person = req.headers["x-session"];+ const auth = (typeof person === "string"+ ? { kind: "session", session: { id: person, email: `${person}@example.com` }, via: "bearer", scopes: ["client"] }+ : { kind: "loopback", scopes: ["admin", "client"] }) as RequestAuth;+ if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, { from: "inline routes" });+ } catch (error) {+ json(res, (error as { status?: number }).status ?? 500, { error: error instanceof Error ? error.message : String(error) });+ }+ });+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ const call = async (method: string, path: string, body?: unknown, session?: string) => {+ const response = await fetch(`${base}${path}`, {+ method, headers: { "content-type": "application/json", ...(session ? { "x-session": session } : {}) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ return { status: response.status, body: await response.json() as Record<string, any> };+ };+ const page = (html = "<p>Hello</p>", title = "Sales board", threadId = bot.threadId, by = bot) => {+ const result = chatApps.createAppCard({ bot: by, threadId, input: { tool: "show_html", html, title } });+ if (result instanceof Promise || !result.ok) throw new Error("not shown");+ return result.messageId;+ };+ const update = (appId: string, html: string, threadId = bot.threadId) => {+ const result = chatApps.createAppCard({ bot, threadId, input: { tool: "update_html", app_id: appId, html } });+ if (result instanceof Promise || !result.ok) throw new Error("not updated");+ };+ const folderPage = async (threadId = bot.threadId) => {+ const root = realpathSync(mkdtempSync(join(tmpdir(), "omb-local-app-")));+ mkdirSync(join(root, "dash"));+ writeFileSync(join(root, "dash", "index.html"), "<h1>Dash</h1><script src='app.js'></script>");+ writeFileSync(join(root, "dash", "data.csv"), "region,total\nNorth,12");+ const result = await chatApps.createAppCard({ bot, threadId, input: { tool: "show_html", path: "dash", title: "Dash" }, folders: async () => ({ roots: [root], vmWorkspace: null }) });+ if (!result.ok) throw new Error(result.error);+ return result.messageId;+ };+ const save = (messageId: string, session?: string, threadId = bot.threadId, botId = bot.id) => call("POST", "/api/local-apps", { botId, threadId, messageId }, session);+ return { store, bot, other, chatApps, localApps, call, page, update, folderPage, save, base };+}++describe("local apps", () => {+ it("saves a page as an app with its title, and saving it again answers with the same app", async () => {+ const { page, save, call } = await fixture();+ const messageId = page();+ const first = await save(messageId);+ expect(first.status).toBe(201);+ expect(first.body.app).toMatchObject({ name: "Sales board", rev: 0, versions: [{ rev: 0 }], manifest: { name: "Sales board" }, chat: true });+ expect(first.body.app.id).toMatch(/^la_[\w-]{16}$/);+ const again = await save(messageId);+ expect(again.status).toBe(200);+ expect(again.body.app.id).toBe(first.body.app.id);+ expect((await call("GET", "/api/local-apps")).body.apps).toHaveLength(1);+ });++ it("follows the newest version the bot shows in that conversation and keeps the earlier ones", async () => {+ const { page, update, save, call } = await fixture();+ const messageId = page("<p>one</p>");+ const { body } = await save(messageId);+ update(messageId, "<p>two</p>");+ update(messageId, "<p>three</p>");+ const after = await call("GET", `/api/local-apps/${body.app.id}`);+ expect(after.body.app).toMatchObject({ rev: 2, versions: [{ rev: 0 }, { rev: 1 }, { rev: 2 }] });+ expect((await call("GET", `/api/local-apps/${body.app.id}/app`)).body.srcdoc).toContain("three");+ expect((await call("GET", `/api/local-apps/${body.app.id}/app?rev=0`)).body.srcdoc).toContain("one");+ });++ it("can stay on one version, and follow the newest again", async () => {+ const { page, update, save, call } = await fixture();+ const messageId = page("<p>one</p>");+ const id = (await save(messageId)).body.app.id;+ update(messageId, "<p>two</p>");+ expect((await call("PATCH", `/api/local-apps/${id}`, { pinnedRev: 0 })).body.app).toMatchObject({ rev: 0, pinnedRev: 0 });+ update(messageId, "<p>three</p>");+ expect((await call("GET", `/api/local-apps/${id}/app`)).body.srcdoc).toContain("one");+ expect((await call("PATCH", `/api/local-apps/${id}`, { pinnedRev: 9 })).status).toBe(404);+ const latest = await call("PATCH", `/api/local-apps/${id}`, { pinnedRev: null });+ expect(latest.body.app.rev).toBe(2);+ expect(latest.body.app.pinnedRev).toBeUndefined();+ });++ it("renames, and refuses an empty name", async () => {+ const { page, save, call } = await fixture();+ const id = (await save(page())).body.app.id;+ expect((await call("PATCH", `/api/local-apps/${id}`, { name: " Team\nboard " })).body.app).toMatchObject({ name: "Team board", manifest: { name: "Team board" } });+ expect((await call("PATCH", `/api/local-apps/${id}`, { name: " " })).status).toBe(400);+ });++ it("builds the document as the chat does: the same policy and abilities", async () => {+ const { page, save, call, chatApps, bot } = await fixture();+ const messageId = page();+ const id = (await save(messageId)).body.app.id;+ const doc = (await call("GET", `/api/local-apps/${id}/app`)).body;+ const chat = chatApps.appDocument(bot.threadId, messageId)!;+ expect(doc).toMatchObject({ messageId, rev: 0, csp: chat.csp, can: chat.can, network: chat.network });+ expect(doc.srcdoc).toBe(chat.srcdoc);+ });++ it("lives on after its conversation is deleted, folder files and all", async () => {+ const { store, bot, folderPage, save, call, chatApps, base } = await fixture();+ const thread = store.createTask(bot.id, "Dashboards")!.threadId!;+ const messageId = await folderPage(thread);+ const id = (await save(messageId, undefined, thread)).body.app.id;+ store.deleteTask(bot.id, thread);+ expect(chatApps.sweep()).toBe(0);+ const swept = chatApps.docs.sweep([...appDocRefs(), ...localAppDocRefs(DATA_DIR)], Date.now() + APP_DOCS_SWEEP_GRACE_MS + 1_000);+ expect(swept).toBe(0);+ const listed = (await call("GET", "/api/local-apps")).body.apps;+ expect(listed[0]).toMatchObject({ id, chat: false });+ const doc = (await call("GET", `/api/local-apps/${id}/app?origin=${encodeURIComponent(base)}`)).body;+ const files = /<base href="([^"]+)"/.exec(doc.srcdoc)?.[1];+ expect(files).toMatch(new RegExp(`^${base}/api/local-app-files/[\\w-]{43}/$`));+ const response = await fetch(`${files}data.csv`);+ expect(response.status).toBe(200);+ expect(await response.text()).toContain("North,12");+ });++ it("removing the app lets its documents be swept", async () => {+ const { store, bot, page, save, call, chatApps } = await fixture();+ const thread = store.createTask(bot.id, "Scratch")!.threadId!;+ const id = (await save(page("<p>only here</p>", "Scratch", thread), undefined, thread)).body.app.id;+ store.deleteTask(bot.id, thread);+ const later = Date.now() + APP_DOCS_SWEEP_GRACE_MS + 1_000;+ expect(chatApps.docs.sweep([...appDocRefs(), ...localAppDocRefs(DATA_DIR)], later)).toBe(0);+ expect((await call("DELETE", `/api/local-apps/${id}`)).body).toEqual({ ok: true });+ expect(JSON.parse(readFileSync(localAppsFile(DATA_DIR), "utf8")).apps).toEqual([]);+ expect(chatApps.docs.sweep([...appDocRefs(), ...localAppDocRefs(DATA_DIR)], later)).toBeGreaterThan(0);+ expect((await call("GET", `/api/local-apps/${id}`)).status).toBe(404);+ });++ it("refuses another bot's page, another conversation's page, an MCP app and a room's page", async () => {+ const { store, bot, other, chatApps, page, save } = await fixture();+ const mine = page();+ expect((await save(mine, undefined, bot.threadId, other.id)).status).toBe(404);+ expect((await save(mine, undefined, other.threadId, other.id)).status).toBe(404);+ const theirs = page("<p>theirs</p>", "Theirs", other.threadId, other);+ expect((await save(theirs, undefined, other.threadId, bot.id)).status).toBe(404);+ const stored = chatApps.docs.put({ source: "mcp", html: "<p>view</p>", data: { tool: { name: "get-time" }, network: { connect: [], resources: [] } } });+ if (!stored.ok) throw new Error("not stored");+ const mcp = store.appendMessage(bot.threadId, { role: "bot", kind: "app", text: "Get time", from: { botId: bot.id },+ app: { v: 1, source: "mcp", title: "Get time", doc: stored.doc, rev: 0, bytes: 11, border: true, network: { connect: [], resources: [] }, mcp: { server: "basic", tool: "get-time", resourceUri: "ui://basic/view" } } } as never).id;+ expect((await save(mcp)).status).toBe(409);+ const room = store.createGroup("Launch", [bot.id, other.id]);+ expect((await save(mine, undefined, room.threadId)).status).toBe(409);+ });++ it("shows a paired person only the apps they saved, from conversations they can still read", async () => {+ let annSees = true;+ const { page, save, call, bot } = await fixture((person, threadId) => person === "ann" && threadId === bot.threadId && annSees);+ const messageId = page();+ expect((await save(messageId, "bob")).status).toBe(404);+ const ann = await save(messageId, "ann");+ expect(ann.status).toBe(201);+ const id = ann.body.app.id;+ expect((await call("GET", "/api/local-apps", undefined, "bob")).body.apps).toEqual([]);+ expect((await call("GET", `/api/local-apps/${id}`, undefined, "bob")).status).toBe(404);+ expect((await call("DELETE", `/api/local-apps/${id}`, undefined, "bob")).status).toBe(404);+ expect((await call("GET", "/api/local-apps", undefined, "ann")).body.apps).toHaveLength(1);+ annSees = false;+ expect((await call("GET", `/api/local-apps/${id}/app`, undefined, "ann")).status).toBe(404);+ expect((await call("GET", "/api/local-apps")).body.apps).toHaveLength(1);+ });++ it("a guest can't save from a conversation they may not change", async () => {+ const { page, save } = await fixture();+ expect((await save(page(), "guest")).status).toBe(403);+ });++ it("carries the abilities the page declared into the app's manifest, and its newest version's after", async () => {+ const { save, chatApps, bot, call } = await fixture();+ const shown = chatApps.createAppCard({ bot, threadId: bot.threadId, input: { tool: "show_html", html: "<p>x</p>", title: "Sales board", uses: ["data", "state"] } });+ if (shown instanceof Promise || !shown.ok) throw new Error("not shown");+ const app = (await save(shown.messageId)).body.app;+ expect(app.manifest).toEqual({ name: "Sales board", uses: ["data", "state"] });+ chatApps.createAppCard({ bot, threadId: bot.threadId, input: { tool: "update_html", app_id: shown.messageId, html: "<p>y</p>", uses: ["state"] } });+ expect((await call("GET", `/api/local-apps/${app.id}`)).body.app.manifest).toEqual({ name: "Sales board", uses: ["state"] });+ chatApps.createAppCard({ bot, threadId: bot.threadId, input: { tool: "update_html", app_id: shown.messageId, html: "<p>z</p>", uses: [] } });+ expect((await call("GET", `/api/local-apps/${app.id}`)).body.app.manifest).toEqual({ name: "Sales board" });+ });+++ it("lets only whoever saved an app, or an admin, rename or remove it, and never from a conversation they may not change", async () => {+ const { page, save, call } = await fixture(() => true, { everything: true });+ const mine = (await save(page())).body.app.id;+ expect((await call("GET", `/api/local-apps/${mine}`, undefined, "bob")).status).toBe(200);+ expect((await call("PATCH", `/api/local-apps/${mine}`, { name: "Bob's now" }, "bob")).status).toBe(403);+ expect((await call("DELETE", `/api/local-apps/${mine}`, undefined, "bob")).status).toBe(403);+ const bobs = (await save(page("<p>bob</p>", "Bob's"), "bob")).body.app.id;+ expect((await call("PATCH", `/api/local-apps/${bobs}`, { name: "Bob's board" }, "bob")).body.app.name).toBe("Bob's board");+ expect((await call("PATCH", `/api/local-apps/${bobs}`, { name: "Owner's" })).status).toBe(200);+ const guests = (await save(page("<p>g</p>", "Guest's"), "ann")).body.app.id;+ expect((await call("DELETE", `/api/local-apps/${guests}`, undefined, "guest")).status).toBe(403);+ expect((await call("DELETE", `/api/local-apps/${bobs}`, undefined, "bob")).body).toEqual({ ok: true });+ });++ it("stops serving a folder app's files once the session that opened it has ended", async () => {+ let live = true;+ const { folderPage, save, call, base } = await fixture(() => true, { live: () => live });+ const id = (await save(await folderPage(), "ann")).body.app.id;+ const doc = (await call("GET", `/api/local-apps/${id}/app?origin=${encodeURIComponent(base)}`, undefined, "ann")).body;+ const files = /<base href="([^"]+)"/.exec(doc.srcdoc)![1]!;+ expect((await fetch(`${files}data.csv`)).status).toBe(200);+ live = false;+ expect((await fetch(`${files}data.csv`)).status).toBe(404);+ });+});diff --git a/server/routes/local-apps.ts b/server/routes/local-apps.tsnew file mode 100644index 0000000000..55fa9cb881--- /dev/null+++ b/server/routes/local-apps.ts@@ -0,0 +1,118 @@+import { z } from "zod";++import { LOCAL_APP_NAME_MAX, type LocalAppsList } from "../../shared/local-apps.ts";+import { webOrigin } from "../../shared/app-frame/csp.ts";+import type { LocalApps } from "../local-apps/service.ts";+import { nameOf } from "../local-apps/service.ts";+import type { LocalAppRecord } from "../local-apps/store.ts";+import { personKey } from "../person-key.ts";+import type { RequestAuth } from "../request-auth.ts";+import { PASS, type RouteHandler } from "./table.ts";++export interface LocalAppsRouteDeps {+ apps: LocalApps;+ store: {+ bot(id: string): unknown;+ botByThread(threadId: string): { id: string } | null;+ groupByThread(threadId: string): unknown;+ taskByThread(botId: string, threadId: string): unknown;+ };+ /** The same filter the GET /api/bots listing applies to this caller. */+ visibleFor(auth: RequestAuth): { everything: boolean; thread(threadId: string): boolean };+ /** On a Cloud home, a guest changes only conversations it started. */+ threadRefusal?(auth: RequestAuth, threadId: string): string | null;+ /** False once a session has ended: a folder app's files stop answering it. */+ live?(auth: RequestAuth): boolean;+}++const LIST = "/api/local-apps";+const ONE = /^\/api\/local-apps\/(la_[A-Za-z0-9_-]{16})(\/app)?$/;+const ID = /^[\w-]{1,128}$/;++const saveBody = z.object({ botId: z.string().regex(ID), threadId: z.string().regex(ID), messageId: z.string().regex(ID) }).strict();+const patchBody = z.object({ name: z.string().max(LOCAL_APP_NAME_MAX * 4).optional(), pinnedRev: z.number().int().min(0).max(999_999).nullable().optional() }).strict();++const ownerOf = (auth: RequestAuth) => (auth.kind === "session" ? personKey(auth.session) : undefined);++/** GET /api/local-apps lists the caller's saved apps; POST saves a page `{ botId, threadId, messageId }` (the same page+ * saved again answers with its app). GET, PATCH `{ name?, pinnedRev? }` and DELETE /api/local-apps/:id; GET+ * /api/local-apps/:id/app?rev=&origin= is the app's document, built as the chat builds it.+ * Security: a viewer who does not see every conversation is shown only the apps they saved, and of those only the ones+ * whose conversation, while it exists, they can still read. Saving asks the same of the page's conversation, so another+ * bot's or another conversation's page reads as one that is not there. */+export function createLocalAppsRoutes(deps: LocalAppsRouteDeps): RouteHandler {+ const { apps, store } = deps;+ const chatHas = (threadId: string) => Boolean(store.botByThread(threadId) || store.groupByThread(threadId));+ const sees = (auth: RequestAuth, record: LocalAppRecord, visible = deps.visibleFor(auth)) => {+ if (visible.everything) return true;+ if (!record.owner || record.owner !== ownerOf(auth)) return false;+ return !chatHas(record.threadId) || visible.thread(record.threadId);+ };+ /** Renaming, keeping a version and removing: whoever saved it or an admin, and never from a conversation the caller+ * may not change. */+ const mayChange = (auth: RequestAuth, record: LocalAppRecord): string | null => {+ if (!auth.scopes.includes("admin") && record.owner !== ownerOf(auth)) return "Only whoever saved this app can change it.";+ return chatHas(record.threadId) ? deps.threadRefusal?.(auth, record.threadId) ?? null : null;+ };++ return async ({ req, res, url, path, method, auth, json, readBody }) => {+ if (path === LIST) {+ if (method === "GET") {+ const visible = deps.visibleFor(auth);+ res.setHeader("cache-control", "private, no-store");+ return json(res, 200, { apps: apps.list().filter((record) => sees(auth, record, visible)).map(apps.view) } satisfies LocalAppsList);+ }+ if (method !== "POST") return PASS;+ const body = saveBody.safeParse(await readBody(req, 4_096));+ if (!body.success) return json(res, 400, { error: "Saving an app takes botId, threadId and messageId of the page." });+ const { botId, threadId, messageId } = body.data;+ if (store.groupByThread(threadId)) return json(res, 409, { error: "A page in a room can't be saved as an app." });+ if (!store.bot(botId) || !store.taskByThread(botId, threadId) || !deps.visibleFor(auth).thread(threadId)) return json(res, 404, { error: "no such conversation" });+ const refused = deps.threadRefusal?.(auth, threadId);+ if (refused) return json(res, 403, { error: refused });+ const saved = apps.save({ botId, threadId, messageId, owner: ownerOf(auth) });+ if (!saved.ok) return json(res, saved.status, { error: saved.error });+ return json(res, saved.created ? 201 : 200, { app: apps.view(saved.app) });+ }++ const m = ONE.exec(path);+ if (!m) return PASS;+ const record = apps.get(m[1]!);+ if (!record || !sees(auth, record)) return json(res, 404, { error: "No such app." });++ if (m[2]) {+ if (method !== "GET") return PASS;+ const asked = url.searchParams.get("rev");+ if (asked !== null && !/^\d{1,6}$/.test(asked)) return json(res, 400, { error: "rev must be a version number" });+ const origin = webOrigin(url.searchParams.get("origin")) ?? webOrigin(url.origin) ?? undefined;+ const viewer = { key: auth.kind === "session" ? `session:${auth.session.id}` : auth.kind,+ allowed: () => (deps.live?.(auth) ?? true) && Boolean(apps.get(record.id)) && sees(auth, apps.get(record.id)!) };+ const doc = apps.document(record.id, asked === null ? undefined : Number(asked), origin, viewer);+ if (!doc) return json(res, 404, { error: "That version of the app is no longer kept." });+ res.setHeader("cache-control", "private, no-store");+ return json(res, 200, doc);+ }++ if (method === "GET") return json(res, 200, { app: apps.view(record) });+ if (method !== "DELETE" && method !== "PATCH") return PASS;+ const refused = mayChange(auth, record);+ if (refused) return json(res, 403, { error: refused });+ if (method === "DELETE") {+ apps.remove(record.id);+ return json(res, 200, { ok: true });+ }+ const body = patchBody.safeParse(await readBody(req, 4_096));+ if (!body.success || (body.data.name === undefined && body.data.pinnedRev === undefined)) return json(res, 400, { error: "Change an app with name or pinnedRev." });+ let changed: LocalAppRecord | null = record;+ if (body.data.name !== undefined) {+ const name = nameOf(body.data.name);+ if (!name) return json(res, 400, { error: "An app needs a name." });+ changed = apps.rename(record.id, name);+ }+ if (changed && body.data.pinnedRev !== undefined) {+ changed = apps.pin(record.id, body.data.pinnedRev);+ if (!changed) return json(res, 404, { error: "That version of the app is no longer kept." });+ }+ return changed ? json(res, 200, { app: apps.view(changed) }) : json(res, 404, { error: "No such app." });+ };+}diff --git a/shared/local-apps.test.ts b/shared/local-apps.test.tsnew file mode 100644index 0000000000..b749036762--- /dev/null+++ b/shared/local-apps.test.ts@@ -0,0 +1,11 @@+import { describe, expect, it } from "vitest";++import { LOCAL_APP_ID as LINK_ID, parseAppLink } from "../electron/app-link.mjs";+import { LOCAL_APP_ID } from "./local-apps.ts";++describe("saved app ids", () => {+ it("are the same shape where the store makes them and where a link is read", () => {+ expect(LINK_ID.source).toBe(LOCAL_APP_ID.source);+ expect(parseAppLink("openmausbot://app/la_AbCdEfGhIjKlMnOp")).toEqual({ id: "la_AbCdEfGhIjKlMnOp", window: false });+ });+});diff --git a/shared/local-apps.ts b/shared/local-apps.tsnew file mode 100644index 0000000000..b70777ed3d--- /dev/null+++ b/shared/local-apps.ts@@ -0,0 +1,45 @@+import type { MausColor } from "./wire.ts";++/** A bot's page the person saved as an app: it runs on the computer or Cloud that keeps it, privately, and lives on+ * without the chat it came from. */++/** Must match LOCAL_APP_ID in electron/app-link.mjs, the one parser of a saved app's link. */+export const LOCAL_APP_ID = /^la_[A-Za-z0-9_-]{16}$/;+export const LOCAL_APP_NAME_MAX = 80;+/** The versions an app keeps, oldest dropped first: a live page can make a new one every few seconds. */+export const LOCAL_APP_VERSIONS = 20;+export const LOCAL_APPS_MAX = 200;++/** What an app says about itself. `uses` carries what its page declared it uses, when the page declared any. */+export interface LocalAppManifest {+ name: string;+ description?: string;+ uses?: string[];+}++/** GET /api/local-apps lists these; one is the answer of every change to an app. */+export interface LocalApp {+ id: string;+ name: string;+ icon?: string;+ botId: string;+ /** The bot that made it, while it is still here. */+ bot: { name: string; color: MausColor } | null;+ /** The conversation and the page's message it was saved from. */+ threadId: string;+ messageId: string;+ /** The versions it keeps, oldest first, numbered as the page numbered them (0 is the first). */+ versions: Array<{ rev: number; at: number }>;+ /** The version it shows: `pinnedRev` when the person chose one, else the newest. */+ rev: number;+ pinnedRev?: number;+ createdAt: number;+ updatedAt: number;+ manifest: LocalAppManifest;+ /** The conversation it came from is still there, so "Go to chat" has somewhere to go. */+ chat: boolean;+}++export interface LocalAppsList {+ apps: LocalApp[];+}diff --git a/src/components/ThreadRefs.tsx b/src/components/ThreadRefs.tsxindex d845e1d2ff..5b10ad33dd 100644--- a/src/components/ThreadRefs.tsx+++ b/src/components/ThreadRefs.tsx@@ -1,4 +1,6 @@import { MentionText } from "./MentionText";+import { parseAppLink } from "../../electron/app-link.mjs";+import { openLocalApp } from "@/lib/local-apps";import type { MentionPeer } from "@/lib/mentions";import { createContext, Fragment, useContext, useMemo, useRef, type ReactNode } from "react";import { botOpensTo, openBot, openThread, useStore, type Action, type AppState, type Bot, type Group, type ThreadTarget } from "@/state/store";@@ -75,6 +77,12 @@ export function ThreadLink({ target, ambiguous, children }: { target: ThreadLink/** Security: a link from outside the app only navigates. */export function openChatLink(dispatch: (action: Action) => void, link: string, state: AppState, threadsShown: boolean): boolean {+ const appId = parseAppLink(link)?.id;+ if (appId) {+ openLocalApp(appId);+ dispatch({ type: "showPublishedApps" });+ return true;+ }const openOwner = (id: string) => {const bot = state.bots.find((candidate) => candidate.id === id);if (bot) {diff --git a/src/components/app/AppFrame.tsx b/src/components/app/AppFrame.tsxindex d441e95783..65327bcff2 100644--- a/src/components/app/AppFrame.tsx+++ b/src/components/app/AppFrame.tsx@@ -2,7 +2,7 @@ import { useLayoutEffect, useRef, type MutableRefObject } from "react";import { appVersion, openExternalLink } from "@/lib/app-links";import { useStore } from "@/state/store";import type { AppBlockedReason, AppDocument } from "../../../shared/app";-import { RPC_HOST_REFUSED, type JsonRpcError } from "../../../shared/app-frame/bridge";+import { PAGE_RPC_METHODS, RPC_HOST_REFUSED, type JsonRpcError } from "../../../shared/app-frame/bridge";import { callAppRpc, newAppSendId, postAppContext, sendAppMessage } from "./app-api";import { mountAppFrame, type AppSelection } from "./app-frame-host";import { appHostContext, appMaxHeight, appThemeContext } from "./app-host-context";@@ -39,6 +39,8 @@ export interface AppFrameProps {onHeading?(heading: boolean | null): void;/** Takes the page's message instead of sending it. */onDraft?(text: string): void;+ /** Why the page's data and state calls can't be answered here (a saved app whose chat is gone): they fail with it. */+ pageRefusal?: string;}const refusal = (message: string): JsonRpcError => ({ code: RPC_HOST_REFUSED, message });@@ -70,6 +72,8 @@ export function AppFrame(props: AppFrameProps) {onHeading: (heading) => latest.current.onHeading?.(heading),adapter: {async callRpc(method, params) {+ const refused = latest.current.pageRefusal;+ if (refused && (PAGE_RPC_METHODS as readonly string[]).includes(method)) throw refusal(refused);const outcome = await callAppRpc({ botId, threadId, messageId, method, params });if (outcome.ok) return outcome.result;if (outcome.signIn) {diff --git a/src/components/app/AppMessage.tsx b/src/components/app/AppMessage.tsxindex 65a2d76e52..43e3671d30 100644--- a/src/components/app/AppMessage.tsx+++ b/src/components/app/AppMessage.tsx@@ -15,6 +15,7 @@ import { appendComposerDraft, appendDraftAttachments } from "@/lib/drafts";import { returnFocusToComposer } from "../AskCard";import { useCanWriteIn } from "@/lib/cloud-guest";import { closePage, onPageOpened, openPage, openPageFor } from "@/lib/open-page";+import { useSaveAsApp } from "./SaveAsApp";import { PAGE_HEIGHT, PAGE_PREVIEW_HEIGHT, PageFullScreen, PageNotes, PagePaneContext, PageToolbar, usePagePin, usePagePoint, usePageSave, usePageShare, usePageVersion } from "./PageTools";const WIDTH = "max-w-[760px]";@@ -210,7 +211,8 @@ function AppRow({ botId, botName, threadId, message, payload, pool, room }: {const share = usePageShare(threadId, message.id, message.publishedPage);const save = usePageSave(threadId, message.id, payload.title);const pin = usePagePin({ botId, threadId, messageId: message.id }, payload.title);- const tools = { version, point, share, save, room, pin, ready: Boolean(current), fullScreen: { open: fullScreen, pane: Boolean(pane), toggle: () => { point.stop(); setFullScreen((open) => !open); } } };+ const saveApp = useSaveAsApp({ botId, threadId, messageId: message.id }, room || !page || !payload.doc);+ const tools = { version, point, share, save, room, pin, saveApp, ready: Boolean(current), fullScreen: { open: fullScreen, pane: Boolean(pane), toggle: () => { point.stop(); setFullScreen((open) => !open); } } };const reloadNow = () => {setProblem(null);diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsxindex 5174b50bb5..b47304affe 100644--- a/src/components/app/PageTools.tsx+++ b/src/components/app/PageTools.tsx@@ -21,6 +21,7 @@ import { AppFrame, type AppFrameHandle } from "./AppFrame";import type { AppSelection } from "./app-frame-host";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_CHIP_PICKED, ASK_PRIMARY_BUTTON } from "../AskCard";import { serverFetch } from "@/lib/relay-server";+import { SaveAsAppButton, type useSaveAsApp } from "./SaveAsApp";/** A page starts at this height in the chat and grows to its content up to the cap, then scrolls inside. */export const PAGE_HEIGHT = { start: 520, cap: 560 } as const;@@ -210,10 +211,11 @@ export interface PageToolsProps {/** Shown in a room: the page acts for nobody, so no Share; Point sends the pick to the bot that made the page. */room?: boolean;pin?: ReturnType<typeof usePagePin>;+ saveApp?: ReturnType<typeof useSaveAsApp>;}/** The card's toolbar: ‹ v2 › and Updated on the left; Point, Share, Open in new tab and Full screen on the right. */-export function PageToolbar({ version, point, share, save, ready, fullScreen, room, pin, className }: PageToolsProps & { className?: string }) {+export function PageToolbar({ version, point, share, save, ready, fullScreen, room, pin, saveApp, className }: PageToolsProps & { className?: string }) {const label = version.latest ? t("chat.preview.version", { n: version.rev + 1 }) : t("chat.preview.versionOf", { n: version.rev + 1, count: version.last + 1 });const busy = share.share.kind === "busy";return (@@ -236,6 +238,7 @@ export function PageToolbar({ version, point, share, save, ready, fullScreen, ro<button type="button" onClick={() => void share.run(version.rev)} disabled={busy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>{busy ? <Loader2 size={14} className="animate-spin" /> : <Share2 size={14} />}{t("chat.preview.share")}</button>+ {saveApp && <SaveAsAppButton app={saveApp} />}{pin?.show && (<button type="button" data-page-pin aria-pressed={pin.pinned} onClick={pin.toggle} disabled={pin.full}title={pin.full ? t("chat.preview.pinFull", { max: MAX_WEB_PANELS }) : t(pin.pinned ? "chat.preview.unpinHint" : "chat.preview.pinHint")}@@ -257,6 +260,7 @@ export function PageToolbar({ version, point, share, save, ready, fullScreen, ro{fullScreen.open ? <X size={16} /> : <Maximize2 size={14} />}</button></div>+ {saveApp?.failed && <p role="alert" data-page-save-app-failed className="basis-full text-end text-xs text-danger">{t("localApps.page.saveFailed")}</p>}{!room && pin?.show && pin.full && <p data-page-pin-full className="basis-full text-end text-xs text-ink-secondary">{t("chat.preview.pinFull", { max: MAX_WEB_PANELS })}</p>}</div>);diff --git a/src/components/app/SaveAsApp.test.ts b/src/components/app/SaveAsApp.test.tsnew file mode 100644index 0000000000..6cc27186ad--- /dev/null+++ b/src/components/app/SaveAsApp.test.ts@@ -0,0 +1,108 @@+// @vitest-environment happy-dom+// Save as app in a page's toolbar: one click saves it under the page's title, and then it opens the app.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { BotEditorStore, type Message, type useStore } from "@/state/store";+import { resetLocalApps, useOpenLocalApp } from "@/lib/local-apps";+import type { AppPayload } from "../../../shared/app";+import { botHtmlDocument } from "../../../shared/app-frame/document";+import type { LocalApp } from "../../../shared/local-apps";+import { createAppPool } from "./app-pool";+import { AppMessage, forgetAppRows } from "./AppMessage";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const payload: AppPayload = { v: 1, source: "html", title: "Sales board", doc: "d0", rev: 0, bytes: 900, border: true, network: { connect: [], resources: [] } };+const row = (app: AppPayload = payload): Message => ({ id: "a1", role: "bot", kind: "app", at: 1, text: "[App] Sales board", app });+const SAVED: LocalApp = { id: "la_board0000000000000", name: "Sales board", botId: "pepper", bot: null, threadId: "t1", messageId: "a1", versions: [{ rev: 0, at: 1 }], rev: 0,+ createdAt: 1, updatedAt: 1, manifest: { name: "Sales board" }, chat: true };++const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+const fetchMock = vi.fn<(path: string, init?: RequestInit) => Promise<Response>>();+const dispatch = vi.fn();+const store = { state: {}, dispatch, flushBotPatches: vi.fn(async () => null) } as unknown as ReturnType<typeof useStore>;+let listed: LocalApp[];+let saveAnswer: () => Response;+let host: HTMLDivElement;+let root: Root;++function Opened() {+ return createElement("output", { "data-open": useOpenLocalApp() ?? "" });+}+const render = async (message: Message, room = false) => {+ await act(async () => {+ root.render(createElement(BotEditorStore, { value: store, children: [+ createElement(AppMessage, { key: "row", botId: "pepper", botName: "Pepper", threadId: "t1", message, pool: createAppPool({ limit: 3 }), room }),+ createElement(Opened, { key: "open" }),+ ] }));+ });+ await settle();+};+const settle = () => act(async () => { for (let i = 0; i < 8; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); });+const saveButton = () => host.querySelector<HTMLButtonElement>("[data-page-save-app]");++beforeEach(() => {+ listed = [];+ saveAnswer = () => json(201, { app: SAVED });+ fetchMock.mockReset();+ fetchMock.mockImplementation(async (path, init) => {+ const url = new URL(path, "http://omb.test");+ if (url.pathname === "/api/local-apps" && init?.method === "POST") return saveAnswer();+ if (url.pathname === "/api/local-apps") return json(200, { apps: listed });+ return json(200, botHtmlDocument({ messageId: "a1", rev: 0, html: "<p>board</p>" }));+ });+ vi.stubGlobal("fetch", fetchMock);+ vi.stubGlobal("IntersectionObserver", undefined);+ dispatch.mockReset();+ forgetAppRows();+ resetLocalApps([]);+ host = document.createElement("div");+ document.body.appendChild(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.unstubAllGlobals();+});++describe("Save as app", () => {+ it("saves the page with no questions, then reads Saved · Open and opens the app", async () => {+ await render(row());+ expect(saveButton()?.textContent).toBe("Save as app");+ await act(async () => saveButton()!.click());+ await settle();+ const post = fetchMock.mock.calls.find(([path, init]) => path.endsWith("/api/local-apps") && init?.method === "POST")!;+ expect(JSON.parse(String(post[1]!.body))).toEqual({ botId: "pepper", threadId: "t1", messageId: "a1" });+ expect(saveButton()?.textContent).toBe("Saved · Open");+ expect(document.querySelector("[role=dialog], [role=alertdialog]")).toBeNull();+ await act(async () => saveButton()!.click());+ expect(dispatch).toHaveBeenCalledWith({ type: "showPublishedApps" });+ expect(host.querySelector("[data-open]")?.getAttribute("data-open")).toBe(SAVED.id);+ expect(fetchMock.mock.calls.filter(([, init]) => init?.method === "POST")).toHaveLength(1);+ });++ it("knows a page that is already saved", async () => {+ resetLocalApps([SAVED]);+ await render(row());+ expect(saveButton()?.textContent).toBe("Saved · Open");+ });++ it("says so when the page couldn't be saved", async () => {+ saveAnswer = () => json(409, { error: "This page isn't stored, so it can't be saved as an app." });+ await render(row());+ await act(async () => saveButton()!.click());+ await settle();+ expect(host.querySelector("[data-page-save-app-failed]")?.textContent).toBe("This page couldn't be saved as an app. Try again.");+ expect(saveButton()?.textContent).toBe("Save as app");+ });++ it("is not offered in a room or for an app from an MCP server", async () => {+ await render(row(), true);+ expect(saveButton()).toBeNull();+ await render(row({ ...payload, source: "mcp", mcp: { server: "basic", tool: "get-time", resourceUri: "ui://basic/view" } }));+ expect(saveButton()).toBeNull();+ });+});diff --git a/src/components/app/SaveAsApp.tsx b/src/components/app/SaveAsApp.tsxnew file mode 100644index 0000000000..46ef367e77--- /dev/null+++ b/src/components/app/SaveAsApp.tsx@@ -0,0 +1,53 @@+import { useEffect, useState } from "react";+import { Check, Grid2x2Plus, Loader2 } from "lucide-react";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { loadLocalApps, openLocalApp, saveLocalApp, savedAppFor, useLocalApps } from "@/lib/local-apps";+import { useStoreDispatch } from "@/state/store-select";+import { ASK_CHIP, ASK_CHIP_IDLE } from "../AskCard";++const LIST_AFTER_MS = 1_500;++/** Save as app for a bot's page: saved with the page's title, no questions; once saved it opens the app instead. */+export function useSaveAsApp(page: { botId: string; threadId: string; messageId: string }, room?: boolean) {+ const dispatch = useStoreDispatch();+ const { apps } = useLocalApps();+ const [busy, setBusy] = useState(false);+ const [failed, setFailed] = useState(false);+ // The page itself loads first; which pages are saved is read once for the whole window, a moment later.+ useEffect(() => {+ if (room || apps) return undefined;+ const timer = setTimeout(() => void loadLocalApps(), LIST_AFTER_MS);+ return () => clearTimeout(timer);+ }, [room, apps]);+ const saved = savedAppFor(apps, page.threadId, page.messageId);+ const open = (id: string) => {+ openLocalApp(id);+ dispatch({ type: "showPublishedApps" });+ };+ const save = async () => {+ setBusy(true);+ setFailed(false);+ try {+ await saveLocalApp(page);+ } catch {+ setFailed(true);+ } finally {+ setBusy(false);+ }+ };+ return { show: !room, saved, busy, failed, run: () => (saved ? open(saved.id) : void save()) };+}++export function SaveAsAppButton({ app }: { app: ReturnType<typeof useSaveAsApp> }) {+ if (!app.show) return null;+ return (+ <button type="button" data-page-save-app={app.saved ? "saved" : ""} onClick={app.run} disabled={app.busy}+ title={app.saved ? t("localApps.page.savedHint") : t("localApps.page.saveHint")}+ className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>+ {app.busy ? <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />+ : app.saved ? <Check size={14} aria-hidden="true" /> : <Grid2x2Plus size={14} aria-hidden="true" />}+ <span role="status">{app.saved ? t("localApps.page.saved") : t("localApps.page.save")}</span>+ </button>+ );+}diff --git a/src/components/published-apps/LocalAppCard.tsx b/src/components/published-apps/LocalAppCard.tsxnew file mode 100644index 0000000000..4b49592ed9--- /dev/null+++ b/src/components/published-apps/LocalAppCard.tsx@@ -0,0 +1,102 @@+import { useEffect, useRef, useState } from "react";+import { AppWindowMac, MessageSquare, MonitorDown, MonitorUp, MoreHorizontal, Pencil, Trash2 } from "lucide-react";++import type { LocalApp } from "../../../shared/local-apps";+import { t } from "@/lib/i18n";+import { relativeTime } from "@/lib/memory";+import type { Bot } from "@/state/store";+import { SidebarPopoverMenu, type SidebarMenuItem } from "../SidebarPopoverMenu";+import { LocalAppThumb } from "./LocalAppThumb";++export { LocalAppMark } from "./LocalAppMark";++export const LOCAL_APP_FIELD = "min-w-0 flex-1 rounded-lg border border-hairline bg-inset px-2 py-0.5 text-[15px] font-semibold text-ink outline-none focus:border-focus";++/** Rename in place: Enter or leaving the field keeps the name, Esc keeps the old one. */+export function InlineName({ name, onDone }: { name: string; onDone: (next: string | null) => void }) {+ const [value, setValue] = useState(name);+ const field = useRef<HTMLInputElement>(null);+ const done = useRef(false);+ useEffect(() => { field.current?.focus(); field.current?.select(); }, []);+ const finish = (next: string | null) => {+ if (done.current) return;+ done.current = true;+ onDone(next === null || !next.trim() || next.trim() === name ? null : next.trim());+ };+ return (+ <input ref={field} dir="auto" value={value} maxLength={80} aria-label={t("localApps.card.nameLabel")} data-local-app-name-field=""+ onChange={(event) => setValue(event.target.value)} onBlur={() => finish(value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") { event.preventDefault(); finish(value); }+ if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); finish(null); }+ }}+ className={LOCAL_APP_FIELD} />+ );+}++/** 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[] {+ 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 }];+}++export function InstalledMark() {+ return <span data-local-app-installed="" className="shrink-0 rounded-full bg-ink/[0.06] px-1.5 text-[11px] leading-4 text-ink-secondary">{t("localApps.install.installed")}</span>;+}++export function LocalAppCard({ app, bot, onOpen, onOpenWindow, onRename, onGoToChat, onRemove, install }: {+ app: LocalApp;+ bot?: Bot;+ onOpen: () => void;+ /** Absent outside the desktop app. */+ onOpenWindow?: () => void;+ onRename: (name: string) => void;+ /** Absent when the chat it came from is gone. */+ onGoToChat?: () => void;+ onRemove: () => void;+ /** Present only where this computer can install launchers. */+ install?: { installed: boolean; run(): void };+}) {+ const [renaming, setRenaming] = useState(false);+ const maker = bot?.name ?? app.bot?.name;+ const facts = [maker ?? t("localApps.card.botGone"), relativeTime(app.updatedAt)].join(" · ");+ const items: SidebarMenuItem[] = [+ { key: "rename", label: t("localApps.card.rename"), icon: <Pencil size={16} />, onSelect: () => setRenaming(true) },+ ...(onGoToChat ? [{ key: "chat", label: t("localApps.card.goToChat"), icon: <MessageSquare size={16} />, onSelect: onGoToChat }] : []),+ ...installItems(install),+ { 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">+ <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">+ <LocalAppThumb app={app} bot={bot} />+ </div>+ <div className="min-w-0 pb-3 pe-2 ps-3.5 pt-2">+ <div className="flex min-w-0 items-center gap-1">+ {renaming ? (+ <div className="relative z-[2] flex min-w-0 flex-1"><InlineName name={app.name} onDone={(next) => { setRenaming(false); if (next) onRename(next); }} /></div>+ ) : (+ <span dir="auto" data-local-app-name="" className="min-w-0 flex-1 truncate text-[15px] font-semibold leading-[22px] text-ink">{app.name}</span>+ )}+ <span className="relative z-[2] flex shrink-0 items-center">+ {onOpenWindow && (+ <button type="button" className="ui-icon-button hover:bg-ink/[0.06] hover:text-ink" onClick={onOpenWindow}+ aria-label={t("localApps.card.openWindow")} title={t("localApps.card.openWindow")}><AppWindowMac size={16} /></button>+ )}+ <SidebarPopoverMenu items={items} ariaLabel={t("localApps.card.more", { name: app.name })} placement="below" align="end"+ triggerTitle={t("localApps.card.more", { name: app.name })} triggerClassName="ui-icon-button hover:bg-ink/[0.06] hover:text-ink aria-expanded:bg-ink/[0.06]"+ renderTrigger={() => <MoreHorizontal size={16} aria-hidden="true" />} />+ </span>+ </div>+ <span className="flex min-w-0 items-center gap-1.5 pe-1.5">+ <span dir="auto" className="min-w-0 truncate text-[13px] leading-[18px] text-ink-secondary" title={facts}>{facts}</span>+ {install?.installed && <InstalledMark />}+ </span>+ </div>+ </li>+ );+}diff --git a/src/components/published-apps/LocalAppMark.tsx b/src/components/published-apps/LocalAppMark.tsxnew file mode 100644index 0000000000..5ba0e97e4f--- /dev/null+++ b/src/components/published-apps/LocalAppMark.tsx@@ -0,0 +1,17 @@+import type { LocalApp } from "../../../shared/local-apps";+import { cn } from "@/lib/cn";+import { appInitial } from "@/lib/published-apps";+import type { Bot } from "@/state/store";++/** The app's mark: its first letter on a plate in the colour of the bot that made it, plain once that bot is gone. */+export function LocalAppMark({ app, bot, size = "md" }: { app: LocalApp; bot?: Bot; size?: "lg" | "md" | "sm" }) {+ const color = (bot ?? app.bot)?.color;+ return (+ <span aria-hidden="true" data-bot-color={color}+ className={cn("flex shrink-0 select-none items-center justify-center rounded-xl font-semibold leading-none",+ size === "lg" ? "size-16 text-[28px]" : size === "md" ? "size-11 text-[20px]" : "size-7 rounded-lg text-[13px]",+ color ? "bot-identity bg-current/[0.14]" : "bg-ink/[0.06] text-ink-tertiary")}>+ {appInitial(app.name)}+ </span>+ );+}diff --git a/src/components/published-apps/LocalAppThumb.test.ts b/src/components/published-apps/LocalAppThumb.test.tsnew file mode 100644index 0000000000..3a29bc83c7--- /dev/null+++ b/src/components/published-apps/LocalAppThumb.test.ts@@ -0,0 +1,96 @@+// @vitest-environment happy-dom+// A saved app's card picture: its own page, small, sandboxed and out of reach; its mark until then and on failure.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { LocalApp } from "../../../shared/local-apps";+import { botHtmlDocument } from "../../../shared/app-frame/document";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const api = vi.hoisted(() => vi.fn());+vi.mock("@/state/api", () => ({ api, ApiError: class extends Error { status = 0; } }));+const { LocalAppThumb } = await import("./LocalAppThumb");++const app = (id: string): LocalApp => ({ id, name: "Sales board", botId: "mira", bot: { name: "Mira", color: "blue" }, threadId: "t", messageId: "m",+ versions: [{ rev: 0, at: 1 }], rev: 0, createdAt: 1, updatedAt: 1, manifest: { name: "Sales board" }, chat: true });++let root: Root;+let host: HTMLElement;+let seen: ((entries: Array<{ isIntersecting: boolean }>) => void) | null;+beforeEach(() => {+ api.mockReset();+ seen = null;+ vi.stubGlobal("IntersectionObserver", class { constructor(cb: typeof seen) { seen = cb; } observe() {} disconnect() {} });+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => { act(() => root.unmount()); host.remove(); vi.unstubAllGlobals(); });++const show = async (id: string) => {+ await act(async () => root.render(createElement(LocalAppThumb, { app: app(id) })));+};+const settle = () => act(async () => { for (let i = 0; i < 6; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); });+const thumb = () => host.querySelector<HTMLElement>("[data-local-app-thumb]")!;++describe("a saved app's card picture", () => {+ it("shows the app's mark, and fetches nothing until the card is on screen", async () => {+ await show("la_thumb000000000001");+ expect(thumb().dataset.localAppThumb).toBe("mark");+ expect(thumb().textContent).toBe("S");+ expect(api).not.toHaveBeenCalled();+ expect(host.querySelector("iframe")).toBeNull();+ });++ it("draws the page in a frame with the chat's sandbox that takes no pointer, keyboard or focus", async () => {+ api.mockResolvedValue(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>board</p>" }));+ await show("la_thumb000000000002");+ await act(async () => seen!([{ isIntersecting: true }]));+ await settle();+ const frame = host.querySelector("iframe")!;+ expect(frame.getAttribute("sandbox")).toBe("allow-scripts allow-forms");+ expect(frame.getAttribute("tabindex")).toBe("-1");+ expect(frame.getAttribute("aria-hidden")).toBe("true");+ expect(frame.hasAttribute("inert")).toBe(true);+ expect(frame.className).toContain("pointer-events-none");+ expect(frame.getAttribute("srcdoc")).toContain("<p>board</p>");+ expect(api.mock.calls[0]![0]).toContain("/api/local-apps/la_thumb000000000002/app?");+ });++ it("keeps the mark when the page can't be fetched, and while the person saves data", async () => {+ api.mockRejectedValue(new Error("offline"));+ await show("la_thumb000000000003");+ await act(async () => seen!([{ isIntersecting: true }]));+ await settle();+ expect(host.querySelector("iframe")).toBeNull();+ expect(thumb().dataset.localAppThumb).toBe("mark");+ act(() => root.unmount());+ root = createRoot(host);+ vi.stubGlobal("navigator", { ...navigator, connection: { saveData: true } });+ seen = null;+ await show("la_thumb000000000004");+ expect(seen).toBeNull();+ });++ it("answers nothing the page asks: no data, state or message reaches a server", async () => {+ api.mockResolvedValue(botHtmlDocument({ messageId: "m", rev: 0, html: "<p>board</p>", uses: ["data", "state"] }));+ await show("la_thumb000000000005");+ await act(async () => seen!([{ isIntersecting: true }]));+ await settle();+ const frame = host.querySelector("iframe")!;+ const posted: unknown[] = [];+ vi.spyOn(frame.contentWindow!, "postMessage").mockImplementation((message: unknown) => { posted.push(message); });+ for (const data of [{ jsonrpc: "2.0", id: "init", method: "ui/initialize", params: {} },+ { jsonrpc: "2.0", id: "q", method: "mausbot/data/query", params: { sql: "SELECT 1" } },+ { jsonrpc: "2.0", id: "s", method: "mausbot/state/set", params: { key: "a", value: 1 } },+ { jsonrpc: "2.0", id: "m", method: "ui/message", params: { role: "user", content: [{ type: "text", text: "hi" }] } }]) {+ await act(async () => { window.dispatchEvent(new MessageEvent("message", { data, source: frame.contentWindow as unknown as MessageEventSource })); });+ }+ await settle();+ expect(posted).toEqual([]);+ expect(api).toHaveBeenCalledTimes(1);+ });+});+diff --git a/src/components/published-apps/LocalAppThumb.tsx b/src/components/published-apps/LocalAppThumb.tsxnew file mode 100644index 0000000000..2b0b03914a--- /dev/null+++ b/src/components/published-apps/LocalAppThumb.tsx@@ -0,0 +1,103 @@+import { useEffect, useRef, useState } from "react";++import type { LocalApp } from "../../../shared/local-apps";+import { fetchLocalAppDocument } from "@/lib/local-apps";+import { cn } from "@/lib/cn";+import type { Bot } from "@/state/store";+import { APP_FRAME_SANDBOX } from "../app/app-frame-host";+import { appThemeContext } from "../app/app-host-context";+import { LocalAppMark } from "./LocalAppMark";++const PAGE_WIDTH = 880, PAGE_HEIGHT = 550;+const LOAD_TIMEOUT_MS = 12_000;+/** A page that draws itself with script gets a moment before it is shown. */+const SETTLE_MS = 350;+const KEPT_DOCS = 40;+const docs = new Map<string, Promise<string>>();++function srcdocOf(app: LocalApp): Promise<string> {+ const key = `${app.id}:${app.rev}`;+ let doc = docs.get(key);+ if (!doc) {+ doc = fetchLocalAppDocument(app.id, app.rev).then((answer) => answer.srcdoc);+ doc.catch(() => docs.delete(key));+ docs.set(key, doc);+ while (docs.size > KEPT_DOCS) docs.delete(docs.keys().next().value!);+ }+ return doc;+}++function savesData(): boolean {+ const connection = (navigator as { connection?: { saveData?: boolean } }).connection;+ return connection?.saveData === true || Boolean(window.matchMedia?.("(prefers-reduced-data: reduce)").matches);+}++/**+ * A card's picture of the app: its own page drawn small, loaded only while the card is on screen. Until then, and+ * whenever it can't be shown (offline, saving data, a page that never loads), the app's mark.+ *+ * Security: the frame has the chat frame's sandbox and the document's own policy, takes no pointer or keyboard, and no+ * host answers it, so the page can't send a message, set context or call anything.+ */+export function LocalAppThumb({ app, bot }: { app: LocalApp; bot?: Bot }) {+ const box = useRef<HTMLDivElement>(null);+ const [onScreen, setOnScreen] = useState(false);+ const [scale, setScale] = useState(0.2);+ const [srcdoc, setSrcdoc] = useState<string | null>(null);+ const [shown, setShown] = useState(false);+ const [gaveUp, setGaveUp] = useState(false);+ const allowed = !savesData();++ useEffect(() => {+ const element = box.current;+ if (!element || !allowed) return;+ const size = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(() => setScale(element.clientWidth / PAGE_WIDTH));+ size?.observe(element);+ setScale(element.clientWidth / PAGE_WIDTH || 0.2);+ if (typeof IntersectionObserver === "undefined") return () => size?.disconnect();+ const watch = new IntersectionObserver((entries) => {+ const visible = entries.at(-1)?.isIntersecting === true;+ setOnScreen(visible);+ if (!visible) setShown(false);+ }, { rootMargin: "300px" });+ watch.observe(element);+ return () => { size?.disconnect(); watch.disconnect(); };+ }, [allowed]);++ useEffect(() => {+ if (!onScreen || gaveUp) return;+ let live = true;+ srcdocOf(app).then((doc) => { if (live) setSrcdoc(doc); }, () => { if (live) setGaveUp(true); });+ return () => { live = false; };+ }, [onScreen, gaveUp, app]);++ const framed = onScreen && !gaveUp && srcdoc !== null;+ useEffect(() => {+ if (!framed || shown) return;+ const timer = setTimeout(() => setGaveUp(true), LOAD_TIMEOUT_MS);+ return () => clearTimeout(timer);+ }, [framed, shown]);++ return (+ <div ref={box} data-local-app-thumb={framed && shown ? "live" : "mark"} className="relative aspect-[16/10] w-full overflow-hidden bg-inset">+ <div aria-hidden="true" className={cn("absolute inset-0 flex items-center justify-center", framed && shown && "invisible")}>+ <LocalAppMark app={app} bot={bot} size="lg" />+ </div>+ {framed && (+ <iframe+ srcDoc={srcdoc}+ title=""+ aria-hidden="true"+ tabIndex={-1}+ sandbox={APP_FRAME_SANDBOX}+ referrerPolicy="no-referrer"+ onLoad={() => setTimeout(() => setShown(true), SETTLE_MS)}+ style={{ width: PAGE_WIDTH, height: PAGE_HEIGHT, transform: `scale(${scale})`, transformOrigin: "0 0", colorScheme: appThemeContext().theme }}+ className={cn("pointer-events-none absolute left-0 top-0 select-none border-0 transition-opacity duration-200 motion-reduce:transition-none",+ shown ? "opacity-100" : "opacity-0")}+ inert+ />+ )}+ </div>+ );+}diff --git a/src/components/published-apps/LocalAppView.tsx b/src/components/published-apps/LocalAppView.tsxnew file mode 100644index 0000000000..c19f29f7f4--- /dev/null+++ b/src/components/published-apps/LocalAppView.tsx@@ -0,0 +1,180 @@+import { useEffect, useRef, useState } from "react";+import { AppWindowMac, Check, ChevronDown, Loader2, MessageSquare, MoreHorizontal } from "lucide-react";++import type { AppDocument } from "../../../shared/app";+import type { LocalApp } from "../../../shared/local-apps";+import { cn } from "@/lib/cn";+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 { SidebarPopoverMenu, type SidebarMenuItem } from "../SidebarPopoverMenu";+import { TOOL_PAGE_TITLE, ToolPage, ToolPageActions, ToolPageHeader } from "../ToolPageShell";++/** How often an open app looks for a version the bot made meanwhile. */+const FOLLOW_MS = 15_000;+const HEADER_BUTTON = "ui-button ui-button-md";++function VersionMenu({ app }: { app: LocalApp }) {+ const newest = app.versions.at(-1)?.rev ?? app.rev;+ const label = t("localApps.view.version", { n: app.rev + 1 });+ if (app.versions.length < 2) return <span data-local-app-version className="text-[13px] text-ink-tertiary tabular-nums">{label}</span>;+ const pin = (rev: number | null) => void changeLocalApp(app.id, { pinnedRev: rev }).catch(() => undefined);+ const mark = (on: boolean) => (on ? <Check size={14} aria-hidden="true" className="text-accent-text" /> : undefined);+ const items: SidebarMenuItem[] = [+ { key: "newest", label: t("localApps.view.newest"), subtitle: t("localApps.view.newestDetail"), checked: app.pinnedRev === undefined,+ trailing: mark(app.pinnedRev === undefined), onSelect: () => pin(null) },+ ...[...app.versions].reverse().map((version, index) => ({+ key: `v${version.rev}`, label: t("localApps.view.version", { n: version.rev + 1 }), checked: app.pinnedRev === version.rev, trailing: mark(app.pinnedRev === version.rev),+ separatorBefore: index === 0, onSelect: () => pin(version.rev === newest && app.pinnedRev === undefined ? null : version.rev),+ })),+ ];+ return (+ <SidebarPopoverMenu items={items} ariaLabel={t("localApps.view.versions")} placement="below" align="end" triggerTitle={t("localApps.view.versions")}+ triggerClassName="ui-pill tabular-nums" renderTrigger={() => (+ <span data-local-app-version className="flex items-center gap-1">+ {app.pinnedRev !== undefined ? t("localApps.view.kept", { n: app.rev + 1 }) : label}<ChevronDown size={12} aria-hidden="true" />+ </span>+ )} />+ );+}++type Loaded = { key: string; doc: AppDocument } | { key: string; failed: true };++/** One saved app filling the content area: the same frame, policy and bridge as the page in its chat, under a slim header. */+export function LocalAppView({ id, botOf, onBack, onGoToChat, onOpenWindow }: {+ id: string;+ botOf?: (botId: string) => Bot | undefined;+ /** Absent in the app's own window, which has nothing to go back to. */+ onBack?: () => void;+ onGoToChat?: (app: LocalApp) => (() => void) | undefined;+ onOpenWindow?: () => void;+}) {+ const { apps, status } = useLocalApps();+ const app = apps?.find((one) => one.id === id);+ const [reload, setReload] = useState(0);+ const [loaded, setLoaded] = useState<Loaded | null>(null);+ const [problem, setProblem] = useState<AppFrameProblem | null>(null);+ const handle = useRef<AppFrameHandle | null>(null);+ const back = useRef<HTMLButtonElement>(null);+ const install = useAppInstall();+ const [installFailed, setInstallFailed] = useState<string | null>(null);+ useEffect(() => { if (!install) void readInstalled(); }, [install]);++ useEffect(() => { if (!apps) void loadLocalApps(); }, [apps]);+ useEffect(() => {+ const look = () => { if (document.visibilityState !== "hidden") void loadLocalApps(); };+ const timer = setInterval(look, FOLLOW_MS);+ window.addEventListener("focus", look);+ return () => { clearInterval(timer); window.removeEventListener("focus", look); };+ }, []);+ useEffect(() => { back.current?.focus({ preventScroll: true }); }, []);++ const appId = app?.id, rev = app?.rev;+ const key = appId === undefined ? "" : `${appId}:${rev}:${reload}`;+ useEffect(() => {+ if (!key || appId === undefined) return;+ const controller = new AbortController();+ void fetchLocalAppDocument(appId, rev, controller.signal).then(+ (doc) => { if (!controller.signal.aborted) { setProblem(null); setLoaded({ key, doc }); } },+ () => { if (!controller.signal.aborted) setLoaded({ key, failed: true }); },+ );+ return () => controller.abort();+ }, [key, appId, rev]);++ const maker = (app && botOf?.(app.botId)) ?? app?.bot ?? undefined;+ const current = loaded && loaded.key === key && "doc" in loaded ? loaded.doc : null;+ const failed = loaded && loaded.key === key && "failed" in loaded;+ 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: () => {+ setInstallFailed(null);+ void (installed ? uninstallLocalApp(app.id) : installLocalApp(app))+ .catch(() => setInstallFailed(t(installed ? "localApps.install.uninstallFailed" : "localApps.install.failed", { name: app.name })));+ } } : undefined;++ const header = (+ <>+ <div className="flex min-w-0 flex-1 basis-0 items-center gap-2.5">+ {app && <LocalAppMark app={app} bot={app ? botOf?.(app.botId) : undefined} size="sm" />}+ <h1 dir="auto" className={cn(TOOL_PAGE_TITLE, "min-w-0 truncate")} title={title}>{title}</h1>+ {maker?.name && <span dir="auto" className="shrink-0 truncate text-[13px] text-ink-tertiary max-sm:hidden">{t("localApps.view.by", { bot: maker.name })}</span>}+ {installed && <span className="max-sm:hidden"><InstalledMark /></span>}+ </div>+ {app && (+ <ToolPageActions>+ <span className="flex items-center gap-1.5">+ <VersionMenu app={app} />+ {goToChat && (+ <button type="button" className={HEADER_BUTTON} onClick={goToChat} title={t("localApps.card.goToChat")}>+ <MessageSquare size={14} aria-hidden="true" /><span className="max-sm:sr-only">{t("localApps.card.goToChat")}</span>+ </button>+ )}+ {!goToChat && !app.chat && <span className="sr-only">{t("localApps.view.chatGone")}</span>}+ {onOpenWindow && (+ <button type="button" className="ui-icon-button hover:bg-ink/[0.06] hover:text-ink" onClick={onOpenWindow}+ aria-label={t("localApps.card.openWindow")} title={t("localApps.card.openWindow")}><AppWindowMac size={16} /></button>+ )}+ {installOne && (+ <SidebarPopoverMenu items={installItems(installOne)} ariaLabel={t("localApps.card.more", { name: app.name })} placement="below" align="end"+ triggerTitle={t("localApps.card.more", { name: app.name })} triggerClassName="ui-icon-button hover:bg-ink/[0.06] hover:text-ink aria-expanded:bg-ink/[0.06]"+ renderTrigger={() => <MoreHorizontal size={16} aria-hidden="true" />} />+ )}+ </span>+ </ToolPageActions>+ )}+ </>+ );++ const body = !app ? (+ <Centered>+ {status === "failed" ? <Retry text={t("localApps.view.loadFailed")} onRetry={() => void loadLocalApps()} />+ : apps ? <p className="text-[13px] text-ink-secondary">{t("localApps.view.gone")}</p>+ : <Loader2 size={18} className="animate-spin text-ink-tertiary motion-reduce:animate-none" aria-hidden="true" />}+ </Centered>+ ) : failed ? (+ <Centered><Retry text={t("localApps.view.loadFailed")} onRetry={() => setReload((count) => count + 1)} /></Centered>+ ) : current ? (+ <AppFrame key={key} doc={current} botId={app.botId} threadId={app.threadId} title={app.name} height={600} handle={handle}+ onHeight={() => {}} onProblem={setProblem} onTeardownRequested={() => onBack?.()} fill+ {...(app.chat ? {} : { pageRefusal: t("localApps.view.chatGoneData") })} />+ ) : (+ <Centered><Loader2 size={18} className="animate-spin text-ink-tertiary motion-reduce:animate-none" aria-hidden="true" /></Centered>+ );++ return (+ <ToolPage label={title || t("localApps.view.back")}>+ {onBack ? (+ <ToolPageHeader backLabel={t("localApps.view.back")} onBack={onBack} backRef={back}>{header}</ToolPageHeader>+ ) : (+ <header className="shrink-0 border-b border-hairline/35 bg-app px-4 py-3"><div className="flex flex-wrap items-center gap-2">{header}</div></header>+ )}+ {app && !app.chat && app.manifest.uses?.length ? (+ <p role="status" data-local-app-chat-gone="" className="shrink-0 border-b border-hairline/35 px-4 py-2 text-[13px] text-ink-secondary">{t("localApps.view.chatGoneData")}</p>+ ) : null}+ {installFailed && <p role="alert" className="shrink-0 border-b border-hairline/35 px-4 py-2 text-[13px] text-danger">{installFailed}</p>}+ <div data-local-app-view={id} data-local-app-state={current ? "live" : failed ? "failed" : app ? "loading" : "absent"} className="relative min-h-0 flex-1 bg-app">+ {body}+ </div>+ {problem?.kind === "offline" && (+ <p role="status" className="shrink-0 border-t border-hairline/35 px-4 py-2 text-[13px] text-ink-secondary">{t("app.strip.offline")}</p>+ )}+ </ToolPage>+ );+}++function Centered({ children }: { children: React.ReactNode }) {+ return <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 p-6 text-center">{children}</div>;+}++function Retry({ text, onRetry }: { text: string; onRetry: () => void }) {+ return (+ <>+ <p role="alert" className="text-[13px] text-ink-secondary">{text}</p>+ <button type="button" className="ui-button ui-button-md" onClick={onRetry}>{t("common.tryAgain")}</button>+ </>+ );+}diff --git a/src/components/published-apps/LocalApps.test.ts b/src/components/published-apps/LocalApps.test.tsnew file mode 100644index 0000000000..350ad0fe40--- /dev/null+++ b/src/components/published-apps/LocalApps.test.ts@@ -0,0 +1,351 @@+// @vitest-environment happy-dom+// Saved apps on the apps page: the section, its cards and their actions, and one app open in its own view.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { LocalApp } from "../../../shared/local-apps";+import { botHtmlDocument } from "../../../shared/app-frame/document";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const fixture = vi.hoisted(() => ({+ state: {+ bots: [{ id: "mira", name: "Mira", color: "blue", threadId: "main", tasks: [{ threadId: "main" }, { threadId: "sales" }] }],+ groups: [],+ config: {},+ },+ dispatch: vi.fn(),+ api: vi.fn(),+}));+class FakeApiError extends Error {+ status: number; body?: Record<string, unknown>;+ constructor(message: string, status: number, body?: Record<string, unknown>) { super(message); this.status = status; this.body = body; }+}+vi.mock("@/state/store", () => ({ useStore: () => ({ state: fixture.state, dispatch: fixture.dispatch, flushBotPatches: async () => null }), api: fixture.api, ApiError: FakeApiError }));+vi.mock("@/state/api", () => ({ api: fixture.api, ApiError: FakeApiError }));++const { PublishedAppsPage } = await import("./PublishedAppsPage");+const { REMOVE_UNDO_MS } = await import("./LocalAppsSection");+const { openLocalApp, resetLocalApps } = await import("@/lib/local-apps");+const { resetAppInstall } = await import("@/lib/local-app-install");++const NOW = Date.parse("2026-11-26T12:00:00Z");+const app = (id: string, name: string, more: Partial<LocalApp> = {}): LocalApp => ({+ id, name, botId: "mira", bot: { name: "Mira", color: "blue" }, threadId: "sales", messageId: `m-${id}`, versions: [{ rev: 0, at: NOW }], rev: 0,+ createdAt: NOW - 86_400_000, updatedAt: NOW - 2 * 3_600_000, manifest: { name }, chat: true, ...more,+});+const BOARD = app("la_board0000000000000", "Sales board", { versions: [{ rev: 0, at: NOW }, { rev: 1, at: NOW }, { rev: 2, at: NOW }], rev: 2 });+const ROTA = app("la_rota00000000000000", "Staff rota", { chat: false, botId: "gone", bot: null });++let root: Root;+let host: HTMLElement;+let saved: LocalApp[];+let published: unknown[];+const calls: Array<{ method: string; path: string; body?: unknown }> = [];++beforeEach(() => {+ vi.useFakeTimers({ now: NOW, toFake: ["Date"] });+ saved = [BOARD, ROTA];+ published = [];+ calls.length = 0;+ fixture.dispatch.mockReset();+ fixture.state.config = {};+ fixture.api.mockReset();+ fixture.api.mockImplementation(async (path: string, init?: { method?: string; body?: string }) => {+ const method = init?.method ?? "GET";+ calls.push({ method, path, ...(init?.body ? { body: JSON.parse(init.body) } : {}) });+ if (path === "/api/published-apps") return { apps: published };+ if (path.startsWith("/api/published-apps/framing")) return { framing: "blocked" };+ if (path === "/api/local-apps") return { apps: saved };+ if (path.endsWith("/rpc")) return { columns: [{ name: "region", type: "VARCHAR" }], rows: [{ region: "north" }], truncated: false };+ const one = /^\/api\/local-apps\/(la_\w+)(\/app)?/.exec(path);+ const found = saved.find((candidate) => candidate.id === one?.[1]);+ if (!one || !found) throw new FakeApiError("No such app.", 404);+ if (one[2]) {+ const rev = new URL(path, "http://omb.test").searchParams.get("rev");+ return botHtmlDocument({ messageId: found.messageId, rev: Number(rev), html: `<p>${found.name} version ${Number(rev) + 1}</p>`,+ ...(found.manifest.uses ? { uses: found.manifest.uses as Array<"data" | "state"> } : {}) });+ }+ if (method === "DELETE") { saved = saved.filter((candidate) => candidate.id !== found.id); return { ok: true }; }+ if (method === "PATCH") {+ const change = JSON.parse(init!.body!) as { name?: string; pinnedRev?: number | null };+ const next = { ...found, ...(change.name ? { name: change.name } : {}),+ ...(change.pinnedRev !== undefined ? { pinnedRev: change.pinnedRev ?? undefined, rev: change.pinnedRev ?? found.versions.at(-1)!.rev } : {}) };+ saved = saved.map((candidate) => (candidate.id === found.id ? next : candidate));+ return { app: next };+ }+ return { app: found };+ });+ resetLocalApps();+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => { act(() => root.unmount()); host.remove(); vi.useRealTimers(); vi.unstubAllGlobals(); });++const settle = () => act(async () => { for (let i = 0; i < 6; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); });+const show = async () => { await act(async () => root.render(createElement(PublishedAppsPage))); await settle(); };+const card = (id: string) => host.querySelector<HTMLElement>(`[data-local-app="${id}"]`)!;+const button = (within: ParentNode, name: string) => [...within.querySelectorAll("button")].find((one) => (one.getAttribute("aria-label") ?? one.textContent?.trim()) === name)!;+const menuItem = (name: string) => [...([...document.querySelectorAll("[role=menu]")].at(-1)?.querySelectorAll<HTMLElement>("[role=menuitem], [role=menuitemradio], [role=menuitemcheckbox]") ?? [])]+ .find((one) => one.textContent?.includes(name))!;++describe("saved apps on the apps page", () => {+ it("says how to get one when nothing is saved, above the published apps", async () => {+ saved = [];+ published = [{ id: "page-a", source: "page", title: "Bakery", url: "https://abcdefghijklmnopqrstuvwxyz.mausbot.page/", bot: { id: "mira", name: "Mira" },+ threadId: "main", publishedAt: NOW, access: "link", canDelete: true }];+ await show();+ const headings = [...host.querySelectorAll("h2")].map((heading) => heading.textContent);+ expect(headings.slice(0, 2)).toEqual(["On this computer", "Published"]);+ expect(host.querySelector("[data-local-apps-empty]")?.textContent).toBe("No saved apps yetAsk a bot to build a page, then Save as app.");+ });++ it("shows one empty state, not two, when nothing is saved or published", async () => {+ saved = [];+ await show();+ expect(host.querySelector("[data-apps-empty]")?.textContent).toBe("No apps yetAsk a bot to build a page, then save it as an app or publish it.");+ expect(host.querySelector("[data-local-apps-empty]")).toBeNull();+ expect(host.textContent).not.toContain("Nothing published yet");+ });++ it("words the place as this Cloud on a Cloud", async () => {+ fixture.state.config = { cloudHome: true };+ await show();+ expect(host.querySelector("h2")?.textContent).toBe("In this Cloud");+ });++ it("shows a card for each app with its name, its bot and when it changed", async () => {+ await show();+ expect([...host.querySelectorAll("[data-local-app-name]")].map((title) => title.textContent)).toEqual(["Sales board", "Staff rota"]);+ expect(card(BOARD.id).textContent).toContain("Mira · 2 hr ago");+ expect(card(ROTA.id).textContent).toContain("Bot removed");+ expect(button(card(BOARD.id), "Open in its own window")).toBeUndefined();+ });++ it("opens an app in its own window on the desktop", async () => {+ const openWindow = vi.fn(async () => true);+ vi.stubGlobal("ogb", { localApps: { openWindow, openChat: vi.fn() } });+ await show();+ act(() => button(card(BOARD.id), "Open in its own window").click());+ expect(openWindow).toHaveBeenCalledWith(BOARD.id);+ });++ it("renames in place, Esc keeping the old name", async () => {+ await show();+ act(() => button(card(BOARD.id), "More for Sales board").click());+ await act(async () => menuItem("Rename").click());+ const field = card(BOARD.id).querySelector<HTMLInputElement>("[data-local-app-name-field]")!;+ expect(document.activeElement).toBe(field);+ act(() => field.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })));+ expect(calls.some((call) => call.method === "PATCH")).toBe(false);+ act(() => button(card(BOARD.id), "More for Sales board").click());+ await act(async () => menuItem("Rename").click());+ const again = card(BOARD.id).querySelector<HTMLInputElement>("[data-local-app-name-field]")!;+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(again, "Team board");+ again.dispatchEvent(new Event("input", { bubbles: true }));+ });+ act(() => again.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));+ await settle();+ expect(calls.find((call) => call.method === "PATCH")).toEqual({ method: "PATCH", path: `/api/local-apps/${BOARD.id}`, body: { name: "Team board" } });+ expect(card(BOARD.id).querySelector("[data-local-app-name]")?.textContent).toBe("Team board");+ });++ it("removes at once with Undo, and tells the server only once Undo has passed", async () => {+ await show();+ vi.useFakeTimers({ now: NOW, toFake: ["Date", "setTimeout", "clearTimeout"] });+ act(() => button(card(ROTA.id), "More for Staff rota").click());+ await act(async () => menuItem("Remove").click());+ expect(card(ROTA.id)).toBeNull();+ expect(host.textContent).toContain("“Staff rota” removed.");+ act(() => button(host, "Undo").click());+ expect(card(ROTA.id)).not.toBeNull();+ act(() => button(card(ROTA.id), "More for Staff rota").click());+ await act(async () => menuItem("Remove").click());+ expect(calls.some((call) => call.method === "DELETE")).toBe(false);+ await act(async () => { await vi.advanceTimersByTimeAsync(REMOVE_UNDO_MS + 10); });+ expect(calls.filter((call) => call.method === "DELETE").map((call) => call.path)).toEqual([`/api/local-apps/${ROTA.id}`]);+ expect(host.textContent).not.toContain("removed.");+ });++ it("goes to the chat it came from, and offers no chat once it is gone", async () => {+ await show();+ act(() => button(card(BOARD.id), "More for Sales board").click());+ await act(async () => menuItem("Go to chat").click());+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "mira", threadId: "sales" });+ act(() => button(card(ROTA.id), "More for Staff rota").click());+ expect(menuItem("Go to chat")).toBeUndefined();+ });+});++describe("a saved app open in its own view", () => {+ it("fills the page with the app's frame, sandboxed as in the chat, under its name", async () => {+ await show();+ act(() => button(card(BOARD.id), "Open Sales board").click());+ await settle();+ const view = host.querySelector<HTMLElement>(`[data-local-app-view="${BOARD.id}"]`)!;+ expect(view.dataset.localAppState).toBe("live");+ expect(host.querySelector("h1")?.textContent).toBe("Sales board");+ const frame = view.querySelector("iframe")!;+ expect(frame.getAttribute("sandbox")).toBe("allow-scripts allow-forms");+ expect(frame.srcdoc).toContain("Sales board version 3");+ expect(calls.find((call) => call.path.startsWith(`/api/local-apps/${BOARD.id}/app`))!.path).toContain("rev=2");+ act(() => button(host, "Back to apps").click());+ expect(host.querySelector("[data-local-app-view]")).toBeNull();+ });++ it("keeps an earlier version from the version menu, and follows the newest again", async () => {+ openLocalApp(BOARD.id);+ await show();+ expect(host.querySelector("[data-local-app-version]")?.textContent).toBe("Version 3");+ act(() => button(host, "Versions").click());+ await act(async () => menuItem("Version 1").click());+ await settle();+ expect(calls.find((call) => call.method === "PATCH")?.body).toEqual({ pinnedRev: 0 });+ expect(host.querySelector("[data-local-app-version]")?.textContent).toBe("Version 1 · kept");+ expect(host.querySelector("iframe")!.srcdoc).toContain("Sales board version 1");+ act(() => button(host, "Versions").click());+ await act(async () => menuItem("Newest").click());+ await settle();+ expect(calls.filter((call) => call.method === "PATCH").at(-1)?.body).toEqual({ pinnedRev: null });+ expect(host.querySelector("iframe")!.srcdoc).toContain("Sales board version 3");+ });++ it("goes to the chat from the header, and has none for an app whose chat is gone", async () => {+ openLocalApp(BOARD.id);+ await show();+ act(() => button(host, "Go to chat").click());+ expect(fixture.dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "mira", threadId: "sales" });+ act(() => openLocalApp(ROTA.id));+ await settle();+ expect(button(host, "Go to chat")).toBeUndefined();+ });++ it("says so when the app is gone", async () => {+ openLocalApp("la_missing0000000000");+ await show();+ expect(host.textContent).toContain("This app is no longer here.");+ });+});++describe("installing a saved app on this computer", () => {+ let bridge: { list: ReturnType<typeof vi.fn>; install: ReturnType<typeof vi.fn>; uninstall: ReturnType<typeof vi.fn>; cleanup: ReturnType<typeof vi.fn> };+ beforeEach(() => {+ resetAppInstall();+ let installed = [BOARD.id];+ bridge = {+ list: vi.fn(async () => ({ available: true, apps: installed.map((id) => ({ id, name: "x", path: "/p" })) })),+ install: vi.fn(async (input: { id: string; name: string }) => { 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); return { ok: true, removed: true }; }),+ cleanup: vi.fn(async () => []),+ };+ vi.stubGlobal("ogb", { appInstall: bridge });+ });++ it("tidies launchers against the whole list, marks an installed app, and offers Install or Uninstall in its menu", async () => {+ await show();+ expect(bridge.cleanup).toHaveBeenCalledWith([BOARD.id, ROTA.id]);+ expect(card(BOARD.id).querySelector("[data-local-app-installed]")?.textContent).toBe("Installed");+ expect(card(ROTA.id).querySelector("[data-local-app-installed]")).toBeNull();+ act(() => button(card(BOARD.id), "More for Sales board").click());+ expect(menuItem("Uninstall")).toBeDefined();+ expect(menuItem("Install on this computer")).toBeUndefined();+ act(() => button(card(ROTA.id), "More for Staff rota").click());+ await act(async () => menuItem("Install on this computer").click());+ await settle();+ expect(bridge.install).toHaveBeenCalledWith({ id: ROTA.id, name: "Staff rota" });+ expect(card(ROTA.id).querySelector("[data-local-app-installed]")).not.toBeNull();+ expect(document.querySelector("[role=dialog], [role=alertdialog]")).toBeNull();+ });++ it("says so in one line when a launcher couldn't be written", async () => {+ bridge.install.mockResolvedValueOnce({ ok: false, reason: "failed" });+ await show();+ act(() => button(card(ROTA.id), "More for Staff rota").click());+ await act(async () => menuItem("Install on this computer").click());+ await settle();+ expect(host.querySelector("[role=alert]")?.textContent).toBe("“Staff rota” couldn't be installed on this computer. Try again.");+ });++ it("offers nothing where launchers can't be installed", async () => {+ bridge.list.mockResolvedValue({ available: false, apps: [] });+ await show();+ act(() => button(card(ROTA.id), "More for Staff rota").click());+ expect(menuItem("Install on this computer")).toBeUndefined();+ expect(host.querySelector("[data-local-app-installed]")).toBeNull();+ });++ it("uninstalls once a removal is past its Undo, and reinstalls under a new name", async () => {+ await show();+ act(() => button(card(BOARD.id), "More for Sales board").click());+ await act(async () => menuItem("Rename").click());+ const field = card(BOARD.id).querySelector<HTMLInputElement>("[data-local-app-name-field]")!;+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(field, "Team board");+ field.dispatchEvent(new Event("input", { bubbles: true }));+ });+ act(() => field.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));+ await settle();+ expect(bridge.install).toHaveBeenCalledWith({ id: BOARD.id, name: "Team board" });+ vi.useFakeTimers({ now: NOW, toFake: ["Date", "setTimeout", "clearTimeout"] });+ act(() => button(card(BOARD.id), "More for Team board").click());+ await act(async () => menuItem("Remove").click());+ expect(bridge.uninstall).not.toHaveBeenCalled();+ await act(async () => { await vi.advanceTimersByTimeAsync(REMOVE_UNDO_MS + 10); });+ expect(bridge.uninstall).toHaveBeenCalledWith(BOARD.id);+ });++ it("offers Uninstall from the app view's header, and marks it installed there", async () => {+ openLocalApp(BOARD.id);+ await show();+ expect(host.querySelector("header [data-local-app-installed]")).not.toBeNull();+ act(() => button(host, "More for Sales board").click());+ await act(async () => menuItem("Uninstall").click());+ await settle();+ expect(bridge.uninstall).toHaveBeenCalledWith(BOARD.id);+ expect(host.querySelector("header [data-local-app-installed]")).toBeNull();+ });+});++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 () => {+ window.dispatchEvent(new MessageEvent("message", { data, source: frame().contentWindow as unknown as MessageEventSource }));+ for (let i = 0; i < 4; i += 1) await new Promise((resolve) => setTimeout(resolve, 0));+ });+ let toPage: Array<{ id?: unknown; result?: unknown; error?: { message?: string } }>;+ const handshake = async () => {+ toPage = [];+ vi.spyOn(frame().contentWindow!, "postMessage").mockImplementation((message: unknown) => { toPage.push(message as never); });+ await fromPage({ jsonrpc: "2.0", id: "init", method: "ui/initialize", params: {} });+ await fromPage({ jsonrpc: "2.0", method: "ui/notifications/initialized", params: {} });+ };+ const QUERY = { jsonrpc: "2.0", id: "q1", method: "mausbot/data/query", params: { sql: "SELECT region FROM sales" } };++ it("queries its bot's data through the page route, with its source conversation and message", async () => {+ saved = [{ ...BOARD, manifest: { name: "Sales board", uses: ["data", "state"] } }];+ openLocalApp(BOARD.id);+ await show();+ await handshake();+ await fromPage(QUERY);+ const call = calls.find((one) => one.path.endsWith("/rpc"))!;+ expect(call).toEqual({ method: "POST", path: `/api/bots/mira/apps/m-${BOARD.id}/rpc`,+ body: { threadId: "sales", method: "mausbot/data/query", params: { sql: "SELECT region FROM sales" } } });+ expect(toPage.find((message) => message.id === "q1")?.result).toEqual({ columns: [{ name: "region", type: "VARCHAR" }], rows: [{ region: "north" }], truncated: false });+ expect(host.querySelector("[data-local-app-chat-gone]")).toBeNull();+ });++ it("says once that its chat was deleted, and answers the page's calls with why, asking no server", async () => {+ saved = [{ ...ROTA, manifest: { name: "Staff rota", uses: ["data"] } }];+ openLocalApp(ROTA.id);+ await show();+ expect(host.querySelector("[data-local-app-chat-gone]")?.textContent).toBe("This app's chat was deleted, so its live data and saved state aren't available.");+ await handshake();+ await fromPage(QUERY);+ expect(calls.some((one) => one.path.endsWith("/rpc"))).toBe(false);+ expect(toPage.find((message) => message.id === "q1")?.error?.message).toBe("This app's chat was deleted, so its live data and saved state aren't available.");+ });+});+diff --git a/src/components/published-apps/LocalAppsSection.tsx b/src/components/published-apps/LocalAppsSection.tsxnew file mode 100644index 0000000000..dee5a1a94c--- /dev/null+++ b/src/components/published-apps/LocalAppsSection.tsx@@ -0,0 +1,127 @@+import { useEffect, useRef, useState } from "react";+import { Grid2x2Plus } from "lucide-react";+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 type { Action, AppState } from "@/state/store";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";+import { LocalAppCard } from "./LocalAppCard";++export const REMOVE_UNDO_MS = 6_000;+export const SECTION_TITLE = "text-[17px] font-semibold text-ink";+export const APP_GRID = "grid grid-cols-[repeat(auto-fill,minmax(min(220px,100%),1fr))] gap-4";++/** The page's empty state: an icon tile, a title and one line. `big` when nothing at all is on the page yet. */+export function AppsEmpty({ title, hint, big = false, data }: { title: string; hint: string; big?: boolean; data: string }) {+ return (+ <div {...{ [`data-${data}`]: "" }} className={cn("px-6 text-center", big ? "py-16" : "py-10")}>+ <div aria-hidden="true" className="mx-auto mb-4 flex size-12 items-center justify-center rounded-2xl bg-accent/10 text-accent"><Grid2x2Plus size={22} /></div>+ <h3 className="text-[17px] font-semibold text-ink">{title}</h3>+ <p className="mx-auto mt-2 max-w-md text-balance text-[14px] leading-relaxed text-ink-secondary">{hint}</p>+ </div>+ );+}++/** The chat a saved app came from, while its bot still has it; else the bot's own chat; null once the bot is gone. */+export function chatOfApp(app: LocalApp, state: Pick<AppState, "bots">): Action | null {+ const bot = state.bots.find((candidate) => candidate.id === app.botId);+ if (!bot) return null;+ const holds = bot.threadId === app.threadId || (bot.tasks ?? []).some((task) => task.threadId === app.threadId);+ return app.chat && holds ? { type: "switchTask", botId: bot.id, threadId: app.threadId } : { type: "select", id: bot.id };+}++export function openAppWindow(id: string): (() => void) | undefined {+ const bridge = window.ogb?.localApps;+ return bridge ? () => void bridge.openWindow(id).catch(() => undefined) : undefined;+}++type Line = { kind: "removed"; app: LocalApp; undo(): void } | { kind: "failed"; text: string };++/** "On this computer" (or "In this Cloud"): the apps saved here, as tiles, each opening in its own view. */+/** `alone`: the published list is empty too, so an empty section speaks for the whole page. */+export function LocalAppsSection({ place, alone = false }: { place: "computer" | "cloud"; alone?: boolean }) {+ const bots = useStoreSelector((state) => state.bots);+ const dispatch = useStoreDispatch();+ const { apps, status } = useLocalApps();+ const [line, setLine] = useState<Line | null>(null);+ const pending = useRef(new Map<string, ReturnType<typeof setTimeout>>());+ useEffect(() => { void loadLocalApps(); }, []);+ useEffect(() => {+ const timers = pending.current;+ return () => {+ // Leaving the page settles every removal still waiting for its Undo.+ for (const [id, timer] of timers) { clearTimeout(timer); void removeLocalApp(id).catch(() => undefined); }+ timers.clear();+ };+ }, []);++ const remove = (app: LocalApp) => {+ const hidden = hideLocalApp(app.id);+ const timer = setTimeout(() => {+ pending.current.delete(app.id);+ setLine((now) => (now?.kind === "removed" && now.app.id === app.id ? null : now));+ void removeLocalApp(app.id).catch(() => {+ hidden.restore();+ setLine({ kind: "failed", text: t("localApps.removeFailed", { name: app.name }) });+ });+ }, REMOVE_UNDO_MS);+ pending.current.set(app.id, timer);+ setLine({ kind: "removed", app, undo: () => {+ clearTimeout(timer);+ pending.current.delete(app.id);+ hidden.restore();+ setLine(null);+ } });+ };+ const rename = (app: LocalApp, name: string) => {+ void changeLocalApp(app.id, { name }).catch(() => setLine({ kind: "failed", text: t("localApps.renameFailed") }));+ };+ const install = useAppInstall();+ const installOf = (app: LocalApp) => {+ 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 goToChat = (app: LocalApp) => {+ const action = chatOfApp(app, { bots });+ return action ? () => dispatch(action) : undefined;+ };++ const title = t(place === "cloud" ? "localApps.section.cloud" : "localApps.section.computer");+ return (+ <section aria-labelledby="local-apps-title" data-local-apps={apps ? apps.length : status}>+ <h2 id="local-apps-title" className={cn(SECTION_TITLE, alone && apps?.length === 0 && "sr-only")}>{title}</h2>+ <div role="status" aria-live="polite" className="empty:hidden mt-3">+ {line?.kind === "removed" && (+ <p className="flex flex-wrap items-center gap-x-3 gap-y-1 rounded-lg bg-inset px-3 py-2 text-[13px] text-ink-secondary">+ <span dir="auto" className="min-w-0 truncate">{t("localApps.removed", { name: line.app.name })}</span>+ <button type="button" onClick={line.undo} className="ms-auto font-medium text-accent-text hover:underline">{t("common.undo")}</button>+ </p>+ )}+ {line?.kind === "failed" && <p role="alert" className="rounded-lg bg-inset px-3 py-2 text-[13px] text-danger">{line.text}</p>}+ </div>+ {status === "failed" && !apps ? (+ <p role="alert" className="mt-3 flex flex-wrap items-center gap-3 text-[13px] text-ink-secondary">+ {t("localApps.loadFailed")}+ <button type="button" className="ui-button ui-button-md" onClick={() => void loadLocalApps()}>{t("common.tryAgain")}</button>+ </p>+ ) : apps && apps.length === 0 ? (+ alone+ ? <AppsEmpty data="apps-empty" title={t("localApps.emptyAll.title")} hint={t("localApps.emptyAll.body")} big />+ : <AppsEmpty data="local-apps-empty" title={t("localApps.emptyTitle")} hint={t("localApps.empty")} />+ ) : apps ? (+ <ul aria-label={title} className={`mt-3 ${APP_GRID}`}>+ {apps.map((app) => (+ <LocalAppCard key={app.id} app={app} bot={bots.find((bot) => bot.id === app.botId)}+ onOpen={() => openLocalApp(app.id)} onOpenWindow={openAppWindow(app.id)} onRename={(name) => rename(app, name)}+ onGoToChat={goToChat(app)} onRemove={() => remove(app)} install={installOf(app)} />+ ))}+ </ul>+ ) : <div aria-hidden="true" className="mt-3 h-24" />}+ </section>+ );+}diff --git a/src/components/published-apps/PublishedAppsPage.test.ts b/src/components/published-apps/PublishedAppsPage.test.tsindex dfbeae6635..7eb7fbcce1 100644--- a/src/components/published-apps/PublishedAppsPage.test.ts+++ b/src/components/published-apps/PublishedAppsPage.test.ts@@ -45,9 +45,14 @@ let host: HTMLElement;let apps: PublishedApp[];let included: { used: number; max: number } | undefined;let deleteAnswer: () => Promise<unknown>;+/** The apps saved on this computer: the page shows one empty state when there are none and nothing is published. */+let saved: unknown[] = [];+const SAVED = { id: "la_saved0000000000000", name: "Sales board", botId: "mira", bot: { name: "Mira", color: "blue" }, threadId: "main", messageId: "m1",+ versions: [{ rev: 0, at: 1 }], rev: 0, createdAt: 1, updatedAt: 1, manifest: { name: "Sales board" }, chat: true };const deletes: string[] = [];beforeEach(() => {+ saved = [];vi.useFakeTimers({ now: NOW, toFake: ["Date"] });apps = [SITE, PAGE, TEAM_ONLY, ORPHAN];included = undefined;@@ -59,6 +64,7 @@ beforeEach(() => {fixture.api.mockReset();fixture.api.mockImplementation(async (path: string, init?: { method?: string; body?: string }) => {if (path === "/api/published-apps") return { apps, ...(included ? { included } : {}) };+ if (path === "/api/local-apps") return { apps: saved };if (path === "/api/published-apps/delete" && init?.method === "POST") {const { id } = JSON.parse(init.body!) as { id: string };deletes.push(id);@@ -81,8 +87,18 @@ const button = (within: ParentNode, name: string) => [...within.querySelectorAllconst dialog = () => document.body.querySelector<HTMLElement>('[role="alertdialog"]');describe("the Published apps page", () => {+ it("says in one empty state how to get the first app when nothing is saved or published", async () => {+ apps = [];+ saved = [];+ await show();+ expect(host.querySelector("[data-apps-empty]")?.textContent).toContain("No apps yet");+ expect(host.textContent).not.toContain("Nothing published yet");+ expect(host.querySelectorAll("[data-apps-empty], [data-local-apps-empty]")).toHaveLength(1);+ });+it("says what it is for and how to get the first app when nothing is published", async () => {apps = [];+ saved = [SAVED];await show();expect(host.querySelector("h1")?.textContent).toBe("Published apps");expect(host.textContent).toContain("Nothing published yet");@@ -198,7 +214,12 @@ describe("the Published apps page", () => {});it("says the list could not be loaded and loads it on Try again", async () => {- fixture.api.mockRejectedValueOnce(new Error("offline"));+ const answer = fixture.api.getMockImplementation()!;+ let failed = false;+ fixture.api.mockImplementation(async (path: string, init?: { method?: string; body?: string }) => {+ if (path === "/api/published-apps" && !failed) { failed = true; throw new Error("offline"); }+ return answer(path, init);+ });await show();expect(host.querySelector('[role="alert"]')?.textContent).toContain("Your published apps couldn't be loaded.");await act(async () => button(host, "Try again").click());@@ -274,6 +295,7 @@ describe("apps on the hosting the Cloud plan includes", () => {it("keeps the count beside the empty page, so a new plan says what it includes", async () => {apps = [];+ saved = [SAVED];included = { used: 0, max: 5 };await show();expect(host.querySelector("[data-included-apps]")?.textContent).toBe("0 of 5 apps included in your plan");diff --git a/src/components/published-apps/PublishedAppsPage.tsx b/src/components/published-apps/PublishedAppsPage.tsxindex 8bda8e8e6c..a8f1efc148 100644--- a/src/components/published-apps/PublishedAppsPage.tsx+++ b/src/components/published-apps/PublishedAppsPage.tsx@@ -11,6 +11,10 @@ import { api, ApiError } from "@/state/api";import { useStore, type AppState } from "@/state/store";import { TOOL_PAGE_TITLE, ToolPage, ToolPageHeader } from "../ToolPageShell";import { PublishedAppCard, type DeleteProblem } from "./PublishedAppCard";+import { chatOfApp, LocalAppsSection, openAppWindow, SECTION_TITLE } from "./LocalAppsSection";+import { LocalAppView } from "./LocalAppView";+import { openLocalApp, useLocalApps, useOpenLocalApp } from "@/lib/local-apps";+import { useStoreDispatch, useStoreSelector } from "@/state/store-select";const DELETE_PROBLEMS: Record<PublishedAppDeleteRefusal, LocaleKey> = {gone: "publishedApps.delete.failed", failed: "publishedApps.delete.failed", forbidden: "publishedApps.delete.forbidden",@@ -27,11 +31,28 @@ export function chatFor(app: PublishedApp, state: Pick<AppState, "bots" | "groupreturn room ? { type: "select", id: room.id } : bot ? { type: "select", id: bot.id } : null;}-/** Everything the person's bots put online, as cards. */+/** The person's apps: the ones saved here, then everything their bots put online; or one saved app, open. */export function PublishedAppsPage() {+ const open = useOpenLocalApp();+ return open ? <OpenApp id={open} /> : <AppsList />;+}++function OpenApp({ id: open }: { id: string }) {+ const bots = useStoreSelector((state) => state.bots);+ const dispatch = useStoreDispatch();+ return (+ <LocalAppView key={open} id={open} botOf={(id) => bots.find((bot) => bot.id === id)} onBack={() => openLocalApp(null)}+ onGoToChat={(app) => { const action = chatOfApp(app, { bots }); return action ? () => { openLocalApp(null); dispatch(action); } : undefined; }}+ onOpenWindow={openAppWindow(open)} />+ );+}++function AppsList() {const { state, dispatch } = useStore();const [apps, setApps] = useState<PublishedApp[] | null>(null);const [included, setIncluded] = useState<PublishedAppsList["included"]>();+ const saved = useLocalApps().apps;+ const nothingYet = apps?.length === 0 && saved?.length === 0;const [failed, setFailed] = useState(false);const back = useRef<HTMLButtonElement>(null);const loading = useRef<AbortController | null>(null);@@ -54,7 +75,7 @@ export function PublishedAppsPage() {useEffect(() => { void load(); return () => loading.current?.abort(); }, [load]);useEffect(() => { back.current?.focus({ preventScroll: true }); }, []);- const open = (url: string) => void openExternalLink(url).catch(() => undefined);+ const openUrl = (url: string) => void openExternalLink(url).catch(() => undefined);const openChat = (app: PublishedApp): boolean => {const action = chatFor(app, state);if (action) dispatch(action);@@ -83,7 +104,10 @@ export function PublishedAppsPage() {<h1 className={TOOL_PAGE_TITLE}>{t("publishedApps.title")}</h1></ToolPageHeader><div className="min-h-0 flex-1 overflow-y-auto" data-published-apps={apps ? apps.length : "loading"}>- <div className="mx-auto w-full max-w-5xl p-4 sm:p-6">+ <div className="mx-auto flex w-full max-w-5xl flex-col gap-10 p-4 sm:p-6">+ <LocalAppsSection place={state.config?.cloudHome === true ? "cloud" : "computer"} alone={apps?.length === 0} />+ {!nothingYet && <section aria-labelledby="published-apps-title">+ <h2 id="published-apps-title" className={`${SECTION_TITLE} mb-3`}>{t("publishedApps.section.published")}</h2>{apps && included && <p data-included-apps={`${included.used}/${included.max}`} className="mb-3 text-[13px] text-ink-secondary">{t("publishedApps.included.used", included)}</p>}{failed && !apps ? (<section role="alert" className="px-6 py-16 text-center">@@ -99,11 +123,12 @@ export function PublishedAppsPage() {) : apps ? (<ul aria-label={t("publishedApps.title")} className="grid grid-cols-[repeat(auto-fill,minmax(min(340px,100%),1fr))] gap-4">{apps.map((app) => (- <PublishedAppCard key={app.id} app={app} onOpen={open} onPreview={() => preview(app)}+ <PublishedAppCard key={app.id} app={app} onOpen={openUrl} onPreview={() => preview(app)}onAsk={app.bot.name && chatFor(app, state) ? () => void openChat(app) : undefined} onDelete={() => remove(app)} />))}</ul>) : null}+ </section>}</div></div></ToolPage>diff --git a/src/hooks/use-external-chat-links.test.ts b/src/hooks/use-external-chat-links.test.tsindex 0411414b4f..23bb7fd30d 100644--- a/src/hooks/use-external-chat-links.test.ts+++ b/src/hooks/use-external-chat-links.test.ts@@ -30,6 +30,20 @@ function render(state: AppState, dispatch: (action: Action) => void) {afterEach(() => { vi.unstubAllGlobals(); fixture.effects = []; fixture.link = null; fixture.showThreads = true; });describe("useExternalChatLinks", () => {+ it("opens a saved app's link on the apps page, in that app's view", async () => {+ const { openLocalApp, openLocalAppId } = await import("@/lib/local-apps");+ openLocalApp(null);+ let deliver: ((link: string) => void) | undefined;+ vi.stubGlobal("window", { ogb: { onChatLink: (cb: (link: string) => void) => { deliver = cb; return () => {}; } } });+ const dispatch = vi.fn();+ render(loaded, dispatch);+ deliver!("openmausbot://app/la_AbCdEfGhIjKlMnOp");+ render(loaded, dispatch);+ expect(dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "showPublishedApps" }]);+ expect(openLocalAppId()).toBe("la_AbCdEfGhIjKlMnOp");+ openLocalApp(null);+ });+it("holds a link that arrives at launch until the bots have loaded, then opens it once", () => {let deliver: ((link: string) => void) | undefined;const unsubscribe = vi.fn();diff --git a/src/lib/app-icon.ts b/src/lib/app-icon.tsnew file mode 100644index 0000000000..f30c026a05--- /dev/null+++ b/src/lib/app-icon.ts@@ -0,0 +1,42 @@+// A saved app's launcher icon, drawn as its card draws its mark: the app's first letter on a plate tinted with the colour+// of the bot that made it, so the launcher looks like the card.+import type { MausColor } from "../../shared/wire";+import { appInitial } from "@/lib/published-apps";++export const APP_ICON_SIDE = 256;+const PLATE_TINT = 0.16;++function rgb(css: string): [number, number, number] | null {+ const hex = /^#([0-9a-f]{6})$/i.exec(css.trim());+ if (hex) return [0, 2, 4].map((at) => parseInt(hex[1]!.slice(at, at + 2), 16)) as [number, number, number];+ const fn = /^rgba?\((\d+)[ ,]+(\d+)[ ,]+(\d+)/i.exec(css.trim());+ return fn ? [Number(fn[1]), Number(fn[2]), Number(fn[3])] : null;+}++/** The bot's colour as the light skin draws it, or null for an app whose bot is gone. */+function identity(color: MausColor | undefined): [number, number, number] | null {+ if (!color || typeof getComputedStyle === "undefined") return null;+ return rgb(getComputedStyle(document.documentElement).getPropertyValue(`--identity-${color}`));+}++/** A small PNG of the app's mark; undefined where the page can't draw one (the launcher then gets a plain letter tile). */+export async function appIconPng(name: string, color: MausColor | undefined): Promise<Uint8Array | undefined> {+ const canvas = typeof document === "undefined" ? null : document.createElement("canvas");+ const context = canvas?.getContext?.("2d");+ if (!canvas || !context) return undefined;+ canvas.width = canvas.height = APP_ICON_SIDE;+ const ink = identity(color);+ const plate = ink ? ink.map((channel) => Math.round(255 + (channel - 255) * PLATE_TINT)) : [236, 236, 236];+ const side = APP_ICON_SIDE, inset = side * 0.06, radius = side * 0.22;+ context.fillStyle = `rgb(${plate.join(",")})`;+ context.beginPath();+ context.roundRect(inset, inset, side - inset * 2, side - inset * 2, radius);+ context.fill();+ context.fillStyle = ink ? `rgb(${ink.join(",")})` : "rgb(120,120,124)";+ context.font = `600 ${Math.round(side * 0.46)}px system-ui, -apple-system, "Segoe UI", sans-serif`;+ context.textAlign = "center";+ context.textBaseline = "middle";+ context.fillText(appInitial(name), side / 2, side / 2 + side * 0.02);+ const blob = await new Promise<Blob | null>((done) => canvas.toBlob(done, "image/png"));+ return blob ? new Uint8Array(await blob.arrayBuffer()) : undefined;+}diff --git a/src/lib/local-app-install.ts b/src/lib/local-app-install.tsnew file mode 100644index 0000000000..377792699f--- /dev/null+++ b/src/lib/local-app-install.ts@@ -0,0 +1,81 @@+// 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).+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;++let state: AppInstallState = null;+const listeners = new Set<() => void>();++const bridge = () => (typeof window === "undefined" ? undefined : window.ogb?.appInstall);++function changed(next: AppInstallState): void {+ state = next;+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+}++/** null outside the desktop app, and until the first read. */+export function useAppInstall(): AppInstallState {+ return useSyncExternalStore(subscribe, () => state, () => state);+}++export async function readInstalled(): Promise<void> {+ const install = bridge();+ if (!install) return;+ try {+ const { available, apps } = await install.list();+ changed({ available: available === true, ids: new Set(apps.map((app) => app.id)) });+ } catch {+ changed({ available: false, ids: new Set() });+ }+}++/** After the whole list of saved apps was read: launchers of apps that are gone are removed. */+export async function tidyInstalled(ids: readonly string[]): Promise<void> {+ const install = bridge();+ if (!install) return;+ await install.cleanup?.([...ids]).catch(() => undefined);+ await readInstalled();+}++/** Rejects when the launcher could not be written. */+export async function installLocalApp(app: Pick<LocalApp, "id" | "name" | "bot">): Promise<void> {+ const install = bridge();+ if (!install) throw new Error("unavailable");+ 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]) });+}++export async function uninstallLocalApp(id: string): Promise<void> {+ const install = bridge();+ 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)) });+}++export const isInstalled = (id: string) => Boolean(state?.ids.has(id));++/** The app is gone for good: so is its launcher. */+export async function afterRemoved(id: string): Promise<void> {+ if (isInstalled(id)) await uninstallLocalApp(id).catch(() => undefined);+}++/** A renamed app's launcher takes the new name. */+export async function afterRenamed(app: LocalApp): Promise<void> {+ if (isInstalled(app.id)) await installLocalApp(app).catch(() => undefined);+}++/** Test seam. */+export function resetAppInstall(next: AppInstallState = null): void {+ changed(next);+}diff --git a/src/lib/local-apps.ts b/src/lib/local-apps.tsnew file mode 100644index 0000000000..a45d311a68--- /dev/null+++ b/src/lib/local-apps.ts@@ -0,0 +1,130 @@+// The person's saved apps: one list for the whole window, read once and kept fresh after each change, and which app is+// open in its own view, if any.+import { useSyncExternalStore } from "react";+import type { AppDocument } from "../../shared/app";+import type { LocalApp, LocalAppsList } from "../../shared/local-apps";+import { api, ApiError } from "@/state/api";+import { afterRemoved, afterRenamed, tidyInstalled } from "@/lib/local-app-install";++export type LocalAppsState = { status: "idle" | "loading" | "failed"; apps: readonly LocalApp[] | null };++let state: LocalAppsState = { status: "idle", apps: null };+let openId: string | null = null;+let loading: Promise<void> | null = null;+const listeners = new Set<() => void>();++function changed(next: Partial<LocalAppsState>): void {+ state = { ...state, ...next };+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+}++export function loadLocalApps(): Promise<void> {+ loading ??= (async () => {+ if (!state.apps) changed({ status: "loading" });+ try {+ const list = await api<LocalAppsList>("/api/local-apps");+ const apps = Array.isArray(list?.apps) ? list.apps : [];+ changed({ status: "idle", apps });+ void tidyInstalled(apps.map((app) => app.id));+ } catch {+ changed({ status: "failed" });+ } finally {+ loading = null;+ }+ })();+ return loading;+}++export function useLocalApps(): LocalAppsState {+ return useSyncExternalStore(subscribe, () => state, () => state);+}++function put(app: LocalApp): void {+ if (!state.apps) {+ void loadLocalApps().then(() => { if (state.apps && !state.apps.some((one) => one.id === app.id)) put(app); });+ return;+ }+ const apps = state.apps;+ changed({ apps: apps.some((one) => one.id === app.id) ? apps.map((one) => (one.id === app.id ? app : one)) : [app, ...apps] });+}++/** The app saved from this page, once the list has been read. */+export function savedAppFor(apps: readonly LocalApp[] | null, threadId: string, messageId: string): LocalApp | undefined {+ return apps?.find((app) => app.threadId === threadId && app.messageId === messageId);+}++export async function saveLocalApp(page: { botId: string; threadId: string; messageId: string }): Promise<LocalApp> {+ const { app } = await api<{ app: LocalApp }>("/api/local-apps", { method: "POST", body: JSON.stringify(page) });+ put(app);+ return app;+}++const onePath = (id: string) => `/api/local-apps/${encodeURIComponent(id)}`;++export async function changeLocalApp(id: string, change: { name?: string; pinnedRev?: number | null }): Promise<LocalApp> {+ const { app } = await api<{ app: LocalApp }>(onePath(id), { method: "PATCH", body: JSON.stringify(change) });+ put(app);+ if (change.name !== undefined) void afterRenamed(app);+ return app;+}++/** Leaves the list at once; `restore` puts it back where it was if the person undoes before the server is told. */+export function hideLocalApp(id: string): { restore(): void } {+ const before = state.apps ?? [];+ const at = before.findIndex((app) => app.id === id);+ const app = before[at];+ changed({ apps: before.filter((one) => one.id !== id) });+ return {+ restore: () => {+ if (!app || state.apps?.some((one) => one.id === id)) return;+ const apps = [...(state.apps ?? [])];+ apps.splice(Math.min(at, apps.length), 0, app);+ changed({ apps });+ },+ };+}++export async function removeLocalApp(id: string): Promise<void> {+ try {+ await api(onePath(id), { method: "DELETE" });+ } catch (error) {+ if (!(error instanceof ApiError && error.status === 404)) throw error;+ }+ await afterRemoved(id);+}++export function localAppDocumentPath(id: string): string {+ return `${onePath(id)}/app`;+}++/** A folder page's files load from this window's own origin, where /api answers. */+export async function fetchLocalAppDocument(id: string, rev?: number, signal?: AbortSignal): Promise<AppDocument> {+ const query = new URLSearchParams({ origin: window.location.origin, ...(rev === undefined ? {} : { rev: String(rev) }) });+ return api<AppDocument>(`${localAppDocumentPath(id)}?${query}`, { signal });+}++export function openLocalApp(id: string | null): void {+ if (openId === id) return;+ openId = id;+ for (const listener of listeners) listener();+}++export function openLocalAppId(): string | null {+ return openId;+}++export function useOpenLocalApp(): string | null {+ return useSyncExternalStore(subscribe, () => openId, () => openId);+}++/** Test seam: forget the list and the open app. */+export function resetLocalApps(apps: readonly LocalApp[] | null = null): void {+ loading = null;+ openId = null;+ changed({ status: "idle", apps });+}diff --git a/src/local-app-window.test.ts b/src/local-app-window.test.tsnew file mode 100644index 0000000000..2338060658--- /dev/null+++ b/src/local-app-window.test.ts@@ -0,0 +1,60 @@+// @vitest-environment happy-dom+// A saved app in its own window: the app and its slim header only, and Go to chat hands the chat to the main window.+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { botHtmlDocument } from "../shared/app-frame/document";+import type { LocalApp } from "../shared/local-apps";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const api = vi.hoisted(() => vi.fn());+vi.mock("@/state/api", () => ({ api, ApiError: class extends Error { status = 0; } }));++const { LocalAppWindow } = await import("./local-app-window");+const { resetLocalApps } = await import("@/lib/local-apps");++const APP: LocalApp = { id: "la_board0000000000000", name: "Sales board", botId: "mira", bot: { name: "Mira", color: "blue" }, threadId: "sales", messageId: "m1",+ versions: [{ rev: 0, at: 1 }], rev: 0, createdAt: 1, updatedAt: 1, manifest: { name: "Sales board" }, chat: true };++let root: Root;+let host: HTMLElement;+beforeEach(() => {+ api.mockReset();+ api.mockImplementation(async (path: string) => (path === "/api/local-apps" ? { apps: [APP] } : botHtmlDocument({ messageId: "m1", rev: 0, html: "<p>board</p>" })));+ resetLocalApps();+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => { act(() => root.unmount()); host.remove(); vi.unstubAllGlobals(); });++const show = async () => {+ await act(async () => root.render(createElement(LocalAppWindow, { id: APP.id })));+ await act(async () => { for (let i = 0; i < 6; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); });+};++describe("an app's own window", () => {+ it("shows only the app, sandboxed, under its name, with nothing to go back to", async () => {+ await show();+ expect(host.querySelector("h1")?.textContent).toBe("Sales board");+ expect(host.querySelector("iframe")?.getAttribute("sandbox")).toBe("allow-scripts allow-forms");+ expect(host.querySelector("button[aria-label='Back to apps']")).toBeNull();+ expect(document.title).toContain("Sales board");+ });++ it("hands Go to chat to the main window as a chat link", async () => {+ const openChat = vi.fn(async () => true);+ vi.stubGlobal("ogb", { localApps: { openWindow: vi.fn(), openChat } });+ await show();+ const go = [...host.querySelectorAll("button")].find((button) => button.textContent?.includes("Go to chat"))!;+ act(() => go.click());+ expect(openChat).toHaveBeenCalledWith("openmausbot://thread/sales?bot=mira");+ });++ it("offers no chat outside the desktop app", async () => {+ await show();+ expect([...host.querySelectorAll("button")].some((button) => button.textContent?.includes("Go to chat"))).toBe(false);+ });+});diff --git a/src/local-app-window.tsx b/src/local-app-window.tsxnew file mode 100644index 0000000000..14e9d9066b--- /dev/null+++ b/src/local-app-window.tsx@@ -0,0 +1,30 @@+// A saved app in a window of its own (/local-app?id=…): only the app and its slim header, without the chat app's store,+// stream or sidebar. The frame is the same one the chat mounts.+import { useEffect, useMemo } from "react";+import { LocalAppView } from "@/components/published-apps/LocalAppView";+import { productName } from "@/lib/brand";+import { useLocalApps } from "@/lib/local-apps";+import { BotEditorStore, initialState, type useStore } from "@/state/store";++/** "Go to chat" from here brings the main window to the app's conversation. */+function chatLink(threadId: string, botId: string): string {+ return `openmausbot://thread/${encodeURIComponent(threadId)}?bot=${encodeURIComponent(botId)}`;+}++export function LocalAppWindow({ id }: { id: string }) {+ const value = useMemo(() => ({+ state: initialState, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {},+ }) as unknown as ReturnType<typeof useStore>, []);+ const { apps } = useLocalApps();+ const name = apps?.find((app) => app.id === id)?.name;+ useEffect(() => { document.title = name ? `${name} · ${productName()}` : productName(); }, [name]);+ const openChat = window.ogb?.localApps?.openChat;+ return (+ <BotEditorStore value={value}>+ <div data-local-app-window={id} className="flex h-dvh min-h-0 flex-col bg-app">+ <LocalAppView id={id}+ onGoToChat={(app) => (openChat && app.chat ? () => void openChat(chatLink(app.threadId, app.botId)).catch(() => undefined) : undefined)} />+ </div>+ </BotEditorStore>+ );+}diff --git a/src/local-apps-preview.tsx b/src/local-apps-preview.tsxnew file mode 100644index 0000000000..3e4d54b5e4--- /dev/null+++ b/src/local-apps-preview.tsx@@ -0,0 +1,207 @@+// Dev-only gallery of saved apps, served at /local-apps-preview.html; not in the packaged app. It mounts the real apps+// page, app view and page toolbar over a fake store and answers every /api request itself, so nothing reaches a server.+// ?view=list|empty|app|toolbar|window|icons &place=computer|cloud &skin=midnight|daylight &long=1 (long names) &desktop=1 (the desktop+// app's bridge: Open in its own window and Install show, the first app installed) &many=1 (13 apps) &published=0 &act=menu|rename|removed|versions (opens that state once drawn)+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { AppMessage } from "@/components/app/AppMessage";+import { PublishedAppsPage } from "@/components/published-apps/PublishedAppsPage";+import { LocalAppWindow } from "./local-app-window";+import { appIconPng } from "@/lib/app-icon";+import { loadLocale } from "@/lib/i18n";+import { openLocalApp } from "@/lib/local-apps";+import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";+import { initialState, StoreContext, type Message } from "@/state/store";+import { botHtmlDocument } from "../shared/app-frame/document";+import type { AppPayload } from "../shared/app";+import type { LocalApp } from "../shared/local-apps";+import type { PublishedApp } from "../shared/published-apps";+import "./styles.css";++const params = new URLSearchParams(location.search);+const view = params.get("view") ?? "list";+const skin = params.get("skin") ?? "midnight";+const long = params.get("long") === "1";+applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");+await loadLocale(params.get("lang") ?? "en");++const now = Date.now();+const HOUR = 3_600_000, DAY = 24 * HOUR;+const BOTS = [+ { id: "mira", name: "Mira", color: "blue", threadId: "mira-main", tasks: [{ threadId: "mira-main" }, { threadId: "sales" }], messages: [] },+ { id: "otto", name: "Otto", color: "orange", threadId: "otto-main", tasks: [{ threadId: "otto-main" }], messages: [] },+ { id: "juno", name: "Juno", color: "green", threadId: "juno-main", tasks: [{ threadId: "juno-main" }], messages: [] },+];+const app = (id: string, name: string, botId: string, updated: number, more: Partial<LocalApp> = {}): LocalApp => {+ const bot = BOTS.find((one) => one.id === botId);+ return { id: `la_${id.padEnd(16, "0")}`, name, botId, bot: bot ? { name: bot.name, color: bot.color as never } : null, threadId: bot?.tasks.at(-1)?.threadId ?? "gone", messageId: `m-${id}`,+ versions: [{ rev: 0, at: now - updated }], rev: 0, createdAt: now - 9 * DAY, updatedAt: now - updated, manifest: { name }, chat: Boolean(bot), ...more };+};+const LOCAL: LocalApp[] = view === "empty" || params.get("saved") === "0" ? [] : [+ app("sales", long ? "Quarterly sales board for the north and east regions with returns" : "Sales board", "mira", 2 * HOUR,+ { versions: [0, 1, 2].map((rev) => ({ rev, at: now - (3 - rev) * HOUR })), rev: 2 }),+ app("rota", "Staff rota", "otto", 26 * HOUR),+ app("budget", "Household budget", "juno", 3 * DAY),+ app("reading", "Reading list", "mira", 9 * DAY),+ app("tide", "Tide times", "gone", 20 * DAY, { chat: false }),+ ...(params.get("many") === "1" ? [+ app("habits", "Habit tracker", "juno", 4 * HOUR), app("trip", "Lisbon trip plan", "otto", 30 * HOUR),+ app("recipes", "Recipe box", "mira", 2 * DAY), app("invoices", "Invoice checker", "otto", 5 * DAY),+ app("garden", "Garden watering", "juno", 6 * DAY), app("books", "Book club votes", "mira", 12 * DAY),+ app("gym", "Gym log", "gone", 15 * DAY, { chat: false }), app("rent", "Rent split", "otto", 25 * DAY),+ ] : []),+];+const PUBLISHED: PublishedApp[] = [+ { id: "page-bakery", source: "page", title: "Bakery order page", url: "https://bakery.example.mausbot.page/", bot: { id: "mira", name: "Mira" }, threadId: "sales",+ publishedAt: now - 2 * HOUR, access: "link", canDelete: true },+ { id: "netlify-rota", source: "netlify", title: "Team rota", url: "https://team-rota.netlify.app/", bot: { id: "otto", name: "Otto" }, threadId: "otto-main",+ publishedAt: now - 4 * DAY, access: "netlify-team", manageUrl: "https://app.netlify.com/projects/team-rota", canDelete: true },+];++const DASHBOARD = `<!doctype html><html><head><meta charset="utf-8"><style>+:root{color-scheme:light dark;--bg:#fbfbfa;--card:#fff;--ink:#1d1d1f;--muted:#6b6b70;--line:#e6e6e3;--bar:#3f7be0;--soft:#3f7be01f;--good:#1f8a55}+@media (prefers-color-scheme:dark){:root{--bg:#141416;--card:#1c1c1f;--ink:#f1f1f2;--muted:#a1a1a8;--line:#2c2c30;--bar:#6d9df0;--soft:#6d9df026;--good:#4cc38a}}+*{box-sizing:border-box}body{margin:0;font:14px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif;background:var(--bg);color:var(--ink)}+main{max-width:1120px;margin:0 auto;padding:24px}h1{font-size:22px;margin:0 0 4px}p.sub{margin:0 0 20px;color:var(--muted)}+.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-bottom:16px}+.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px}+.kpi .label{color:var(--muted);font-size:12px}.kpi .value{font-size:26px;font-weight:600;margin-top:4px;font-variant-numeric:tabular-nums}.kpi .delta{font-size:12px;color:var(--good)}+.grid{display:grid;grid-template-columns:2fr 1fr;gap:12px}@media (max-width:720px){.grid{grid-template-columns:1fr}}+h2{font-size:14px;margin:0 0 12px}svg{display:block;width:100%;height:auto}+table{width:100%;border-collapse:collapse;font-variant-numeric:tabular-nums}td,th{padding:8px 0;border-bottom:1px solid var(--line);text-align:start}th{color:var(--muted);font-weight:500;font-size:12px}td.n{text-align:end}+.bar{height:8px;border-radius:4px;background:var(--soft)}.bar>i{display:block;height:100%;border-radius:4px;background:var(--bar)}+</style></head><body><main>+<h1>Sales board</h1><p class="sub">North and East regions · updated this morning</p>+<section class="kpis">+<div class="card kpi"><div class="label">Revenue this month</div><div class="value">€48,210</div><div class="delta">+12% on October</div></div>+<div class="card kpi"><div class="label">Orders</div><div class="value">1,284</div><div class="delta">+8%</div></div>+<div class="card kpi"><div class="label">Average order</div><div class="value">€37.55</div><div class="delta">+3%</div></div>+<div class="card kpi"><div class="label">Returns</div><div class="value">2.1%</div><div class="delta">−0.4 pts</div></div>+</section>+<section class="grid">+<div class="card"><h2>Weekly revenue</h2>+<svg viewBox="0 0 600 220" role="img" aria-label="Weekly revenue, rising from 7,900 to 12,600 euros">+<g stroke="var(--line)" stroke-width="1"><line x1="40" y1="20" x2="590" y2="20"/><line x1="40" y1="80" x2="590" y2="80"/><line x1="40" y1="140" x2="590" y2="140"/><line x1="40" y1="200" x2="590" y2="200"/></g>+<g fill="var(--muted)" font-size="11"><text x="0" y="24">€15k</text><text x="0" y="84">€10k</text><text x="0" y="144">€5k</text><text x="0" y="204">€0</text></g>+<g fill="var(--bar)">${[79, 84, 92, 88, 101, 107, 115, 126].map((value, index) => `<rect x="${58 + index * 66}" y="${200 - value * 1.2}" width="40" height="${value * 1.2}" rx="4"/>`).join("")}</g>+<g fill="var(--muted)" font-size="11">${["W40", "W41", "W42", "W43", "W44", "W45", "W46", "W47"].map((label, index) => `<text x="${66 + index * 66}" y="216">${label}</text>`).join("")}</g>+</svg></div>+<div class="card"><h2>Top products</h2><table><thead><tr><th>Product</th><th class="n">Sold</th></tr></thead><tbody>+<tr><td>Sourdough loaf<div class="bar"><i style="width:92%"></i></div></td><td class="n">412</td></tr>+<tr><td>Croissant box<div class="bar"><i style="width:71%"></i></div></td><td class="n">318</td></tr>+<tr><td>Rye bread<div class="bar"><i style="width:48%"></i></div></td><td class="n">215</td></tr>+<tr><td>Cinnamon buns<div class="bar"><i style="width:36%"></i></div></td><td class="n">160</td></tr>+</tbody></table></div>+</section></main></body></html>`;++const page = (title: string, accent: string, body: string) => `<!doctype html><html><head><meta charset="utf-8"><style>+:root{color-scheme:light dark;--bg:#fbfbfa;--card:#fff;--ink:#1d1d1f;--muted:#6b6b70;--line:#e6e6e3;--accent:${accent}}+@media (prefers-color-scheme:dark){:root{--bg:#141416;--card:#1c1c1f;--ink:#f1f1f2;--muted:#a1a1a8;--line:#2c2c30}}+*{box-sizing:border-box}body{margin:0;font:15px/1.5 system-ui,-apple-system,sans-serif;background:var(--bg);color:var(--ink)}+main{max-width:1120px;margin:0 auto;padding:32px}h1{font-size:28px;margin:0 0 20px}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:14px}+.card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:18px}.tag{display:inline-block;padding:2px 10px;border-radius:999px;background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent);font-size:13px}+table{width:100%;border-collapse:collapse}td,th{padding:10px 8px;border-bottom:1px solid var(--line);text-align:start}th{color:var(--muted);font-weight:500}+.bar{height:10px;border-radius:5px;background:var(--accent)}</style></head><body><main><h1>${title}</h1>${body}</main></body></html>`;+const ROTA = page("Staff rota", "#d9822b", `<table><tr><th>Day</th><th>Morning</th><th>Afternoon</th><th>Close</th></tr>${["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day, n) =>+ `<tr><td>${day}</td><td><span class="tag">${["Ana", "Ben", "Cleo"][n % 3]}</span></td><td><span class="tag">${["Dev", "Eli", "Fay"][n % 3]}</span></td><td>${["Gus", "Hal"][n % 2]}</td></tr>`).join("")}</table>`);+const BUDGET = page("Household budget", "#1f8a55", `<div class="grid">${[["Rent", 72], ["Food", 48], ["Transport", 22], ["Energy", 35], ["Fun", 18], ["Savings", 60]].map(([label, value]) =>+ `<div class="card"><div>${label}</div><div style="font-size:26px;font-weight:600;margin:6px 0">€${Number(value) * 13}</div><div class="bar" style="width:${value}%"></div></div>`).join("")}</div>`);+const READING = page("Reading list", "#3f7be0", `<div class="grid">${["The Overstory", "Piranesi", "Klara and the Sun", "Project Hail Mary", "Circe", "The Dispossessed"].map((book, n) =>+ `<div class="card"><div style="height:120px;border-radius:10px;background:color-mix(in srgb,var(--accent) ${12 + n * 8}%,var(--card))"></div><p style="margin:10px 0 0;font-weight:600">${book}</p></div>`).join("")}</div>`);+const PAGES = [DASHBOARD, ROTA, BUDGET, READING];++const PAGE: AppPayload = { v: 1, source: "html", title: "Sales board", doc: "d2", rev: 2, history: ["d0", "d1"], bytes: 4200, border: true, network: { connect: [], resources: [] } };+const rows: Message[] = [+ { id: "m-sales", role: "bot", kind: "app", at: now, text: "[App] Sales board", app: PAGE },+ { id: "m-plain", role: "bot", kind: "app", at: now, text: "[App] Weekly plan", app: { ...PAGE, title: "Weekly plan", doc: "d9", rev: 0, history: [] } },+];++const reply = (body: unknown, status = 200) => Response.json(body, { status });+globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url, location.href);+ const path = url.pathname;+ if (path === "/api/local-apps" && init?.method === "POST") return reply({ app: LOCAL[0] }, 201);+ if (path === "/api/local-apps") return reply({ apps: LOCAL });+ if (path === "/api/published-apps") return reply({ apps: view === "empty" || params.get("published") === "0" ? [] : PUBLISHED });+ if (path === "/api/published-apps/framing") return reply({ framing: "blocked" });+ if (path.endsWith("/app")) {+ const id = path.split("/").at(-2) ?? "";+ const html = PAGES[LOCAL.findIndex((one) => one.id === id) % PAGES.length] ?? DASHBOARD;+ return reply(botHtmlDocument({ messageId: "m-sales", rev: Number(url.searchParams.get("rev") ?? 2), html }));+ }+ return reply({ error: "not in the preview" }, 404);+};++const config = { cloudHome: params.get("place") === "cloud" };+const state = { ...initialState, hydrated: true, bots: BOTS as never, config: config as never };+const store = { state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };+if (view === "app") openLocalApp(LOCAL[0]!.id);+if (params.get("desktop") === "1" || view === "window") {+ let installed = [LOCAL[0]!.id];+ (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 })) }),+ 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 }; },+ cleanup: async () => [],+ },+ };+}++createRoot(document.getElementById("root")!).render(+ <StrictMode>+ <StoreContext.Provider value={store as never}>+ {view === "icons" ? (+ <main data-icons="" className="flex min-h-screen flex-wrap items-center justify-center gap-6 bg-app p-8" />+ ) : view === "window" ? (+ <LocalAppWindow id={LOCAL[0]!.id} />+ ) : view === "toolbar" ? (+ <main className="min-h-screen bg-app p-4 sm:p-8">+ <div className="mx-auto flex max-w-[760px] flex-col gap-6">+ {rows.map((row) => <AppMessage key={row.id} botId="mira" botName="Mira" threadId="sales" message={row} />)}+ </div>+ </main>+ ) : (+ <div className="flex h-screen bg-app"><PublishedAppsPage /></div>+ )}+ </StoreContext.Provider>+ </StrictMode>,+);++const act = params.get("act");+const click = (element: Element | null | undefined) => (element as HTMLElement | null | undefined)?.click();+const whenDrawn = (selector: string, run: () => void) => {+ const look = () => (document.querySelector(selector) ? run() : window.setTimeout(look, 50));+ look();+};+const menuRow = (name: string) => [...document.querySelectorAll("[role=menu] [role^=menuitem]")].find((row) => row.textContent?.includes(name));+const ready = () => { document.body.dataset.shotReady = ""; };+if (act === "menu" || act === "rename" || act === "removed") {+ whenDrawn("[data-thumbs-ready]", () => {+ click(document.querySelector("[data-local-app] [aria-haspopup], [data-local-app] [aria-expanded]"));+ window.setTimeout(() => {+ if (act === "rename") click(menuRow("Rename"));+ if (act === "removed") click(menuRow("Remove"));+ window.setTimeout(ready, 300);+ }, 300);+ });+}+if (act === "versions") whenDrawn("[data-local-app-version]", () => { click(document.querySelector("[data-local-app-version]")?.closest("button")); window.setTimeout(ready, 300); });+if (view === "icons") {+ whenDrawn("[data-icons]", () => void Promise.all(LOCAL.map((one) => appIconPng(one.name, one.bot?.color))).then((pngs) => {+ for (const png of pngs) {+ const image = document.createElement("img");+ if (png) image.src = URL.createObjectURL(new Blob([new Uint8Array(png)], { type: "image/png" }));+ image.width = image.height = 128;+ document.querySelector("[data-icons]")!.append(image);+ }+ window.setTimeout(ready, 300);+ }));+}+const thumbsReady = () => {+ const onScreen = [...document.querySelectorAll<HTMLElement>("[data-local-app-thumb]")].filter((thumb) => thumb.getBoundingClientRect().top < window.innerHeight);+ if (onScreen.length && onScreen.every((thumb) => thumb.dataset.localAppThumb === "live")) window.setTimeout(() => { document.body.dataset.thumbsReady = ""; }, 300);+ else window.setTimeout(thumbsReady, 100);+};+thumbsReady();diff --git a/src/locales/en.json b/src/locales/en.jsonindex 0f63876c71..4c2d69ea79 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7381,6 +7381,46 @@"publishedApps.status.takenDown": "Taken down","publishedApps.status.notLive": "Not online yet","publishedApps.included.used": "{used} of {max} apps included in your plan",+ "publishedApps.section.published": "Published",+ "localApps.section.computer": "On this computer",+ "localApps.section.cloud": "In this Cloud",+ "localApps.empty": "Ask a bot to build a page, then Save as app.",+ "localApps.emptyTitle": "No saved apps yet",+ "localApps.emptyAll.title": "No apps yet",+ "localApps.emptyAll.body": "Ask a bot to build a page, then save it as an app or publish it.",+ "localApps.loadFailed": "Your apps couldn't be loaded.",+ "localApps.page.save": "Save as app",+ "localApps.page.saved": "Saved · Open",+ "localApps.page.saveHint": "Keep this page as an app you can open without the chat",+ "localApps.page.savedHint": "Open the app",+ "localApps.page.saveFailed": "This page couldn't be saved as an app. Try again.",+ "localApps.card.openOf": "Open {name}",+ "localApps.card.openWindow": "Open in its own window",+ "localApps.card.more": "More for {name}",+ "localApps.card.rename": "Rename",+ "localApps.card.nameLabel": "App name",+ "localApps.card.goToChat": "Go to chat",+ "localApps.card.remove": "Remove",+ "localApps.card.botGone": "Bot removed",+ "localApps.removed": "“{name}” removed.",+ "localApps.removeFailed": "“{name}” couldn't be removed. Try again.",+ "localApps.renameFailed": "The new name couldn't be saved. Try again.",+ "localApps.view.back": "Back to apps",+ "localApps.view.versions": "Versions",+ "localApps.view.newest": "Newest",+ "localApps.view.newestDetail": "Shows each new version the bot makes",+ "localApps.view.version": "Version {n}",+ "localApps.view.kept": "Version {n} · kept",+ "localApps.view.chatGone": "The chat it came from was deleted",+ "localApps.view.chatGoneData": "This app's chat was deleted, so its live data and saved state aren't available.",+ "localApps.view.loadFailed": "This app couldn't be opened.",+ "localApps.view.gone": "This app is no longer here.",+ "localApps.view.by": "By {bot}",+ "localApps.install.install": "Install on this computer",+ "localApps.install.uninstall": "Uninstall",+ "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.","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.jsonindex b8d7a940c6..713554691f 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -6992,6 +6992,46 @@"publishedApps.status.takenDown": "Tirado do ar","publishedApps.status.notLive": "Ainda não está no ar","publishedApps.included.used": "{used} de {max} apps incluídos no seu plano",+ "publishedApps.section.published": "Publicados",+ "localApps.section.computer": "Neste computador",+ "localApps.section.cloud": "Neste Cloud",+ "localApps.empty": "Peça a um bot para criar uma página e use “Salvar como app”.",+ "localApps.emptyTitle": "Nenhum app salvo ainda",+ "localApps.emptyAll.title": "Nenhum app ainda",+ "localApps.emptyAll.body": "Peça a um bot para criar uma página e salve como app ou publique.",+ "localApps.loadFailed": "Não foi possível carregar seus apps.",+ "localApps.page.save": "Salvar como app",+ "localApps.page.saved": "Salvo · Abrir",+ "localApps.page.saveHint": "Guardar esta página como um app que abre sem o chat",+ "localApps.page.savedHint": "Abrir o app",+ "localApps.page.saveFailed": "Não foi possível salvar esta página como app. Tente de novo.",+ "localApps.card.openOf": "Abrir {name}",+ "localApps.card.openWindow": "Abrir em uma janela própria",+ "localApps.card.more": "Mais opções de {name}",+ "localApps.card.rename": "Renomear",+ "localApps.card.nameLabel": "Nome do app",+ "localApps.card.goToChat": "Ir para o chat",+ "localApps.card.remove": "Remover",+ "localApps.card.botGone": "Bot removido",+ "localApps.removed": "“{name}” removido.",+ "localApps.removeFailed": "Não foi possível remover “{name}”. Tente de novo.",+ "localApps.renameFailed": "Não foi possível salvar o novo nome. Tente de novo.",+ "localApps.view.back": "Voltar para os apps",+ "localApps.view.versions": "Versões",+ "localApps.view.newest": "Mais recente",+ "localApps.view.newestDetail": "Mostra cada nova versão que o bot fizer",+ "localApps.view.version": "Versão {n}",+ "localApps.view.kept": "Versão {n} · fixada",+ "localApps.view.chatGone": "O chat de onde ele veio foi excluído",+ "localApps.view.chatGoneData": "O chat deste app foi excluído. Os dados ao vivo e o estado salvo não estão disponíveis.",+ "localApps.view.loadFailed": "Não foi possível abrir este app.",+ "localApps.view.gone": "Este app não existe mais.",+ "localApps.view.by": "Feito por {bot}",+ "localApps.install.install": "Instalar neste computador",+ "localApps.install.uninstall": "Desinstalar",+ "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.","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/main.tsx b/src/main.tsxindex 9962472f8e..3ce7f0dea4 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -34,7 +34,7 @@ const pageLanguage = loadPageLanguage();// The app is its own chunk, so these pages don't parse it. Everywhere else its fetch starts now, alongside the session// read, instead of after it. A failed fetch renders as a throw, so PageBoundary offers a reload.-const PAGES_WITHOUT_THE_APP = new Set(["/home", "/pair", "/desktop-viewer"]);+const PAGES_WITHOUT_THE_APP = new Set(["/home", "/pair", "/desktop-viewer", "/local-app"]);const loadApp = () => import("./App").catch((error: unknown) => ({ default: (): never => { throw error; } }));const appPage = PAGES_WITHOUT_THE_APP.has(location.pathname) ? null : loadApp();if (appPage) startDesktopLaunchMarks();@@ -77,6 +77,11 @@ async function chooseRoot(): Promise<React.ReactNode> {const { DesktopViewer } = await import("./components/DesktopViewer");return <DesktopViewer />;}+ if (location.pathname === "/local-app") {+ const { LocalAppWindow } = await import("./local-app-window");+ await pageLanguage;+ return <LocalAppWindow id={new URLSearchParams(location.search).get("id") ?? ""} />;+ }const { default: App } = await (appPage ?? loadApp());void loadTheme();return <App />;diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex 62553af589..f83560ccb0 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -442,6 +442,12 @@ const __APP_VERSION__: string;/** Receives a chat link (openmausbot://thread/… or openmausbot://bot/…)* opened from outside the app. */onChatLink?(cb: (link: string) => void): () => void;+ /** A saved app in a window of its own, on the server this window shows; true once it is open. `openChat` brings+ * the main window to a chat link (openmausbot://thread/…) from an app's own window. */+ localApps?: {+ openWindow(id: string): Promise<boolean>;+ openChat(link: string): Promise<boolean>;+ };/** The desktop shell's app-menu Preferences… item was activated; open* app Settings. Every server's page in the window receives it, and the* bridge is absent in the browser. "cloud" is the@@ -546,6 +552,19 @@ const __APP_VERSION__: string;retry(id: string): Promise<import("../../electron/update-all-run.mjs").UpdateAllView>;onState(cb: (view: import("../../electron/update-all-run.mjs").UpdateAllView) => void): () => void;};+ /** Saved apps as launchers on this computer (electron/app-install/), this computer's own page only: a bundle in+ * ~/Applications/MausBot Apps (macOS), a Start menu shortcut (Windows), a desktop entry (Linux), each opening+ * openmausbot://app/<id>?window=1 (the app in its own window). Installing again replaces the launcher; a new name+ * 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: 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 }> }>;+ /** `ids`: every saved app's id; launchers of any other app are removed. Absent in older desktop builds. */+ cleanup?(ids: string[]): Promise<string[]>;+ };/** On a server's page from the Server menu: asks for this app's own update, from the person's click. The page* learns only what was done; the app asks in its own dialog before it restarts. Absent in older desktop builds. */appUpdate?: {