Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Train nov7-b: 16 community PRs (#4803)
Milind Soni7c03e1706d55
diff --git a/companion/src/routes.ts b/companion/src/routes.tsindex 5cf73fd051..09b6333af4 100644--- a/companion/src/routes.ts+++ b/companion/src/routes.ts@@ -110,6 +110,9 @@ const ALLOWED: ReadonlyArray<{ method: string; path: RegExp }> = [// A credential value crosses only as an HPKE envelope, bound to the// authenticated device and the exact pending card.{ method: "POST", path: /^\/api\/bots\/[\w-]+\/secret-cards\/[\w-]+\/provide$/ },+ // A typed custom secret: the harness checks thread visibility and that only+ // the conversation's own person may answer it.+ { method: "POST", path: /^\/api\/bots\/[\w-]+\/secret-cards\/[\w-]+\/save$/ },{ method: "POST", path: /^\/api\/bots\/[\w-]+\/active-branch$/ },{ method: "POST", path: /^\/api\/bots\/[\w-]+\/compact$/ },// Set me up under a new bot's greeting and the x on its chip: no more than a typed /setup.diff --git a/companion/test/routes.test.ts b/companion/test/routes.test.tsindex fd2cd3956f..6fadc9d229 100644--- a/companion/test/routes.test.ts+++ b/companion/test/routes.test.ts@@ -129,6 +129,7 @@ describe("what the app may do", () => {["POST", "/api/bots/bot_123/connector-cards/msg_2/dismiss"],["POST", "/api/bots/bot_123/secret-cards/msg_2/resume"],["POST", "/api/bots/bot_123/secret-cards/msg_2/dismiss"],+ ["POST", "/api/bots/bot_123/secret-cards/msg_2/save"],["POST", "/api/bots/bot_123/sign-in-cards/msg_3/done"],["POST", "/api/bots/bot_123/sign-in-cards/msg_3/cancel"],];@@ -270,6 +271,13 @@ describe("what it may not", () => {expect(allowed("POST", "/api/bots/bot_123/secret-cards/message_1/provide/extra")).toBe(false);});+ it("allows a typed custom secret only through the exact save verb", () => {+ expect(allowed("POST", "/api/bots/bot_123/secret-cards/message_1/save")).toBe(true);+ expect(allowed("GET", "/api/bots/bot_123/secret-cards/message_1/save")).toBe(false);+ expect(allowed("POST", "/api/bots/bot_123/secret-cards/message_1/save/extra")).toBe(false);+ expect(allowed("POST", "/api/bots/bot_123/secret-cards/message_1/saved")).toBe(false);+ });+it("allows a path only for the methods it was allowed for", () => {expect(allowed("GET", "/api/bots")).toBe(true);expect(allowed("DELETE", "/api/bots/bot_123")).toBe(false);diff --git a/docs/custom-engines.md b/docs/custom-engines.mdindex f5d2a9d72a..1fcea0ca81 100644--- a/docs/custom-engines.md+++ b/docs/custom-engines.md@@ -9,7 +9,8 @@ after editing (instance entries are read at boot).Each instance shows its driver's mark. An OpenAI-compatible server shows themark of whoever runs it, read from the host in its address: `api.deepseek.com`shows DeepSeek, `<resource>.openai.azure.com` Microsoft Azure,-`dashscope-intl.aliyuncs.com` Qwen, `openrouter.ai` OpenRouter, and so on+`dashscope-intl.aliyuncs.com` or `<workspace>.<region>.maas.aliyuncs.com` Qwen,+`openrouter.ai` OpenRouter, and so on(the list is `SERVER_HOSTS` in `server/provider-icon.ts`). A server without amark of its own, such as Groq, Together, Ollama or LM Studio, keeps the default.@@ -173,6 +174,29 @@ entry:also depends on the chosen model; the driver cannot add vision to a text-onlymodel. See [tool verification](verification/openai-tools.md) for scope and tests.+### Example: Alibaba Cloud Model Studio (Qwen)++Use the `openai-compat` instance above with your Model Studio API key and a+model ID enabled for your account. Set `config.url` to the base URL from+your Model Studio workspace, including `/compatible-mode/v1`:++| Region | Base URL |+|---|---|+| Beijing | `https://<workspace-id>.cn-beijing.maas.aliyuncs.com/compatible-mode/v1` |+| Virginia | `https://<workspace-id>.us-east-1.maas.aliyuncs.com/compatible-mode/v1` |+| Singapore | `https://<workspace-id>.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` |+| Tokyo | `https://<workspace-id>.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1` |++Replace `<workspace-id>` with your workspace ID. The API key must come from+the same region as the endpoint; a mismatch can return HTTP 401 even when+the key is valid. The older `dashscope.aliyuncs.com` and+`dashscope-intl.aliyuncs.com` addresses still work. Both address formats show+the Qwen mark; the mark identifies the service, not the selected model's+capabilities or account access.++See [Alibaba Cloud's OpenAI-compatible API guide](https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope)+for current addresses, model availability and region requirements.+## Notes- `config.json` is written with mode 0600; values in `environment` are storeddiff --git a/scripts/smoke-packaged-server.mjs b/scripts/smoke-packaged-server.mjsindex a4cf94e6dd..ebef0ea3d0 100644--- a/scripts/smoke-packaged-server.mjs+++ b/scripts/smoke-packaged-server.mjs@@ -281,6 +281,56 @@ if (listening) {} catch (error) { backupReport = { error: String(error) }; }}+// SECURITY.md's loopback promise has two halves. The backup export above proves the+// packaged desktop's own loopback may run a public mutation. The other half: the same+// request is refused when the server runs where "local" includes every bot's shell. Start+// the same bundle again at service trust and check both sides of that gate.+let serviceTrustReport = null;+if (listening) {+ const serviceHome = mkdtempSync(join(tmpdir(), "omb-smoke-service-"));+ const [servicePort, serviceWebhookPort] = await freePorts(2);+ const service = spawn(process.execPath, [join(staging, "server", "index.js")], {+ cwd: staging,+ env: { ...fixtureEnv, HOME: serviceHome, USERPROFILE: serviceHome, OMB_DATA_DIR: join(serviceHome, ".openmausbot"),+ OMB_PORT: String(servicePort), OMB_WEBHOOK_PORT: String(serviceWebhookPort), OMB_LOOPBACK_TRUST: "service" },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let serviceOutput = "";+ service.stdout.on("data", (chunk) => (serviceOutput += chunk));+ service.stderr.on("data", (chunk) => (serviceOutput += chunk));+ try {+ const until = Date.now() + 45_000;+ let serving = false;+ while (Date.now() < until && service.exitCode === null) {+ try {+ // A stalled connection must not outlive the readiness deadline: every probe is bounded.+ const remaining = Math.max(until - Date.now(), 1_000);+ if ((await fetch(`http://127.0.0.1:${servicePort}/api/health`, { signal: AbortSignal.timeout(Math.min(remaining, 10_000)) })).ok) { serving = true; break; }+ } catch { /* not up yet */ }+ await new Promise((resolve) => setTimeout(resolve, 300));+ }+ const healthStatus = serving ? (await fetch(`http://127.0.0.1:${servicePort}/api/health`, { signal: AbortSignal.timeout(10_000) })).status : null;+ const mutation = await fetch(`http://127.0.0.1:${servicePort}/api/workspace-backup/export`, {+ method: "POST", headers: { "content-type": "application/json" },+ body: JSON.stringify({ password: "packaged-fixture-password-only" }), signal: AbortSignal.timeout(15_000),+ });+ serviceTrustReport = { serving, healthStatus, exportStatus: mutation.status };+ } catch (error) {+ serviceTrustReport = { error: String(error) };+ } finally {+ // Windows holds data files open past the kill for a moment: wait for the exit before removing the home, and+ // say so when the home could not go.+ const exited = new Promise((resolve) => service.once("exit", () => resolve(null)));+ if (service.exitCode === null) service.kill("SIGKILL");+ await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 10_000).unref())]);+ try {+ rmSync(serviceHome, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });+ } catch (error) {+ serviceTrustReport ??= {};+ serviceTrustReport.cleanup = `could not remove the service-trust home: ${error}`;+ }+ }+}// The container image runs the server through server-launcher.js: it must start// the server as its own child, through the bootstrap that keeps Node's compile// cache on the data volume, and SIGTERM must end both with a clean exit.@@ -463,11 +513,17 @@ if (!backupReport?.ok) {console.error("the packaged backup worker failed its encrypted export smoke:", backupReport);process.exit(1);}+if (!serviceTrustReport || serviceTrustReport.error || serviceTrustReport.serving !== true ||+ serviceTrustReport.healthStatus !== 200 || serviceTrustReport.exportStatus !== 403) {+ console.error("the packaged server's loopback trust gate did not hold at service trust:", serviceTrustReport);+ process.exit(1);+}console.log(`packaged server started with no node_modules in reach (port ${port}) ✓`);console.log(`all ${count} spawned proxy paths resolve inside the packaged server dir ✓`);console.log("packaged MCP stdio server reached the API and flushed its final frames ✓");console.log("packaged openmausbot doctor and bots answered from the bundle ✓");console.log("packaged backup worker exported an encrypted archive ✓");+console.log("packaged loopback trust gate: health serves, a public mutation is refused at service trust ✓");if (launcherReport) console.log("packaged container launcher ran the server as its child and stopped it cleanly ✓");if (desktopEntryReport) console.log(`packaged desktop entry started the server twice on its compile cache (${desktopEntryReport.starts[0].cached.length} entries) ✓`);if (layerShipped) console.log("packaged server found its enterprise layer inside the server dir ✓");diff --git a/server/bot-cwd.test.ts b/server/bot-cwd.test.tsindex 515fee01e3..e75fca3a97 100644--- a/server/bot-cwd.test.ts+++ b/server/bot-cwd.test.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { homedir, tmpdir } from "node:os";import { join, resolve } from "node:path";import { afterAll, describe, expect, it } from "vitest";@@ -38,8 +38,19 @@ describe("validateBotCwd", () => {describe("sharedProjectFolder", () => {const data = join(dir, "omb-data");const project = join(dir, "omb-data-site");+ const privateWorkspace = join(data, "task-workspaces", "bot", "thread");mkdirSync(join(data, "task-workspaces", "bot", "thread"), { recursive: true });mkdirSync(project);+ const linkKind = process.platform === "win32" ? "junction" : "dir";+ const intoData = join(dir, "site-link-into-data");+ const outside = join(dir, "omb-outside-site");+ const anotherOutside = join(dir, "omb-another-outside");+ mkdirSync(outside);+ mkdirSync(anotherOutside);+ try { symlinkSync(privateWorkspace, intoData, linkKind); } catch {}+ const outLink = join(dir, "site-link-outside");+ try { symlinkSync(outside, outLink, linkKind); } catch {}+ const linked = existsSync(intoData) && existsSync(outLink);it("shares an existing folder outside the data folder, even one whose name starts the same", () => {expect(sharedProjectFolder(project, data)).toBe(project);@@ -47,11 +58,36 @@ describe("sharedProjectFolder", () => {it("never shares the data folder, a private workspace in it, a missing folder or no folder", () => {expect(sharedProjectFolder(data, data)).toBeUndefined();- expect(sharedProjectFolder(join(data, "task-workspaces", "bot", "thread"), data)).toBeUndefined();+ expect(sharedProjectFolder(privateWorkspace, data)).toBeUndefined();expect(sharedProjectFolder(join(dir, "gone"), data)).toBeUndefined();expect(sharedProjectFolder(null, data)).toBeUndefined();expect(sharedProjectFolder(undefined, data)).toBeUndefined();});++ it.runIf(linked)("never shares a folder whose link resolves into the data folder, while a link out stays shareable", () => {+ expect(sharedProjectFolder(intoData, data)).toBeUndefined();+ expect(sharedProjectFolder(outLink, data)).toBe(realpathSync(outside));+ });++ it.runIf(linked)("returns the folder a link resolved to at check time, so retargeting it cannot move a shared task", () => {+ expect(sharedProjectFolder(outLink, data)).toBe(realpathSync(outside));+ rmSync(outLink);+ symlinkSync(join(dir, "omb-another-outside"), outLink, linkKind);+ expect(realpathSync(outLink)).not.toBe(realpathSync(outside));+ expect(sharedProjectFolder(outLink, data)).toBe(realpathSync(join(dir, "omb-another-outside")));+ });++ it.runIf(linked)("checks the data root as it really resolves, so a linked data folder is still a boundary", () => {+ const linkedData = join(dir, "omb-data-link");+ try { symlinkSync(data, linkedData, linkKind); } catch {}+ if (!existsSync(linkedData)) return;+ expect(sharedProjectFolder(privateWorkspace, linkedData)).toBeUndefined();+ expect(sharedProjectFolder(project, linkedData)).toBe(project);+ });++ it.runIf(linked)("still validates a linked folder as a plain working folder", () => {+ expect(validateBotCwd(intoData)).toEqual({ ok: true, cwd: intoData });+ });});describe("inMyFolderCwd", () => {diff --git a/server/bot-cwd.ts b/server/bot-cwd.tsindex 13e629ae87..98b3a53f62 100644--- a/server/bot-cwd.ts+++ b/server/bot-cwd.ts@@ -1,4 +1,4 @@-import { statSync } from "node:fs";+import { lstatSync, realpathSync, statSync } from "node:fs";import { homedir } from "node:os";import { isAbsolute, relative, resolve } from "node:path";@@ -32,12 +32,25 @@ export function folderToFollow(bot: { id: string; cwd?: string }, threadId: strireturn isOwnThreadFolder(threadCwd, bot.id, threadId) ? bot.cwd : undefined;}-/** A conversation's folder a teammate may be sent to: one that still exists, outside OpenMausBot's own data (a bot's private workspace). */+/** A conversation's folder a teammate may be sent to: one that still exists, outside OpenMausBot's own data (a bot's private workspace).+ * The path as given and where it really leads are both checked against the data root as it really resolves too, and a+ * link is shared as the folder it resolved to at check time, so retargeting it afterwards cannot move a shared task. */export function sharedProjectFolder(cwd: string | null | undefined, dataDir: string): string | undefined {const checked = cwd ? validateBotCwd(cwd) : undefined;if (!checked?.ok || !checked.cwd) return undefined;- const inside = relative(resolve(dataDir), checked.cwd);- return inside === "" || (!inside.startsWith("..") && !isAbsolute(inside)) ? undefined : checked.cwd;+ let real: string;+ let root: string;+ try {+ real = realpathSync(checked.cwd);+ root = realpathSync(resolve(dataDir));+ } catch {+ return undefined;+ }+ for (const candidate of [checked.cwd, real]) {+ const inside = relative(root, candidate);+ if (inside === "" || (!inside.startsWith("..") && !isAbsolute(inside))) return undefined;+ }+ return lstatSync(checked.cwd).isSymbolicLink() ? real : checked.cwd;}/** coordinate_bots' in_my_folder: the sender's project folder for the teammate threads it opens outside a room, or why an explicit true cannot be honoured. Omitted means on whenever there is a folder to share. */diff --git a/server/config.test.ts b/server/config.test.tsindex bf2faceee6..a77734b83b 100644--- a/server/config.test.ts+++ b/server/config.test.ts@@ -1,5 +1,8 @@-import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";-import { join } from "node:path";+import { execFileSync } from "node:child_process";+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir, userInfo } from "node:os";+import { dirname, join } from "node:path";+import { pathToFileURL } from "node:url";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { botThreadLimitText, defaultBotThreads, maxConcurrentBotThreads, maxConcurrentChildThreads } from "./bot-thread-limits.ts";@@ -2377,3 +2380,46 @@ describe("X research's included relay token", () => {expect(WORKSPACE_CREDENTIAL_ENV).toContain("OMB_TREG_KEY");});});++describe("DATA_DIR outside the suite's throwaway home", () => {+ function childDataDir(env: NodeJS.ProcessEnv): string {+ const script = "const m = await import(process.env.OMB_CONFIG_URL); process.stdout.write(m.DATA_DIR);";+ const { OMB_DATA_DIR: _dataDir, VITEST: _vitest, NODE_ENV: _nodeEnv, ...inherited } = process.env;+ return execFileSync(process.execPath, ["--experimental-strip-types", "--no-warnings", "--input-type=module", "-e", script], {+ env: { ...inherited, OMB_CONFIG_URL: pathToFileURL(join(import.meta.dirname, "config.ts")).href, ...env }, encoding: "utf8",+ });+ }++ it("never resolves to the person's real data folder when a test runs without the setup file", () => {+ const realHome = userInfo().homedir;+ const dataDir = childDataDir({ HOME: realHome, USERPROFILE: realHome, VITEST: "true" });+ try {+ expect(dataDir).not.toBe(join(realHome, ".openmausbot"));+ expect(dataDir.startsWith(tmpdir())).toBe(true);+ } finally {+ // Only ever a throwaway folder: a broken guard would hand back the real home here.+ const throwaway = dirname(dataDir);+ if (throwaway.startsWith(join(realpathSync(tmpdir()), "omb-test-home-")) || throwaway.startsWith(join(tmpdir(), "omb-test-home-"))) {+ rmSync(throwaway, { recursive: true, force: true });+ }+ }+ });++ it("treats an empty OMB_DATA_DIR as unset", () => {+ const home = mkdtempSync(join(tmpdir(), "omb-config-home-"));+ try {+ expect(childDataDir({ HOME: home, USERPROFILE: home, OMB_DATA_DIR: "" })).toBe(join(home, ".openmausbot"));+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ it("keeps the home folder outside tests", () => {+ const home = mkdtempSync(join(tmpdir(), "omb-config-home-"));+ try {+ expect(childDataDir({ HOME: home, USERPROFILE: home })).toBe(join(home, ".openmausbot"));+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/server/config.ts b/server/config.tsindex 805a6993e5..f1c8f41d52 100644--- a/server/config.ts+++ b/server/config.ts@@ -1,6 +1,6 @@// ~/.openmausbot/config.json, with env vars overriding its credentials.import { readFileSync, mkdirSync, existsSync, renameSync } from "node:fs";-import { homedir } from "node:os";+import { dataHome } from "./data-dir.ts";import { join } from "node:path";import { isDeepStrictEqual } from "node:util";import { z } from "zod";@@ -710,8 +710,8 @@ export function changedInstanceIds(before: Record<string, unknown>, after: Recor.filter((id) => !isDeepStrictEqual(before[id], after[id]));}-export const DATA_DIR = process.env.OMB_DATA_DIR ?? join(homedir(), ".openmausbot");-const LEGACY_DATA_DIR = join(homedir(), ".opengrokbot");+export const DATA_DIR = process.env.OMB_DATA_DIR || join(dataHome(), ".openmausbot");+const LEGACY_DATA_DIR = join(dataHome(), ".opengrokbot");export const EVENTS_DIR = join(DATA_DIR, "events");export const NATIVE_DIR = join(DATA_DIR, "native");diff --git a/server/data-dir.ts b/server/data-dir.tsnew file mode 100644index 0000000000..0766b3dfac--- /dev/null+++ b/server/data-dir.ts@@ -0,0 +1,14 @@+import { mkdtempSync } from "node:fs";+import { homedir, tmpdir, userInfo } from "node:os";+import { join } from "node:path";++let home: string | undefined;++/** The home the data folder lives under. Under vitest, with HOME still the real one, a temp folder instead, so a test+ * never reads, migrates or deletes the person's own data. */+export function dataHome(): string {+ if (home !== undefined) return home;+ const real = homedir();+ home = process.env.VITEST !== undefined && real === userInfo().homedir ? mkdtempSync(join(tmpdir(), "omb-test-home-")) : real;+ return home;+}diff --git a/server/drivers/acp/custom-model-catalog.test.ts b/server/drivers/acp/custom-model-catalog.test.tsindex c7f4d939d7..d4ff403079 100644--- a/server/drivers/acp/custom-model-catalog.test.ts+++ b/server/drivers/acp/custom-model-catalog.test.ts@@ -24,7 +24,13 @@ import { createInterface } from 'node:readline';let current='deep';const mode=process.env.CATALOG_MODE;const modelOptions=[{value:'deep',name:'Deep'},{value:'flash',name:'Flash'},{value:'silent',name:'Silent'},{value:'rejected',name:'Rejected'}];-function result(){return {sessionId:'fake-session',configOptions:[{id:'model',type:'select',category:'model',currentValue:current,options:modelOptions},...(current==='silent'?[]:[{id:current==='flash'?'thought_level':'reasoning_effort',type:'select',category:'thought_level',currentValue:current==='flash'?'low':'max',options:[{value:current==='flash'?'low':'max',name:current==='flash'?'Low':'Max'}]}])]};}+function result(){if(mode==='hostile'||mode==='hostile-default'||mode==='hostile-labels'||mode==='hostile-all'){const options=mode==='hostile-labels'+ ?[{value:'plain-model',name:'Plain'+String.fromCharCode(0x202e)+'Reversed'},{value:'good-model',name:'Good Model'}]+ :mode==='hostile-all'+ ?[{value:'../../.openmausbot',name:'Traversal'},{value:'bad'+String.fromCharCode(0)+'id',name:'Control'},{value:'x'.repeat(500),name:'Long'}]+ :[{value:'../../.openmausbot',name:'Traversal'},{value:'bad'+String.fromCharCode(0)+'id',name:'Control'},{value:'x'.repeat(500),name:'Long'},{value:'ok-model',name:'Fine'+String.fromCharCode(7)+'Name'},{value:'good-model',name:'Good Model'}];+ return {sessionId:'fake-session',configOptions:[{id:'model',type:'select',category:'model',currentValue:mode==='hostile-default'?String.fromCharCode(46,46,92)+String.fromCharCode(46,46,92)+'private':mode==='hostile-all'?'../../.openmausbot':'good-model',options}]};}+ return {sessionId:'fake-session',configOptions:[{id:'model',type:'select',category:'model',currentValue:current,options:modelOptions},...(current==='silent'?[]:[{id:current==='flash'?'thought_level':'reasoning_effort',type:'select',category:'thought_level',currentValue:current==='flash'?'low':'max',options:[{value:current==='flash'?'low':'max',name:current==='flash'?'Low':'Max'}]}])]};}function emit(value){process.stdout.write(JSON.stringify(value)+'\\n');}function legacyResult(){const r=result();return {...r,models:{currentModelId:current,availableModels:modelOptions.map(x=>({modelId:x.value,name:x.name}))},configOptions:r.configOptions.filter(x=>x.id!=='model')}}appendFileSync(process.env.CATALOG_DUMP,JSON.stringify({cwd:process.cwd(),pid:process.pid})+'\\n');@@ -159,4 +165,39 @@ describe("custom ACP catalog discovery (isolated fake CLI)", () => {const requests = await fixture.requests();await expect(readFile(requests[0].cwd)).rejects.toMatchObject({ code: "ENOENT" });});++ it("skips discovered entries whose id or label is not a usable slug, and never sends them back to the agent", async () => {+ const fixture = await fake("hostile");+ const catalog = await discoverAcpModels(fixture.env, fixture.config.cli, []);+ expect(catalog.options).toEqual([+ { id: "ok-model", label: "ok-model" },+ { id: "good-model", label: "Good Model" },+ ]);+ expect(catalog.default).toBe("good-model");+ const sent = JSON.stringify(await fixture.requests());+ expect(sent).not.toContain("../.openmausbot");+ expect(sent).not.toContain("bad\u0000id");+ expect(sent).not.toContain("x".repeat(500));+ });++ it("never lets an unusable session model become the catalog default", async () => {+ const fixture = await fake("hostile-default");+ const catalog = await discoverAcpModels(fixture.env, fixture.config.cli, []);+ expect(catalog.default).toBe("ok-model");+ expect(catalog.options.map((option) => option.id)).toEqual(["ok-model", "good-model"]);+ });++ it("rejects a custom catalog whose every discovered id was unusable instead of leaving only the default", async () => {+ const fixture = await fake("hostile-all");+ await expect(resolveCustomAcpModels(fixture.env, fixture.config)).rejects.toThrow("did not advertise any usable models");+ });++ it("rejects bidirectional controls and control characters in labels, and falls back to the id", async () => {+ const fixture = await fake("hostile-labels");+ const catalog = await discoverAcpModels(fixture.env, fixture.config.cli, []);+ expect(catalog.options).toEqual([+ { id: "plain-model", label: "plain-model" },+ { id: "good-model", label: "Good Model" },+ ]);+ });});diff --git a/server/drivers/acp/custom-model-catalog.ts b/server/drivers/acp/custom-model-catalog.tsindex 56a76be5e5..f9cb5254ec 100644--- a/server/drivers/acp/custom-model-catalog.ts+++ b/server/drivers/acp/custom-model-catalog.ts@@ -68,6 +68,26 @@ async function stopDiscovery(child: ReturnType<typeof spawnCli> | undefined, graconst AGENT_DEFAULT = { id: "agent-default", label: "Agent default" };+/** A discovered model or variant id is an opaque key the picker, the request rebuild and the set_model round-trips+ * treat as trusted; the agent advertising it is untrusted, so traversal, control characters, quotes and shell+ * metacharacters are skipped. Real ids include parameterised forms (`grok-4.7[context=256k,fast=true]`). */+function usableDiscoveredId(id: unknown): id is string {+ return typeof id === "string" && id.length <= 200 && !id.includes("..")+ && /^[A-Za-z0-9][A-Za-z0-9 ._():[\]{}=,@+/:-]*$/.test(id);+}++/** Bidirectional controls can reorder or hide picker text, so a label rendered for one model must not carry them. */+const BIDI_CONTROLS = new Set([0x061c, 0x200e, 0x200f, 0x202a, 0x202b, 0x202c, 0x202d, 0x202e, 0x2066, 0x2067, 0x2068, 0x2069]);++function usableDiscoveredLabel(label: unknown): label is string {+ if (typeof label !== "string" || label.length > 200) return false;+ for (const char of label) {+ const code = char.codePointAt(0)!;+ if (code < 0x20 || (code >= 0x7f && code <= 0x9f) || BIDI_CONTROLS.has(code)) return false;+ }+ return true;+}+export function resolveCustomAcpModels(env: Record<string, string | undefined>,config: Pick<AcpConfig, "cli">,@@ -188,9 +208,12 @@ export async function discoverAcpModels(const mark = discovery.custom ? { custom: true } : {};const { passthrough } = discovery;const options: ModelCatalog["options"] = passthrough ? [{ ...passthrough, ...mark }] : [];+ let discovered = 0;for (const model of modelOption.options) {if (model.id === passthrough?.id) continue;if (failure) throw failure;+ if (!usableDiscoveredId(model.id)) continue;+ discovered++;let confirmed: unknown;if (model.id === modelOption.currentValue) {confirmed = initial;@@ -206,13 +229,25 @@ export async function discoverAcpModels(if (failure) throw failure;}}- const variants = confirmed ? acpVariantOption(confirmed)?.options : undefined;- const label = discovery.label ? discovery.label(model, initial) : model.label;- options.push({ ...model, label, ...mark, ...(variants?.length ? { variants } : {}) });+ const variants = confirmed ? acpVariantOption(confirmed)?.options.flatMap((variant) => usableDiscoveredId(variant.id)+ ? [{ ...variant, label: usableDiscoveredLabel(variant.label) ? variant.label : variant.id }]+ : []) : undefined;+ const named = discovery.label ? discovery.label(model, initial) : model.label;+ const label = usableDiscoveredLabel(named) ? named : model.id;+ const provider = usableDiscoveredLabel(model.provider) ? model.provider : undefined;+ options.push({+ id: model.id, label,+ ...(provider ? { provider } : {}), ...mark,+ ...(variants?.length ? { variants } : {}),+ });}if (failure) throw failure;+ // Only the passthrough default left means every advertised model was unusable: keeping the previous catalog+ // beats replacing it with a picker that has lost its models.+ if (!discovered) throw new Error("The ACP agent did not advertise any usable models. The previous catalog was kept.");const preferred = discovery.default && options.some((option) => option.id === discovery.default) ? discovery.default : undefined;- catalog = { default: passthrough?.id ?? preferred ?? modelOption.currentValue ?? options[0].id, options };+ const current = usableDiscoveredId(modelOption.currentValue) ? modelOption.currentValue : undefined;+ catalog = { default: passthrough?.id ?? preferred ?? current ?? options[0].id, options };} catch (error) {thrown = error;} finally {diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.tsindex b97dee5b5b..96dd8a2ff6 100644--- a/server/drivers/chat-mcp-tools.test.ts+++ b/server/drivers/chat-mcp-tools.test.ts@@ -10,6 +10,7 @@ import { ChatToolSessionError, SAVED_RESULTS_FOLDER, SAVED_RESULTS_KEPT, chatTooimport { EXECUTOR_LIKE_TOOLS } from "../testing/executor-like-tools.ts";import type { ToolScope } from "../../shared/tool-scope.ts";import { catalogServer, CUA_DRIVER_WINDOWS_TOOLS, syntheticToolNames } from "../testing/cua-driver-tools.ts";+import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";import { startFakeHttpMcp } from "../testing/fake-http-mcp-server.ts";import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";import { wideSchema } from "../testing/oversized-tool-schema.ts";@@ -396,6 +397,45 @@ describe("Chat MCP session", () => {expect(alive(failed.read().pid)).toBe(false);});+ it("skips a connected-apps mount that fails, and keeps the turn alive", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const ready = fixture();+ const refused = fixture(`if(message.method === "tools/list") { send({jsonrpc:"2.0",id:message.id,error:{code:-32000,message:"connector service returned HTTP 503"}}); continue; }`);+ const session = await mountChatTools({ composio: refused.server, custom: { ready: ready.server } }, ready.controller.signal);+ sessions.push(session);+ expect(session.definitions.map((definition) => definition.function.name)).toEqual(["ready_write"]);+ expect(session.skipped).toEqual([{ server: "composio", reason: expect.stringContaining("MCP request failed") }]);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(`"composio"`));+ await vi.waitFor(() => expect(alive(refused.read().pid)).toBe(false));+ expect(alive(ready.read().pid)).toBe(true);+ await expect(session.execute("ready_write", { value: "still works" }, ready.controller.signal)).resolves.toMatchObject({ ok: true, text: "recorded:still works" });+ warn.mockRestore();+ });++ it("skips the connected-apps own-apps mount that fails, and keeps the turn alive", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const ready = fixture();+ const missing = { command: join(ready.dir, "does-not-exist"), args: [], env: {} };+ const session = await mountChatTools({ composioOwn: missing, custom: { ready: ready.server } }, ready.controller.signal);+ sessions.push(session);+ expect(session.definitions.map((definition) => definition.function.name)).toEqual(["ready_write"]);+ expect(session.skipped.map((entry) => entry.server)).toEqual([OWN_APPS_SERVER]);+ warn.mockRestore();+ });++ it("keeps a configured server that shares the own-apps name alive when the built-in own-apps mount fails", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const ready = fixture();+ const missing = { command: join(ready.dir, "does-not-exist"), args: [], env: {} };+ const session = await mountChatTools({ composioOwn: missing, custom: { [OWN_APPS_SERVER]: ready.server } }, ready.controller.signal);+ sessions.push(session);+ expect(session.skipped.map((entry) => entry.server)).toEqual([OWN_APPS_SERVER]);+ expect(alive(ready.read().pid)).toBe(true);+ expect(session.definitions).toHaveLength(1);+ await expect(session.execute(session.definitions[0]!.function.name, { value: "still works" }, ready.controller.signal)).resolves.toMatchObject({ ok: true });+ warn.mockRestore();+ });+it("fails setup when the Local VM lists no tools, but not when the owner's selection leaves none", async () => {const empty = fixture(`if(message.method === "tools/list") { reply(message,{tools:[]}); continue; }`);await expect(empty.mount(true, true)).rejects.toThrow("The Local VM listed no tools");diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.tsindex f928c1ce94..8fc21f812e 100644--- a/server/drivers/chat-mcp-tools.ts+++ b/server/drivers/chat-mcp-tools.ts@@ -434,6 +434,12 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (integrations?.data && eligible("data")) servers.push(["data", integrations.data]);if (integrations?.email && eligible("email")) servers.push(["email", integrations.email]);if (integrations?.device && eligible("device")) servers.push(["device", integrations.device]);+ // Connected apps are optional: their tool catalog is fetched from the connected-apps service while+ // mounting, so an unreachable service must not fail the whole turn. A failed mount is skipped like a+ // configured server's, which the model is told about. (CLI engines already drop them and go on.)+ const optionalBuiltIns = new Set<string>();+ if (integrations?.composio) optionalBuiltIns.add("composio");+ if (integrations?.composioOwn) optionalBuiltIns.add(OWN_APPS_SERVER);const builtIns = servers.length;const besideBrowser = servers.some(([, descriptor]) => descriptor === integrations?.browser);const merged: MergedChatMcpServers[] = [];@@ -459,6 +465,8 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]const skipped: SkippedChatMcpServer[] = [];const trimmed: TrimmedChatMcpServer[] = [];const started = new Map<string, ChatMcpClient>();+ // By mount index too: a configured server may share a built-in's name, and a failed mount closes only its own client.+ const startedAt: Array<ChatMcpClient | undefined> = [];let closed = false;let closing: Promise<void> | undefined;const close = (): Promise<void> => {@@ -510,11 +518,11 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}}};- const skip = async (server: string, error: unknown) => {+ const skip = async (server: string, error: unknown, client = started.get(server)) => {const reason = error instanceof Error ? error.message : "MCP server failed to start";skipped.push({ server, reason });console.warn(`chat-mcp: skipping MCP server "${server}" for this turn: ${reason}`);- await started.get(server)?.close();+ await client?.close();};const offeredTools: Array<{ origin: ToolOrigin; tools: CheckedTool[] }> = [];let configured: Array<{ origin: ToolOrigin; tools: CheckedTool[] }> = [];@@ -549,7 +557,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]if (!direct.has(server.origin.server)) searched.push(server);else {try { register(server.origin, server.tools); }- catch (error) { configured = configured.filter((entry) => entry !== server); await skip(server.origin.server, error); continue; }+ catch (error) { configured = configured.filter((entry) => entry !== server); await skip(server.origin.server, error, server.origin.client); continue; }}budget.servers.push({ name: server.origin.server, tools: server.tools.length, direct: direct.has(server.origin.server) });}@@ -582,6 +590,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]const client = new ChatMcpClient(descriptor, computerUse, index >= builtIns);clients.push(client);started.set(name, client);+ startedAt[index] = client;const computer = descriptor === integrations?.localComputer;const keeps = (tool: unknown) => !computer || !object(tool) || typeof tool.name !== "string" || listsComputerTool(tool.name, besideBrowser);const include = (tool: unknown) => keeps(tool) && (scope === undefined || (object(tool) && typeof tool.name === "string"@@ -597,14 +606,17 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]}));for (const [index, mount] of mounts.entries()) {if (signal.aborted || closed) throw aborted();+ const name = servers[index]![0];+ if (mount.status === "rejected") {+ if (index >= builtIns || optionalBuiltIns.has(name)) { await skip(name, mount.reason, startedAt[index]); continue; }+ throw mount.reason;+ }if (index < builtIns) {- if (mount.status === "rejected") throw mount.reason;offeredTools.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) });continue;}- if (mount.status === "rejected") { await skip(servers[index]![0], mount.reason); continue; }try { configured.push({ origin: mount.value.origin, tools: checkedTools(mount.value.tools, mount.value.origin.server) }); }- catch (error) { await skip(mount.value.origin.server, error); }+ catch (error) { await skip(mount.value.origin.server, error, mount.value.origin.client); }}await layout(toolLimit);if (signal.aborted || closed) throw aborted();diff --git a/server/drivers/minimax.test.ts b/server/drivers/minimax.test.tsindex 9eb74ec643..276815f6db 100644--- a/server/drivers/minimax.test.ts+++ b/server/drivers/minimax.test.ts@@ -74,6 +74,48 @@ describe("MinimaxDriver", () => {});});+ const endpointCases: Array<{+ name: string; configuredUrl?: string; environmentUrl?: string;+ local: Record<string, string>; expectedUrl: string;+ }> = [+ { name: "explicit international URL over local CN region", configuredUrl: "https://api.minimax.io/v1", local: { region: "cn" }, expectedUrl: "https://api.minimax.io/v1" },+ { name: "normalized explicit international URL over local proxy", configuredUrl: " https://api.minimax.io/v1/ ", local: { base_url: "https://saved-proxy.example.test/v1" }, expectedUrl: "https://api.minimax.io/v1" },+ { name: "explicit custom URL over local CN region", configuredUrl: "https://chosen.example.test/", local: { region: "cn" }, expectedUrl: "https://chosen.example.test/v1" },+ { name: "international environment URL over local CN region", environmentUrl: "https://api.minimax.io/v1", local: { region: "cn" }, expectedUrl: "https://api.minimax.io/v1" },+ { name: "custom environment URL over local proxy", environmentUrl: "https://environment.example.test/v1", local: { base_url: "https://saved-proxy.example.test/v1" }, expectedUrl: "https://environment.example.test/v1" },+ { name: "instance URL over environment and local settings", configuredUrl: "https://api.minimax.io/v1", environmentUrl: "https://environment.example.test/v1", local: { region: "cn" }, expectedUrl: "https://api.minimax.io/v1" },+ { name: "local CN region when no explicit URL is set", local: { region: "cn" }, expectedUrl: "https://api.minimaxi.com/v1" },+ { name: "local proxy when no explicit URL is set", local: { base_url: "https://saved-proxy.example.test/v1" }, expectedUrl: "https://saved-proxy.example.test/v1" },+ { name: "international fallback when no URL is configured", local: {}, expectedUrl: "https://api.minimax.io/v1" },+ ];++ it.each(endpointCases)("routes a turn using $name", async ({ configuredUrl, environmentUrl, local, expectedUrl }) => {+ const dir = join(home, ".mmx");+ mkdirSync(dir);+ writeFileSync(join(dir, "config.json"), JSON.stringify({ api_key: "fixture-local-key", ...local }));+ if (environmentUrl) process.env.MINIMAX_BASE_URL = environmentUrl;+ const requests: Array<{ url: string; key: string | null }> = [];+ vi.stubGlobal("fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => {+ requests.push({ url: String(input), key: new Headers(init?.headers).get("authorization") });+ return new Response('data: {"choices":[{"delta":{"content":"fixture reply"}}]}\n' ++ 'data: [DONE]\n', { headers: { "content-type": "text/event-stream" } });+ }));+ const instance = await MinimaxDriver.create({+ instanceId: "minimax-routing", displayName: "MiniMax fixture", enabled: true,+ config: decodeMinimaxConfig({ ...(configuredUrl === undefined ? {} : { url: configuredUrl }), tools: false }),+ environment: { MINIMAX_API_KEY: "fixture-instance-key" },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.adapter.sendTurn({ threadId: "routing-fixture", text: "fixture" });+ expect(await recorder.until(event => event.type === "turn.completed")).toMatchObject({ ok: true });+ expect(requests).toEqual([{ url: `${expectedUrl}/chat/completions`, key: "Bearer fixture-instance-key" }]);+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });+it("skips blank environment credentials and does not probe on snapshot", async () => {const dir = join(home, ".mmx");mkdirSync(dir);diff --git a/server/drivers/minimax.ts b/server/drivers/minimax.tsindex 5fc240ed82..84418e60b1 100644--- a/server/drivers/minimax.ts+++ b/server/drivers/minimax.ts@@ -23,7 +23,8 @@ const MODELS: ModelCatalog = {export interface MinimaxConfig {tools?: boolean;- url: string;+ /** An explicit instance or environment URL; absent uses mmx-cli's endpoint, then the international API. */+ url?: string;}interface LocalMiniMaxConfig {@@ -66,9 +67,10 @@ export function decodeMinimaxConfig(raw: unknown): MinimaxConfig {if (tools !== undefined && typeof tools !== "boolean") throw new Error("tools must be a boolean");const parsed = driverConfigSchema.safeParse(raw ?? {});const config = parsed.success ? parsed.data : {};+ const url = config.url?.trim() || process.env.MINIMAX_BASE_URL?.trim();return {...(tools !== undefined ? { tools } : {}),- url: normalizedApiUrl(config.url?.trim() || process.env.MINIMAX_BASE_URL?.trim() || DEFAULT_URL),+ ...(url ? { url: normalizedApiUrl(url) } : {}),};}@@ -95,9 +97,7 @@ export const MinimaxDriver: ProviderDriver<MinimaxConfig> = {input.environment[API_KEY_ENV]?.trim() ||process.env[API_KEY_ENV]?.trim() ||local.apiKey;- const apiUrl = input.config.url === DEFAULT_URL && local.url !== DEFAULT_URL- ? local.url- : input.config.url;+ const apiUrl = input.config.url ?? local.url;const models = local.defaultModel && MODELS.options.some((model) => model.id === local.defaultModel)? { ...MODELS, default: local.defaultModel }: MODELS;diff --git a/server/drivers/openai-compat-idle.test.ts b/server/drivers/openai-compat-idle.test.tsindex 255941dc67..ed3ca3d02d 100644--- a/server/drivers/openai-compat-idle.test.ts+++ b/server/drivers/openai-compat-idle.test.ts@@ -116,7 +116,7 @@ it("checks only servers on this machine or network, never a cloud provider", ()for (const url of ["http://127.0.0.1:11434/v1", "http://localhost:1234/v1", "http://[::1]:8080/v1", "http://192.168.1.20:11434/v1", "http://10.0.0.5/v1", "http://172.20.1.2/v1", "http://studio.local:1234/v1"]) {expect(onThisNetwork(url), url).toBe(true);}- for (const url of ["https://openrouter.ai/api/v1", "https://api.together.xyz/v1", "http://172.32.0.1/v1", "not a url"]) {+ for (const url of ["https://openrouter.ai/api/v1", "https://api.together.xyz/v1", "http://172.32.0.1/v1", "https://127.example.test/v1", "https://127.0.0.1.example.test/v1", "not a url"]) {expect(onThisNetwork(url), url).toBe(false);}});diff --git a/server/engine-limits.test.ts b/server/engine-limits.test.tsindex a5b0b3a5df..fce083e566 100644--- a/server/engine-limits.test.ts+++ b/server/engine-limits.test.ts@@ -61,6 +61,15 @@ describe("usage limits a bot reads", () => {]);});+ it("lists an OpenCode Go account's allowance like the other plans", () => {+ const [account] = read({+ instances: [instance("oc", "opencodeGo", "OpenCode")],+ report: report(row("oc", { driver: "opencode", plan: "Go", fiveHour: open(30), weekly: open(55) })),+ });+ expect(account).toMatchObject({ account: "OpenCode", engine: "opencodeGo", status: "ok", plan: "Go" });+ expect(account?.windows.map((window) => window.name)).toEqual(["5-hour", "weekly"]);+ });+it("says unknown, not unsupported, when the read itself failed", () => {expect(read({ instances: [instance("claude"), instance("cursor", "cursorAgent", "Cursor")], report: null }).map((account) => account.status)).toEqual(["unknown", "unsupported"]);});diff --git a/server/engine-limits.ts b/server/engine-limits.tsindex d75c963e71..f5a0478f12 100644--- a/server/engine-limits.ts+++ b/server/engine-limits.ts@@ -35,7 +35,7 @@ export interface EngineLimitInstance {enabled: boolean;}-const REPORTING_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex", "grokAgent"]);+const REPORTING_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex", "grokAgent", "opencodeGo"]);const UNSUPPORTED_WHY = "This AI does not report usage limits to this app.";const NO_WINDOWS_WHY = "The account answered but reported no usage windows.";const NOT_CHECKED_WHY = "Usage could not be checked just now. Try again later.";diff --git a/server/headless/host-doctor.ts b/server/headless/host-doctor.tsindex 223ebbefdf..6bc6f6d533 100644--- a/server/headless/host-doctor.ts+++ b/server/headless/host-doctor.ts@@ -316,7 +316,7 @@ export async function hostDoctor(ctx: VerbContext, probe: HostProbe = systemProbconst port = Number(rawPort);if (!Number.isInteger(port) || port < 1 || port > 65_535) throw usageError("--port must be 1-65535");// A Linux machine's path, also when the checks are tested on Windows.- const dataDir = posix.resolve(flag(ctx.flags, "data-dir") ?? ctx.env.OMB_DATA_DIR ?? join(homedir(), ".openmausbot"));+ const dataDir = posix.resolve(flag(ctx.flags, "data-dir") ?? (ctx.env.OMB_DATA_DIR || join(homedir(), ".openmausbot")));const domain = flag(ctx.flags, "domain")?.trim().toLowerCase();return hostReport(await checkHost(probe, { dataDir, port, ...(domain ? { domain } : {}) }));}diff --git a/server/instance-icons.e2e.test.ts b/server/instance-icons.e2e.test.tsindex 6da18dcc1c..a33292ac61 100644--- a/server/instance-icons.e2e.test.ts+++ b/server/instance-icons.e2e.test.ts@@ -28,6 +28,8 @@ it("lists an OpenAI-compatible server with its provider's mark, and a stored icowriteFileSync(join(home, "config.json"), JSON.stringify({instances: {deepseekServer: server("https://api.deepseek.com/v1", { displayName: "DeepSeek" }),+ qwenWorkspace: server("https://workspace-123.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", { displayName: "Qwen" }),+ qwenLookalike: server("https://workspace-123.cn-beijing.maas.aliyuncs.com.evil.test/compatible-mode/v1"),lookalike: server("https://api.openai.com.evil.test/v1"),ownIcon: server("https://api.x.ai/v1", { icon: { kind: "preset", preset: "cohere" } }),},@@ -51,6 +53,8 @@ it("lists an OpenAI-compatible server with its provider's mark, and a stored icoconst { instances } = await response.json() as { instances: Array<{ instanceId: string; icon?: unknown }> };const icon = (id: string) => instances.find((instance) => instance.instanceId === id)!.icon;expect(icon("deepseekServer")).toEqual({ kind: "preset", preset: "deepseek" });+ expect(icon("qwenWorkspace")).toEqual({ kind: "preset", preset: "qwen" });+ expect(icon("qwenLookalike")).toBeUndefined();expect(icon("lookalike")).toBeUndefined();expect(icon("ownIcon")).toEqual({ kind: "preset", preset: "cohere" });}, 60_000);diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.tsindex eb0661b15e..19efc4d125 100644--- a/server/limit-resets.test.ts+++ b/server/limit-resets.test.ts@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { codexLimitResetsAt } from "./drivers/codex-errors.ts";import { engineLimitFromUsage, LimitResetClock, nearLimitNote, UNNAMED_LIMIT_MS } from "./limit-resets.ts";import type { RuntimeEvent } from "../shared/runtime-events.ts";-import { parseClaudeUsage, parseCodexUsage, type PlanProviderRow, type PlanUsageReport, type PlanWindows } from "./plan-usage.ts";+import { parseClaudeUsage, parseCodexUsage, parseOpenCodeUsage, type PlanProviderRow, type PlanUsageReport, type PlanWindows } from "./plan-usage.ts";const NOW = Date.parse("2026-10-19T10:00:00Z");const HOUR = 3_600_000;@@ -14,8 +14,10 @@ const HOUR = 3_600_000;const REFUSAL_GRACE_FOR_TEST = 10 * 60_000 + 1;const iso = (at: number) => new Date(at).toISOString();-function row(id: string, driver: "claude" | "codex", windows: PlanWindows): PlanProviderRow {- return { id, name: driver === "claude" ? "Claude" : "Codex", driver, ok: true, error: null, ...windows };+/** A plan-usage row for one driver, named as the usage panel names it. */+function row(id: string, driver: PlanProviderRow["driver"], windows: PlanWindows): PlanProviderRow {+ const name = driver === "claude" ? "Claude" : driver === "codex" ? "Codex" : driver === "opencode" ? "OpenCode" : "Grok";+ return { id, name, driver, ok: true, error: null, ...windows };}/** As the Claude usage endpoint answers (utilization, resets_at). */const claude = (fiveHour: [number, number | null], weekly: [number, number | null]) => row("claude", "claude", parseClaudeUsage({@@ -41,6 +43,20 @@ describe("engineLimitFromUsage", () => {expect(engineLimitFromUsage(claude([10, NOW + 2 * HOUR], [95, NOW + 50 * HOUR]))).toMatchObject({ window: "weekly", usedPercent: 95, resetsAt: NOW + 50 * HOUR });});+ it("reads OpenCode Go's rolling and weekly allowance for its marker", () => {+ const opencode = row("opencodeGo", "opencode", parseOpenCodeUsage({+ usage: {+ rolling: { percent: 30, resetsAt: iso(NOW + 3 * HOUR) },+ weekly: { percent: 55, resetsAt: iso(NOW + 4 * 24 * HOUR) },+ monthly: { percent: 20, resetsAt: iso(NOW + 20 * 24 * HOUR) },+ },+ }));+ expect(engineLimitFromUsage(opencode)).toMatchObject({+ engine: "opencodeGo", name: "OpenCode", driver: "opencode", window: "weekly", usedPercent: 55, resetsAt: NOW + 4 * 24 * HOUR, blocked: false,+ });+ expect(engineLimitFromUsage(opencode)?.windows?.map((window) => window.window)).toEqual(["5-hour", "weekly"]);+ });+it("waits for the latest reset of every window at its limit, and knows no time when one has none", () => {expect(engineLimitFromUsage(claude([100, NOW + 2 * HOUR], [60, NOW + 50 * HOUR]))).toMatchObject({ blocked: true, window: "5-hour", resetsAt: NOW + 2 * HOUR });expect(engineLimitFromUsage(claude([100, NOW + 2 * HOUR], [100, NOW + 50 * HOUR]))).toMatchObject({ blocked: true, window: "weekly", resetsAt: NOW + 50 * HOUR });diff --git a/server/limit-resets.ts b/server/limit-resets.tsindex 15f5bb21a6..56b0214283 100644--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@ -16,6 +16,9 @@ const SOON_AFTER_REFUSAL_MS = 5_000;type Driver = EngineLimit["driver"];+/** The drivers whose plan usage gives a limit to show and to route around. */+const REPORTED_DRIVERS: ReadonlySet<string> = new Set(["claude", "codex", "grok", "opencode"]);+function windowLine(name: LimitWindowName, window: PlanWindow): { window: LimitWindowName; used: number; resetsAt: number | null } | null {if (!window.available || window.usedPercent === null) return null;const resetsAt = window.resetsAt ? Date.parse(window.resetsAt) : NaN;@@ -25,7 +28,7 @@ function windowLine(name: LimitWindowName, window: PlanWindow): { window: LimitW/** An engine's limit from its plan-usage row. The windows at their limit decide, and all must reset, so the latest of* their resets counts; with none at the limit, the fullest window counts. Null when the row has no usage. */export function engineLimitFromUsage(row: PlanProviderRow): EngineLimit | null {- if (!row.ok || (row.driver !== "claude" && row.driver !== "codex" && row.driver !== "grok")) return null;+ if (!row.ok || !REPORTED_DRIVERS.has(row.driver)) return null;const windows = [windowLine("5-hour", row.fiveHour), windowLine("weekly", row.weekly)].filter((line) => line !== null);const base = { engine: row.id, name: row.name, driver: row.driver as Driver,windows: windows.map(({ window, used, resetsAt }) => ({ window, usedPercent: used, resetsAt })) };@@ -52,7 +55,7 @@ function codexHoldGone(row: PlanProviderRow, limit: EngineLimit, held: number |return windows.every((line) => line === null || (line.resetsAt !== null && Math.abs(line.resetsAt - held) > SAME_RESET_MS));}-const PRODUCT_NAMES: Record<string, string> = { claudeAgent: "Claude", codex: "Codex", grokAgent: "Grok" };+const PRODUCT_NAMES: Record<string, string> = { claudeAgent: "Claude", codex: "Codex", grokAgent: "Grok", opencodeGo: "OpenCode" };/** "Claude", "Codex", or the name the person gave that engine. */export function engineLabel(engine: string, instance?: { displayName?: string; driverKind: string }): string {diff --git a/server/notify.test.ts b/server/notify.test.tsindex 36644586d0..b125ab0f74 100644--- a/server/notify.test.ts+++ b/server/notify.test.ts@@ -121,6 +121,13 @@ describe("summarize", () => {expect(long.endsWith("…")).toBe(true);expect(summarize("short")).toBe("short");});++ it("reads a bot's Markdown as the plain line a lock screen shows", () => {+ expect(summarize("**Facture reçue** — consulter le [document](https://example.com/facture)"))+ .toBe("Facture reçue — consulter le document");+ expect(summarize("I added the **cover card** to the deck.")).toBe("I added the cover card to the deck.");+ expect(summarize("Run `pnpm test` and *ship* it.")).toBe("Run pnpm test and ship it.");+ });});describe("buildSpendNotification", () => {diff --git a/server/notify.ts b/server/notify.tsindex c521ea91b8..ac2c7742bb 100644--- a/server/notify.ts+++ b/server/notify.ts@@ -1,11 +1,13 @@import type { Notification, NotifyKind } from "../shared/notification.ts";import { personMentionExcerpt } from "../shared/person-mention.ts";+import { plainPreviewText } from "../shared/plain-preview.ts";import { conversationLanguage, serverLine, type ServerLineKey } from "./server-lines.ts";export type { Notification, NotifyKind } from "../shared/notification.ts";+/** Fenced code stays out of a banner, as before; the rest of the Markdown becomes the readable line a lock screen shows. */export function summarize(text: string, max = 140): string {- const line = text.replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim();+ const line = plainPreviewText(text.replace(/```[\s\S]*?```/g, " "));return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;}diff --git a/server/provider-icon.test.ts b/server/provider-icon.test.tsindex a537dba4e1..0acec9e146 100644--- a/server/provider-icon.test.ts+++ b/server/provider-icon.test.ts@@ -15,6 +15,10 @@ describe("a server's mark comes from its host", () => {["https://api.deepseek.com", "deepseek"],["https://dashscope.aliyuncs.com/compatible-mode/v1", "qwen"],["https://dashscope-intl.aliyuncs.com/compatible-mode/v1", "qwen"],+ ["https://workspace-123.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", "qwen"],+ ["https://workspace-123.us-east-1.maas.aliyuncs.com/compatible-mode/v1", "qwen"],+ ["https://workspace-123.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", "qwen"],+ ["https://workspace-123.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1", "qwen"],["https://api.moonshot.ai/v1", "moonshot"],["https://api.moonshot.cn/v1", "moonshot"],["https://api.mistral.ai/v1", "mistral"],@@ -33,6 +37,7 @@ describe("a server's mark comes from its host", () => {expect(serverIconPreset("http://api.deepseek.com/v1")).toBe("deepseek");expect(serverIconPreset("HTTPS://API.DeepSeek.COM/v1")).toBe("deepseek");expect(serverIconPreset("https://api.openai.com./v1")).toBe("openai");+ expect(serverIconPreset("HTTPS://WORKSPACE-123.CN-BEIJING.MAAS.ALIYUNCS.COM.:8443/compatible-mode/v1")).toBe("qwen");});it.each([@@ -48,6 +53,13 @@ describe("a server's mark comes from its host", () => {"https://bedrock-runtime.my-bucket.s3.amazonaws.com/openai/v1","https://dashscope.aliyuncs.com.evil.test/compatible-mode/v1","https://evil-dashscope.aliyuncs.com/compatible-mode/v1",+ "https://workspace-123.cn-beijing.maas.aliyuncs.com.evil.test/compatible-mode/v1",+ "https://[email protected]/v1",+ "https://evil.test/workspace-123.cn-beijing.maas.aliyuncs.com/v1",+ "https://evil.test/v1?host=workspace-123.cn-beijing.maas.aliyuncs.com",+ "https://extra.workspace-123.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "https://cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "https://workspace-123.cn-beijing.other.aliyuncs.com/compatible-mode/v1","https://api.x.ai.evil.test/v1",])("never matches the look-alike %s", (url) => {expect(serverIconPreset(url)).toBeUndefined();@@ -79,6 +91,7 @@ describe("an instance's mark", () => {it("is the mark of whoever runs an OpenAI-compatible server", () => {expect(instanceIcon(server("https://api.deepseek.com/v1"))).toEqual({ icon: { kind: "preset", preset: "deepseek" } });expect(instanceIcon(server("https://dashscope-intl.aliyuncs.com/compatible-mode/v1"))).toEqual({ icon: { kind: "preset", preset: "qwen" } });+ expect(instanceIcon(server("https://workspace-123.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"))).toEqual({ icon: { kind: "preset", preset: "qwen" } });});it("keeps a stored icon, preset or custom, over the server's", () => {@@ -86,6 +99,7 @@ describe("an instance's mark", () => {const custom = { kind: "custom", dataUrl: "data:image/png;base64,iVBORw0KGgo=" } as const;expect(instanceIcon(server("https://api.deepseek.com/v1", { icon: preset }))).toEqual({ icon: preset });expect(instanceIcon(server("https://api.deepseek.com/v1", { icon: custom }))).toEqual({ icon: custom });+ expect(instanceIcon(server("https://workspace-123.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", { icon: custom }))).toEqual({ icon: custom });expect(instanceIcon({ driver: "claudeAgent", icon: preset })).toEqual({ icon: preset });});diff --git a/server/provider-icon.ts b/server/provider-icon.tsindex eb933db3c8..5bb4bcada3 100644--- a/server/provider-icon.ts+++ b/server/provider-icon.ts@@ -30,6 +30,7 @@ const SERVER_HOSTS: Record<string, ProviderIconPreset> = {"api.x.ai": "xai","api.deepseek.com": "deepseek","dashscope.aliyuncs.com": "qwen", "dashscope-*.aliyuncs.com": "qwen",+ "*.*.maas.aliyuncs.com": "qwen","api.moonshot.ai": "moonshot", "api.moonshot.cn": "moonshot","api.mistral.ai": "mistral", "codestral.mistral.ai": "mistral","api.cohere.com": "cohere", "api.cohere.ai": "cohere",diff --git a/server/provider-key-check.test.ts b/server/provider-key-check.test.tsindex 9f6002641e..f87c0ffd3f 100644--- a/server/provider-key-check.test.ts+++ b/server/provider-key-check.test.ts@@ -1,6 +1,40 @@import { createServer, type Server } from "node:http";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { checkProviderKey, providerModelsUrl } from "./provider-key-check.ts";+import { checkProviderKey, isLoopback, providerModelsUrl } from "./provider-key-check.ts";++describe("loopback hosts for HTTP key checks", () => {+ it.each(["localhost", "127.0.0.1", "127.0.0.2", "127.255.255.255", "::1", "[::1]"])("accepts the local host %s", host => {+ expect(isLoopback(host)).toBe(true);+ });++ it.each(["127.example.test", "127.0.0.1.example.test", "127.0.0.999", "127.", "128.0.0.1", "example.test"])("rejects the non-loopback host %s", host => {+ expect(isLoopback(host)).toBe(false);+ });++ it.each(["http://127.example.test/v1", "http://127.0.0.1.example.test/v1"])("never sends a key to %s", async url => {+ let calls = 0;+ const provider: typeof fetch = async () => { calls++; return Response.json({ data: [] }); };+ expect(await checkProviderKey({ provider: "openaiCompat", key: "fixture-key", url }, provider))+ .toEqual({ ok: false, reason: "unexpected" });+ expect(calls).toBe(0);+ });++ it.each([+ "http://localhost:1234/v1", "http://127.0.0.2:1234/v1", "http://[::1]:1234/v1",+ "http://127.1:1234/v1", "http://2130706433:1234/v1", "http://0x7f000001:1234/v1",+ "https://127.example.test/v1",+ ])("keeps URL-normalized local addresses and HTTPS endpoints working: %s", async url => {+ let calls = 0;+ const provider: typeof fetch = async (_input, init) => {+ calls++;+ expect(new Headers(init?.headers).get("authorization")).toBe("Bearer fixture-key");+ return Response.json({ data: [{ id: "fixture-model" }] });+ };+ expect(await checkProviderKey({ provider: "openaiCompat", key: "fixture-key", url }, provider))+ .toEqual({ ok: true, check: "models", models: ["fixture-model"] });+ expect(calls).toBe(1);+ });+});// A local stand-in for a provider's models endpoint; no real provider is contacted in this file.describe("provider key check", () => {diff --git a/server/provider-key-check.ts b/server/provider-key-check.tsindex 5d9172eec1..0cee25772f 100644--- a/server/provider-key-check.ts+++ b/server/provider-key-check.ts@@ -1,4 +1,6 @@// OpenRouter's catalog is public, so /key proves the key there; elsewhere /models proves only catalog access. Keys go only over TLS (or loopback).+import { isIP } from "node:net";+export type ProviderKeyKind = "anthropic" | "openai" | "openrouter" | "openaiCompat" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "meta";export type ProviderKeyVerdict =@@ -26,7 +28,7 @@ const MAX_MODELS = 5;/** A URL hostname on this machine: the only place a key may go over plain http. */export function isLoopback(hostname: string): boolean {const host = hostname.replace(/^\[|\]$/g, "");- return host === "localhost" || host === "127.0.0.1" || host === "::1" || host.startsWith("127.");+ return host === "localhost" || host === "::1" || (isIP(host) === 4 && host.startsWith("127."));}export function providerBaseUrl(provider: ProviderKeyKind, base?: string | null): string {diff --git a/server/provider-key-flow.test.ts b/server/provider-key-flow.test.tsindex 8138517c2c..601654dd11 100644--- a/server/provider-key-flow.test.ts+++ b/server/provider-key-flow.test.ts@@ -39,6 +39,10 @@ it("saving and replacing a workspace key reaches an existing bot's next requestmethod: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ provider: "openaiCompat" }),});expect(missing.status).toBe(400);+ for (const url of ["http://127.example.test/v1", "http://127.0.0.1.example.test/v1"]) {+ expect(await api("POST", "/api/keys/test", { provider: "openaiCompat", key: "fixture-key", url }))+ .toEqual({ ok: false, reason: "unexpected" });+ }const status = await api("PUT", "/api/config", {openaiCompat: { url: `http://127.0.0.1:${address.port}/v1`, key: "fixture-first-key" },instances: { openaiCompat: { driver: "openai-compat" } },diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex a6b57183db..040a2ed120 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -412,6 +412,10 @@ describe("resolveRequestAuth", () => {it("never grants loopback trust to a request that came through a proxy, whatever Host it carries", () => {expect(isProxied(request({ host: "localhost", "x-forwarded-for": "203.0.113.9" }))).toBe(true);expect(isProxied(request({ host: "localhost", "x-forwarded-proto": "https" }))).toBe(true);+ for (const name of ["x-real-ip", "cf-connecting-ip", "true-client-ip", "x-client-ip"]) {+ expect(isProxied(request({ host: "localhost", [name]: "203.0.113.9" }))).toBe(true);+ expect(resolve({ host: "localhost", [name]: "203.0.113.9" }).auth).toBeNull();+ }expect(isProxied(request({ host: "localhost" }))).toBe(false);const viaProxy = resolve({ host: "localhost", "x-forwarded-for": "203.0.113.9" });expect(viaProxy.auth).toBeNull();diff --git a/server/request-auth.ts b/server/request-auth.tsindex 14a3eab488..3a634ac429 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -176,11 +176,17 @@ export function requestOrigin(req: IncomingMessage): string | null {return `${proto}://${host.toLowerCase()}`;}+/** Every header a reverse proxy uses to name its client, so one that sets only X-Real-IP is still not loopback. */+const PROXY_HEADERS = [+ "x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "forwarded",+ "x-real-ip", "cf-connecting-ip", "true-client-ip", "x-client-ip",+] as const;+/** Security: loopback trust rests on the Host header, which any client writes, so a request is remote (never the owner)* when it came through a proxy, over the IPC socket, or from another machine's address, as on a LAN listener. */export function isProxied(req: IncomingMessage): boolean {- const h = req.headers;- return ipcPeer(req) || networkPeer(req) || Boolean(h["x-forwarded-for"] || h["x-forwarded-proto"] || h["x-forwarded-host"] || h["forwarded"]);+ if (ipcPeer(req) || networkPeer(req)) return true;+ return PROXY_HEADERS.some((name) => req.headers[name] !== undefined);}const LOOPBACK_PEER = /^(?:127\.|::1$|::ffff:127\.)/;diff --git a/shared/mcp-name.ts b/shared/mcp-name.tsindex d4ce875294..b591cd6815 100644--- a/shared/mcp-name.ts+++ b/shared/mcp-name.ts@@ -6,6 +6,8 @@ export const RESERVED_MCP_NAMES: ReadonlySet<string> = new Set(["composio","data","browser",+ "email",+ "device","phone","dweb","openmausbot_connectors",diff --git a/shared/plain-preview.ts b/shared/plain-preview.tsnew file mode 100644index 0000000000..5a97622cd3--- /dev/null+++ b/shared/plain-preview.ts@@ -0,0 +1,41 @@+/** Markdown a person typed, as the one plain line a sidebar or an OS notification can show. */+export function plainPreviewText(text: string): string {+ const escaped: string[] = [];+ let out = text.replace(/\r\n?/g, "\n").replace(/\\([\\`*_{}[\]()#+\-.!|>~])/g, (_match, char: string) => {+ escaped.push(char);+ return `\uE000${escaped.length - 1}\uE001`;+ });+ const code: string[] = [];+ const park = (body: string) => {+ code.push(body.replace(/\uE000(\d+)\uE001/g, (_match, index: string) => `\\${escaped[Number(index)] ?? ""}`));+ return `\uE002${code.length - 1}\uE003`;+ };+ // (a closing fence is the same character, at least as long as the opening)+ out = out.replace(/^[ \t]*((`|~)\2{2,})[^\n]*(?:\n([\s\S]*?))?(?:\n[ \t]*\1\2*[ \t]*(?=\n|$(?![\s\S]))|$(?![\s\S]))/gm, (_block, _fence: string, _char: string, body: string | undefined) => `\n${park(body ?? "")}\n`);+ out = out.replace(/(`+)([^`]*?)\1/g, (_span, _ticks: string, body: string) => park(body));+ out = out.replace(/!\[([^\]]*)\]\((?:[^()]|\([^)]*\))*\)/g, "$1");+ out = out.replace(/!\[([^\]]*)\]\[[^\]]*\]/g, "$1");+ out = out.replace(/\[([^\]]+)\]\((?:[^()]|\([^)]*\))*\)/g, "$1");+ out = out.replace(/\[([^\]]+)\]\[[^\]]*\]/g, "$1");+ out = out.replace(/^[ \t]{0,3}\[[^\]]+\]:[ \t]+\S+.*$/gm, "");+ out = out.replace(/<((?:https?|mailto):[^>\s]+)>/gi, "$1");+ out = out.replace(/<br\s*\/?>/gi, " ");+ out = out.replace(/<\/?(?:b|strong|i|em|u|s|del|ins|mark|code|kbd|sub|sup|small|span|p|div)\b[^>]*>/gi, "");+ out = out.replace(/^[ \t]{0,3}#{1,6}[ \t]+/gm, "");+ out = out.replace(/^[ \t]{0,3}#{1,6}[ \t]*$/gm, "");+ out = out.replace(/^[ \t]*(?:>[ \t]?)+/gm, "");+ out = out.replace(/^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?/gm, "");+ out = out.replace(/^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)*\|?[ \t]*$/gm, "");+ out = out.replace(/^[ \t]{0,3}(?:[-*_][ \t]*){3,}$/gm, "");+ out = out.replace(/^[ \t]*\|(.*)\|[ \t]*$/gm, (_row, cells: string) => cells.split("|").map((cell) => cell.trim()).filter(Boolean).join(" "));+ // Underscores inside a word (snake_case) and a lone * (2 * 3) are not emphasis.+ out = out.replace(/(\*{1,3}|_{1,3})(?=\S)([\s\S]*?\S)\1(?![\p{L}\p{N}])/gu, (match, marks: string, inner: string, offset: number, whole: string) => {+ if (marks[0] === "_" && offset > 0 && /[\p{L}\p{N}]/u.test(whole[offset - 1]!)) return match;+ return inner;+ });+ out = out.replace(/~~(?=\S)([\s\S]*?\S)~~/g, "$1");+ out = out.replace(/\*\*+|`{3,}|~~/g, "");+ out = out.replace(/\uE002(\d+)\uE003/g, (_match, index: string) => code[Number(index)] ?? "");+ out = out.replace(/\uE000(\d+)\uE001/g, (_match, index: string) => escaped[Number(index)] ?? "");+ return out.replace(/\s+/g, " ").trim();+}diff --git a/src/components/ApprovalCard.test.ts b/src/components/ApprovalCard.test.tsindex 7085f02478..b60f30e4ad 100644--- a/src/components/ApprovalCard.test.ts+++ b/src/components/ApprovalCard.test.ts@@ -478,6 +478,31 @@ describe("ApprovalCard tool-call kinds", () => {}});+ it("names the custom MCP server a tool comes from, and stays quiet about the app's own servers", () => {+ const html = renderToStaticMarkup(createElement(ApprovalCard, { bot, message: kindMessage("mcp__github__create_issue") }));+ expect(html).toContain("Scout wants to github · create issue");+ const own = renderToStaticMarkup(createElement(ApprovalCard, { bot, message: kindMessage("mcp__ogb__computer_batch") }));+ expect(own).toContain("Scout wants to computer batch");+ expect(own).not.toContain("ogb");+ const underscored = renderToStaticMarkup(createElement(ApprovalCard, { bot, message: kindMessage("mcp__my_server__create_issue") }));+ expect(underscored).toContain("Scout wants to my_server · create issue");+ const email = renderToStaticMarkup(createElement(ApprovalCard, { bot, message: kindMessage("mcp__email__EMAIL_SEND_MESSAGE") }));+ expect(email).toContain("Scout wants to send message");+ expect(email).not.toContain("email ·");+ const device = renderToStaticMarkup(createElement(ApprovalCard, { bot, message: kindMessage("mcp__device__calendar_list") }));+ expect(device).not.toContain("device ·");+ });++ it("labels the action from a qualified MCP title when the request carries no tool kind", () => {+ const message = kindMessage("tool");+ message.card = { ...message.card!, title: "mcp__github__create_issue" };+ const html = renderToStaticMarkup(createElement(ApprovalCard, { bot, message }));+ expect(html).toContain("Scout wants to github · create issue");+ expect(html).not.toContain("use a tool");+ const plain = renderToStaticMarkup(createElement(ApprovalCard, { bot, message: kindMessage("tool") }));+ expect(plain).toContain("Scout wants to use a tool");+ });+it("reads grammatically when no tool is known", () => {const html = renderToStaticMarkup(createElement(ApprovalCard, { message: kindMessage(undefined) }));expect(html).toContain("Wants to take an action");diff --git a/src/components/ApprovalCard.tsx b/src/components/ApprovalCard.tsxindex 083c3691ac..914b460b4a 100644--- a/src/components/ApprovalCard.tsx+++ b/src/components/ApprovalCard.tsx@@ -10,6 +10,7 @@ import { approvalDetailText, composioActionPhrase, outboundSummary } from "@/libimport { niceDate, niceTime, scheduleLabel } from "@/lib/schedule-label";import { cronPresetText, cronText } from "@/lib/cron-text";import { PROFILE_REQUEST_FIELDS, type ProfileRequestField } from "../../shared/profile-request";+import { RESERVED_MCP_NAMES } from "../../shared/mcp-name";import type { RoutineRequestSchedule } from "../../shared/routine-request";import { isSkillSwitchAction, type SkillShareRecord } from "../../shared/skill-request";import { cardAutomation } from "@/lib/automations";@@ -108,7 +109,11 @@ export function approvalCardOutcome(card: OptionCardData): string | undefined {export function toolLabel(tool?: string): string {if (!tool) return t("approval.tool.takeAction");- const bare = tool.replace(/^mcp__[^_]+__/, "").replace(/_/g, " ");+ // MCP tool names are `mcp__<server>__<name>`; a server name may itself carry underscores, so the server is the+ // second `__`-split segment and everything after it is the tool.+ const mcp = tool.startsWith("mcp__") ? tool.split("__") : undefined;+ const server = mcp?.[1];+ const action = (mcp ? mcp.slice(2).join("__") : tool).replace(/_/g, " ");const nice: ToolLabels = {Bash: "approval.tool.runCommand",Read: "approval.tool.readFile",@@ -134,7 +139,9 @@ export function toolLabel(tool?: string): string {};const key = nice[tool];if (key) return t(key);- return composioActionPhrase(tool.replace(/^mcp__[^_]+__/, "")) ?? bare;+ // A custom MCP server's tools read like the app's own unless the card names the server asking.+ const phrase = mcp ? composioActionPhrase(mcp.slice(2).join("__")) ?? action : action;+ return server && !RESERVED_MCP_NAMES.has(server) ? `${server} · ${phrase}` : phrase;}function plainWhen(schedule: RoutineRequestSchedule): string {@@ -465,6 +472,9 @@ export function ApprovalCard({? skillAction === "update" ? "update_skill" : "stage_skill": isProfileRequest? "update_profile"+ // An ACP permission request without a tool kind carries the qualified MCP tool name as its title: label the+ // action with it instead of "use a tool".+ : (!card.tool || card.tool === "tool") && (card.title ?? "").startsWith("mcp__") ? card.title: card.tool;const profileHeader = isProfileRequest && card.profileRequest? card.profileRequest.targetBotId === card.profileRequest.botIddiff --git a/src/components/NotificationsPanel.test.ts b/src/components/NotificationsPanel.test.tsindex 100e7c9e42..40836107e6 100644--- a/src/components/NotificationsPanel.test.ts+++ b/src/components/NotificationsPanel.test.ts@@ -39,6 +39,16 @@ describe("a row in the bell", () => {});});+describe("a row stored before notifications spoke plain text", () => {+ const scout: Bot = { id: "scout", threadId: "main", name: "Scout", title: "", description: "", notifications: true, color: "green", unread: false, modelSelection: { instanceId: "fake", model: "m" }, messages: [], tasks: [] };+ it("shows its Markdown as the readable line", () => {+ const state = { ...initialState, bots: [scout], notifications: [{ id: "n1", at: 1, read: true, kind: "done" as const, botId: "scout", botName: "Scout", threadId: "main", title: "Scout finished", body: "**Facture reçue** — [voir](https://example.com)" }] };+ const html = renderToStaticMarkup(createElement(StoreContext.Provider, { value: { state, dispatch: vi.fn() } as never }, createElement(NotificationsPanel)));+ expect(html).toContain("Facture reçue — voir");+ expect(html).not.toContain("**");+ });+});+describe("notificationThreadName", () => {it("finds a bot task title", () => {expect(notificationThreadName({ botId: "b1", threadId: "t-2" }, state)).toBe("Hotpatches");diff --git a/src/components/NotificationsPanel.tsx b/src/components/NotificationsPanel.tsxindex 4d49fa23c4..216fa70148 100644--- a/src/components/NotificationsPanel.tsx+++ b/src/components/NotificationsPanel.tsx@@ -9,6 +9,7 @@ import type { LocaleKey } from "@/locales";import { BotAvatar, type BotAvatarProps } from "./Avatar";import { threadUpdatedLabel } from "./SidebarThreadRow";import type { NotificationLogEntry, NotifyKind } from "../../shared/notification";+import { plainPreviewText } from "../../shared/plain-preview";import { Select } from "./Select";const KIND_LOOK: Record<NotifyKind, { Icon: LucideIcon; className: string; status: LocaleKey }> = {@@ -244,7 +245,7 @@ function NotificationRow({ entry, title, now, bot, threadName, onOpen }: { entry)}<span className={cn("shrink-0 text-[11px] font-medium", className)}>{t(status)}</span></span>- {entry.body && <span className="mt-0.5 block truncate text-[12px] text-ink-secondary">{entry.body}</span>}+ {entry.body && <span className="mt-0.5 block truncate text-[12px] text-ink-secondary">{plainPreviewText(entry.body)}</span>}<span className="mt-0.5 block text-[11px] text-ink-tertiary">{threadUpdatedLabel(entry.at, now)}</span></span></button>diff --git a/src/components/onboarding/SignInPill.poll.test.ts b/src/components/onboarding/SignInPill.poll.test.tsnew file mode 100644index 0000000000..f5c5281558--- /dev/null+++ b/src/components/onboarding/SignInPill.poll.test.ts@@ -0,0 +1,171 @@+// @vitest-environment happy-dom+// The pill's status poll: a dead server or network slows the poll and then says so, instead of spinning forever.+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { InstanceInfo } from "@/state/store";++const fixture = vi.hoisted(() => ({ responses: [] as Array<{ ok?: boolean; body?: unknown; hang?: boolean; status?: number; message?: string }> }));+vi.mock("@/state/store", async (importOriginal) => {+ const original = await importOriginal<typeof import("@/state/store")>();+ return {+ ...original,+ useStore: () => ({ refreshInstances: vi.fn(), refreshModels: vi.fn() }),+ api: vi.fn(async (url: string, init?: { timeoutMs?: number }) => {+ const entry = fixture.responses.shift();+ if (!entry) throw new Error(`unexpected call ${url}`);+ if (entry.hang) {+ return new Promise((_, reject) => {+ setTimeout(() => reject(Object.assign(new Error("The operation was aborted."), { name: "AbortError" })), init?.timeoutMs ?? 0);+ });+ }+ if (entry.status) throw new original.ApiError(entry.message ?? "gone", entry.status);+ if (!entry.ok) throw new Error("server unreachable");+ return entry.body;+ }),+ };+});+vi.mock("@/lib/app-links", () => ({ openExternalLink: vi.fn(async () => {}) }));+vi.mock("@/lib/product-events", () => ({ engineSignedIn: vi.fn() }));+vi.mock("@/components/ClaudeSignIn", () => ({ claudeSignInLink: () => null }));++import { api } from "@/state/store";+import { useSignInPill } from "./SignInPill";++const instance = {+ instanceId: "kimi-1",+ driverKind: "kimiAgent",+ displayName: "Kimi",+ authentication: { method: "device_code" },+} as never as InstanceInfo;++let root: Root;+let container: HTMLDivElement;+const probe = { pill: undefined as ReturnType<typeof useSignInPill> | undefined };+function Probe({ instance }: { instance: InstanceInfo | undefined }) {+ probe.pill = useSignInPill(instance);+ return createElement("div", null, probe.pill.slot.kind);+}+const render = () => flushSync(() => root.render(createElement(Probe, { instance })));+/** Let React commit the state a poll callback just set before the test reads it. */+const settle = async () => {+ for (let i = 0; i < 3; i++) await vi.advanceTimersByTimeAsync(0);+};+const calls = () => vi.mocked(api).mock.calls as unknown as string[][];++beforeEach(() => {+ vi.useFakeTimers();+ fixture.responses = [];+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ flushSync(() => root.unmount());+ container.remove();+ document.body.innerHTML = "";+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++describe("the sign-in pill's status poll", () => {+ it("keeps a waiting sign-in alive at its own pace while the server answers", async () => {+ fixture.responses = [+ { ok: true, body: { auth: { phase: "waiting", flowId: "f1" } } },+ { ok: true, body: { auth: { phase: "waiting", flowId: "f1" } } },+ ];+ render();+ await probe.pill!.start();+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(2_000);+ await vi.advanceTimersByTimeAsync(2_000);+ expect(calls().filter((c) => c[0].includes("/auth/status")).length).toBe(2);+ expect(probe.pill!.slot.kind).toBe("waiting");+ });++ it("slows down when the server stops answering, and gives up with the pill's own words", async () => {+ fixture.responses = [+ { ok: true, body: { auth: { phase: "waiting", flowId: "f1" } } },+ { ok: false }, { ok: false }, { ok: false },+ ];+ render();+ await probe.pill!.start();+ await vi.advanceTimersByTimeAsync(0);+ expect(probe.pill!.slot.kind).toBe("waiting");+ await vi.advanceTimersByTimeAsync(2_000);+ await vi.advanceTimersByTimeAsync(4_000);+ await vi.advanceTimersByTimeAsync(8_000);+ await settle();+ const status = calls().filter((c) => c[0].includes("/auth/status")).length;+ expect(status).toBe(3);+ expect(probe.pill!.slot.kind).toBe("start");+ expect(probe.pill!.error).toBe("Lost touch with the server during sign-in. Check the connection and start again.");+ await vi.advanceTimersByTimeAsync(60_000);+ expect((await calls()).filter((c) => c[0].includes("/auth/status")).length).toBe(3);+ });++ it("counts a request that never came back as a miss, through its own deadline", async () => {+ fixture.responses = [+ { ok: true, body: { auth: { phase: "waiting", flowId: "f1" } } },+ { hang: true }, { hang: true }, { hang: true },+ ];+ render();+ await probe.pill!.start();+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(2_000 + 10_000);+ await vi.advanceTimersByTimeAsync(4_000 + 10_000);+ await vi.advanceTimersByTimeAsync(8_000 + 10_000);+ await settle();+ expect(calls().filter((c) => c[0].includes("/auth/status")).length).toBe(3);+ expect(probe.pill!.slot.kind).toBe("start");+ expect(probe.pill!.error).toBe("Lost touch with the server during sign-in. Check the connection and start again.");+ });++ it("says what the server said when the sign-in is really gone, without retrying", async () => {+ fixture.responses = [+ { ok: true, body: { auth: { phase: "waiting", flowId: "f1" } } },+ { status: 404, message: "This sign-in flow is gone." },+ ];+ render();+ await probe.pill!.start();+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(2_000);+ await settle();+ expect(probe.pill!.slot.kind).toBe("start");+ expect(probe.pill!.error).toBe("This sign-in flow is gone.");+ expect(calls().filter((c) => c[0].includes("/auth/status")).length).toBe(1);+ });++ it("neither counts nor reschedules a request the cleanup aborted", async () => {+ fixture.responses = [+ { ok: true, body: { auth: { phase: "waiting", flowId: "f1" } } },+ { hang: true },+ ];+ render();+ await probe.pill!.start();+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(2_000);+ expect(calls().filter((c) => c[0].includes("/auth/status")).length).toBe(1);+ flushSync(() => root.unmount());+ await vi.advanceTimersByTimeAsync(60_000);+ expect(calls().filter((c) => c[0].includes("/auth/status")).length).toBe(1);+ });++ it("recovers the poll after one miss once the server is back", async () => {+ fixture.responses = [+ { ok: true, body: { auth: { phase: "waiting", flowId: "f1" } } },+ { ok: false },+ { ok: true, body: { auth: { phase: "succeeded", flowId: "f1" } } },+ ];+ render();+ await probe.pill!.start();+ await vi.advanceTimersByTimeAsync(0);+ await vi.advanceTimersByTimeAsync(2_000);+ await vi.advanceTimersByTimeAsync(4_000);+ await settle();+ expect(probe.pill!.slot.kind).toBe("start");+ expect(probe.pill!.error).toBeNull();+ });+});diff --git a/src/components/onboarding/SignInPill.tsx b/src/components/onboarding/SignInPill.tsxindex c7c491ad45..4562358e35 100644--- a/src/components/onboarding/SignInPill.tsx+++ b/src/components/onboarding/SignInPill.tsx@@ -8,10 +8,13 @@ import { useCopyFeedback } from "@/lib/copy-text";import { t } from "@/lib/i18n";import { plainSignIn } from "@/lib/onboarding";import { engineSignedIn } from "@/lib/product-events";-import { api, useStore, type InstanceInfo } from "@/state/store";+import { api, ApiError, useStore, type InstanceInfo } from "@/state/store";import { deviceSignInLink, isDeviceSignInCode } from "../../../shared/device-sign-in";const POLL_MS = 2_000;+const POLL_MAX_MS = 30_000;+const POLL_STALLS = 3;+const POLL_TIMEOUT_MS = 10_000;export const PILL = "ui-button ui-button-pill ui-button-lg ui-button-primary w-[288px] max-w-full";type Slot =@@ -107,21 +110,41 @@ export function useSignInPill(instance: InstanceInfo | undefined) {useEffect(() => {if (!polling) return;const controller = new AbortController();- const timer = window.setInterval(() => {- void api(`${base}/auth/status?flowId=${encodeURIComponent(polling)}`, { signal: controller.signal })+ let timer: number | undefined;+ let stalls = 0;+ let cancelled = false;+ const schedule = () => {+ if (cancelled) return;+ timer = window.setTimeout(check, Math.min(POLL_MS * 2 ** stalls, POLL_MAX_MS));+ };+ const check = () => {+ void api(`${base}/auth/status?flowId=${encodeURIComponent(polling)}`, { signal: controller.signal, timeoutMs: POLL_TIMEOUT_MS }).then(({ auth }: { auth: DeviceSignInStatus }) => {- if (auth.phase === "succeeded") void done();- else if (auth.phase !== "waiting") fail(new Error(auth.message ?? t("engineSetup.device.failed")));- else if (isDeviceSignInCode(provider, auth.userCode)) {+ if (cancelled) return;+ if (auth.phase === "succeeded") return void done();+ if (auth.phase !== "waiting") return fail(new Error(auth.message ?? t("engineSetup.device.failed")));+ stalls = 0;+ if (isDeviceSignInCode(provider, auth.userCode)) {const code = auth.userCode;setSlot((current) => current.kind === "code" && current.flowId === polling && current.code !== code? { ...current, code, link: deviceSignInLink(provider, auth.authorizationUrl, code) } : current);}+ schedule();})- .catch(() => {});- }, POLL_MS);+ .catch((cause) => {+ if (cancelled || controller.signal.aborted) return;+ // The server named a real problem (a flow that is gone, a dead session): show its words at once. A+ // request that never came back or a dropped connection only counts as a miss and slows the poll down.+ if (cause instanceof ApiError && cause.status < 500) return fail(cause);+ stalls += 1;+ if (stalls >= POLL_STALLS) fail(new Error(t("engineSetup.device.unreachable")));+ else schedule();+ });+ };+ schedule();return () => {- window.clearInterval(timer);+ cancelled = true;+ if (timer) window.clearTimeout(timer);controller.abort();};}, [polling, base, done, provider]);diff --git a/src/lib/copy-text.test.ts b/src/lib/copy-text.test.tsindex d5f5379bb0..2cdadfc7b6 100644--- a/src/lib/copy-text.test.ts+++ b/src/lib/copy-text.test.ts@@ -46,6 +46,33 @@ describe("copyText", () => {expect(await copyText("x")).toBe("failed");});+ const legacyDocument = (execCommand: () => boolean) => {+ const focus = vi.fn();+ vi.stubGlobal("document", {+ body: { appendChild() {} },+ activeElement: { focus },+ createElement: () => ({ style: {}, setAttribute() {}, select() {}, setSelectionRange() {}, remove() {} }),+ execCommand: vi.fn(execCommand),+ });+ return { focus, execCommand: (document as unknown as { execCommand: ReturnType<typeof vi.fn> }).execCommand };+ };++ it("copies with the legacy path when there is no clipboard and no bridge (phone on plain LAN http)", async () => {+ setEnv(undefined);+ const legacy = legacyDocument(() => true);+ expect(await copyText("hello")).toBe("copied");+ expect(legacy.execCommand).toHaveBeenCalledWith("copy");+ expect(legacy.focus).toHaveBeenCalled();+ });++ it("prefers the desktop bridge over the legacy path", async () => {+ const bridge = vi.fn(async () => true);+ setEnv(undefined, bridge);+ const legacy = legacyDocument(() => true);+ expect(await copyText("hello")).toBe("copied");+ expect(legacy.execCommand).not.toHaveBeenCalled();+ });+it("treats empty or blank text as empty and writes nothing", async () => {const writeText = vi.fn(async () => {});const bridge = vi.fn(async () => true);diff --git a/src/lib/copy-text.ts b/src/lib/copy-text.tsindex 1cc1a16424..99d4f945ee 100644--- a/src/lib/copy-text.ts+++ b/src/lib/copy-text.ts@@ -27,7 +27,33 @@ function writeWeb(text: string): Promise<boolean> {});}-/** The web Clipboard API rejects unfocused, denied and insecure-context writes; then the desktop bridge runs. Never throws. */+/**+ * Legacy execCommand fallback: on insecure-context (plain-LAN-HTTP) mobile+ * browsers `navigator.clipboard` is undefined and only the classic+ * select-then-copy path works. No-op outside a real DOM.+ */+function writeLegacy(text: string): boolean {+ if (typeof document === "undefined" || !document.body || typeof document.execCommand !== "function") return false;+ const active = document.activeElement as HTMLElement | null;+ const area = document.createElement("textarea");+ area.value = text;+ area.setAttribute("readonly", "");+ area.style.position = "fixed";+ area.style.left = "-9999px";+ try {+ document.body.appendChild(area);+ area.select();+ area.setSelectionRange(0, text.length);+ return document.execCommand("copy");+ } catch {+ return false;+ } finally {+ area.remove();+ active?.focus?.({ preventScroll: true });+ }+}++/** Web Clipboard API, then the desktop bridge, then legacy execCommand (insecure-context mobile). Never throws. */export async function copyText(text: string): Promise<CopyResult> {if (!text.trim()) return "empty";if (await writeWeb(text)) return "copied";@@ -35,7 +61,7 @@ export async function copyText(text: string): Promise<CopyResult> {if (typeof window !== "undefined" && (await window.ogb?.copyText?.(text)) === true) return "copied";} catch {}- return "failed";+ return writeLegacy(text) ? "copied" : "failed";}interface CopyFeedbackOptions {diff --git a/src/lib/notify.test.ts b/src/lib/notify.test.tsindex 8622551345..009d1f4af0 100644--- a/src/lib/notify.test.ts+++ b/src/lib/notify.test.ts@@ -110,6 +110,12 @@ describe("desktop notifications", () => {expect(notices[0]!.options).toMatchObject({ tag: "openmausbot:spend", icon: undefined });});+ it("shows a stored Markdown body as plain text", () => {+ const { notices } = installNotification("granted");+ showNotification({ ...frame, body: "**Facture reçue** — [voir](https://example.com)" }, vi.fn());+ expect(notices[0]?.options?.body).toBe("Facture reçue — voir");+ });+it("still alerts a focused app when another task is visible", () => {const { notices } = installNotification("granted", true);@@ -179,6 +185,13 @@ describe("on the desktop app, where main shows the banner so its click outlivesexpect(notices).toHaveLength(0);});+ it("hands main the same plain line for an older Markdown body", async () => {+ const { show } = installBridge(async () => true);+ showNotification({ ...frame, body: "**Facture reçue**" }, vi.fn());+ await flush();+ expect(show).toHaveBeenCalledWith(expect.objectContaining({ body: "Facture reçue" }));+ });+it("asks main for nothing without the person's permission or over the thread on screen, as ever", async () => {const denied = installBridge(async () => true);vi.stubGlobal("Notification", class { static permission = "denied"; });diff --git a/src/lib/notify.ts b/src/lib/notify.tsindex f677d483ba..e84fda3586 100644--- a/src/lib/notify.ts+++ b/src/lib/notify.ts@@ -1,4 +1,5 @@import type { Notification } from "../../shared/notification";+import { plainPreviewText } from "../../shared/plain-preview";import { finishedNotificationsEnabled, notificationSoundsEnabled } from "./notification-preferences";export type NotifyFrame = Notification;@@ -43,8 +44,10 @@ export function showNotification(if (Notification.permission !== "granted") return;const title = placeName ? `${placeName} · ${frame.title}` : frame.title;+ // Entries saved before the harness spoke plain text still carry Markdown.+ const body = plainPreviewText(frame.body);const options: NotificationOptions = {- body: frame.body,+ body,...buildNotificationOptions({ id: frame.botId, avatarUrl }),...(spend ? { tag: "openmausbot:spend", icon: undefined } : {}),...(notificationSoundsEnabled() ? {} : { silent: true }),@@ -58,6 +61,6 @@ export function showNotification(const desktop = window.ogb?.desktopNotifications;if (!desktop) return shownByPage();void desktop.show({- title, body: frame.body, tag: options.tag, silent: options.silent === true, picture: options.icon, botId: frame.botId, threadId: frame.threadId,+ title, body, tag: options.tag, silent: options.silent === true, picture: options.icon, botId: frame.botId, threadId: frame.threadId,}).then((shown) => { if (!shown) shownByPage(); }, shownByPage);}diff --git a/src/lib/plain-preview.ts b/src/lib/plain-preview.tsindex 4ec81e09f2..69f6f847fe 100644--- a/src/lib/plain-preview.ts+++ b/src/lib/plain-preview.ts@@ -1,40 +1 @@-export function plainPreviewText(text: string): string {- const escaped: string[] = [];- let out = text.replace(/\r\n?/g, "\n").replace(/\\([\\`*_{}[\]()#+\-.!|>~])/g, (_match, char: string) => {- escaped.push(char);- return `\uE000${escaped.length - 1}\uE001`;- });- const code: string[] = [];- const park = (body: string) => {- code.push(body.replace(/\uE000(\d+)\uE001/g, (_match, index: string) => `\\${escaped[Number(index)] ?? ""}`));- return `\uE002${code.length - 1}\uE003`;- };- // (a closing fence is the same character, at least as long as the opening)- out = out.replace(/^[ \t]*((`|~)\2{2,})[^\n]*(?:\n([\s\S]*?))?(?:\n[ \t]*\1\2*[ \t]*(?=\n|$(?![\s\S]))|$(?![\s\S]))/gm, (_block, _fence: string, _char: string, body: string | undefined) => `\n${park(body ?? "")}\n`);- out = out.replace(/(`+)([^`]*?)\1/g, (_span, _ticks: string, body: string) => park(body));- out = out.replace(/!\[([^\]]*)\]\((?:[^()]|\([^)]*\))*\)/g, "$1");- out = out.replace(/!\[([^\]]*)\]\[[^\]]*\]/g, "$1");- out = out.replace(/\[([^\]]+)\]\((?:[^()]|\([^)]*\))*\)/g, "$1");- out = out.replace(/\[([^\]]+)\]\[[^\]]*\]/g, "$1");- out = out.replace(/^[ \t]{0,3}\[[^\]]+\]:[ \t]+\S+.*$/gm, "");- out = out.replace(/<((?:https?|mailto):[^>\s]+)>/gi, "$1");- out = out.replace(/<br\s*\/?>/gi, " ");- out = out.replace(/<\/?(?:b|strong|i|em|u|s|del|ins|mark|code|kbd|sub|sup|small|span|p|div)\b[^>]*>/gi, "");- out = out.replace(/^[ \t]{0,3}#{1,6}[ \t]+/gm, "");- out = out.replace(/^[ \t]{0,3}#{1,6}[ \t]*$/gm, "");- out = out.replace(/^[ \t]*(?:>[ \t]?)+/gm, "");- out = out.replace(/^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?/gm, "");- out = out.replace(/^[ \t]*\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)*\|?[ \t]*$/gm, "");- out = out.replace(/^[ \t]{0,3}(?:[-*_][ \t]*){3,}$/gm, "");- out = out.replace(/^[ \t]*\|(.*)\|[ \t]*$/gm, (_row, cells: string) => cells.split("|").map((cell) => cell.trim()).filter(Boolean).join(" "));- // Underscores inside a word (snake_case) and a lone * (2 * 3) are not emphasis.- out = out.replace(/(\*{1,3}|_{1,3})(?=\S)([\s\S]*?\S)\1(?![\p{L}\p{N}])/gu, (match, marks: string, inner: string, offset: number, whole: string) => {- if (marks[0] === "_" && offset > 0 && /[\p{L}\p{N}]/u.test(whole[offset - 1]!)) return match;- return inner;- });- out = out.replace(/~~(?=\S)([\s\S]*?\S)~~/g, "$1");- out = out.replace(/\*\*+|`{3,}|~~/g, "");- out = out.replace(/\uE002(\d+)\uE003/g, (_match, index: string) => code[Number(index)] ?? "");- out = out.replace(/\uE000(\d+)\uE001/g, (_match, index: string) => escaped[Number(index)] ?? "");- return out.replace(/\s+/g, " ").trim();-}+export { plainPreviewText } from "../../shared/plain-preview";diff --git a/src/locales/en.json b/src/locales/en.jsonindex 0019ec7c9a..8fc6f643a9 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -5800,6 +5800,7 @@"engineSetup.device.cancelled": "Sign-in cancelled. You can request a new code when ready.","engineSetup.device.expired": "This code expired. Request a new code to try again.","engineSetup.device.failed": "Sign-in could not be completed. Try again, or check the Codex installation.",+ "engineSetup.device.unreachable": "Lost touch with the server during sign-in. Check the connection and start again.","engineSetup.device.invalidChallenge": "Codex did not return a valid OpenAI sign-in link and code. Cancel and try again.","engineSetup.device.flowEnded": "This sign-in session is no longer available. Check that this browser is still paired with Full access, then request a new code.","engineSetup.device.tryAgain": "Try again",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 8376637464..f4521d5a4e 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -511,7 +511,7 @@"cloudHome.step.starting": "Démarrage du Cloud","cloudHome.step.checking": "Vérification qu'il est prêt","cloudHome.connect": "Ouvrir le Cloud",- "cloudHome.connectHelp": "Ouvre le Cloud dans cette fenêtre. Revenez à « This computer » à gauche de l'application.",+ "cloudHome.connectHelp": "Ouvre le Cloud dans cette fenêtre. Revenez à l'icône de votre ordinateur, à gauche de l'application.","cloudHome.filesLink": "Partager des dossiers avec le Cloud dans Fichiers","cloudHome.connectFailed": "Impossible d'ouvrir le Cloud. Réessayez dans un instant.","cloudHome.waking": "Réveil du Cloud…",@@ -1908,7 +1908,7 @@"computer.linux.waylandBadge": "Indisponible sur Wayland","computer.linux.waylandBefore": "Le contrôle local est disponible sur Ubuntu Xorg. Il reste désactivé sur Wayland tant que sa frontière de sécurité des entrées n'est pas validée. Déconnectez-vous et choisissez","computer.linux.waylandXorg": "Ubuntu on Xorg",- "computer.linux.waylandAfter": "pour utiliser « This computer » ; le chat, le Bureau cloud, le Bureau privé et l’aperçu d’écran fonctionnent toujours ici.",+ "computer.linux.waylandAfter": "pour utiliser l'icône de votre ordinateur, à gauche de l'application ; le chat, le Bureau cloud, le Bureau privé et l’aperçu d’écran fonctionnent toujours ici.","computer.linux.enableBefore": "Une fois cette option activée, les bots que vous affectez explicitement à","computer.linux.enableAfter": "peuvent inspecter le bureau actif et demander des actions de souris ou de clavier. Chaque action locale vous demande d’abord votre autorisation.","computer.linux.waylandInput": "GNOME peut aussi vous demander d'autoriser la saisie au premier plan pour cette session de bureau.",@@ -2341,27 +2341,27 @@"app.loading.updating": "Mise à jour de My Cloud…","cloudSend.list.routineOne": "1 routine","cloudSend.list.routines": "{count} routines",- "cloudSend.result.held": "Ta clé {key} est enregistrée dans le Cloud. Tes bots l'utilisent dès que le crédit Claude de l'essai est épuisé.",- "cloudSend.move.copy": "Tes bots déménagent dans le Cloud…",- "cloudSend.move.copyChats": "Tes bots déménagent dans le Cloud… {done} sur {total} discussions",+ "cloudSend.result.held": "Votre clé {key} est enregistrée dans le Cloud. Vos bots l'utilisent dès que le crédit Claude de l'essai est épuisé.",+ "cloudSend.move.copy": "Vos bots déménagent dans le Cloud…",+ "cloudSend.move.copyChats": "Vos bots déménagent dans le Cloud… {done} sur {total} discussions","cloudSend.move.bringing": "Les bots de cet ordinateur arrivent dans le Cloud…","cloudSend.move.bringingChats": "Les bots de cet ordinateur arrivent dans le Cloud… {done} sur {total} discussions",- "cloudSend.move.waiting": "Tes bots déménagent dans le Cloud… en attendant que {name} ait fini",- "cloudSend.move.waitingAny": "Tes bots déménagent dans le Cloud… en attendant que tes bots aient fini",- "cloudSend.move.waitingSignIn": "Tes bots déménagent dans le Cloud… en attendant qu'une connexion soit terminée",+ "cloudSend.move.waiting": "Vos bots déménagent dans le Cloud… en attendant que {name} ait fini",+ "cloudSend.move.waitingAny": "Vos bots déménagent dans le Cloud… en attendant que vos bots aient fini",+ "cloudSend.move.waitingSignIn": "Vos bots déménagent dans le Cloud… en attendant qu'une connexion soit terminée","cloudSend.move.finishing": "Déménagement dans le Cloud… presque fini",- "cloudSend.move.updating": "My Cloud est en cours de mise à jour. Ton déménagement commence une fois la mise à jour terminée.",- "cloudSend.move.failing": "Tes bots n'ont pas encore pu déménager dans le Cloud : {error}",- "cloudSend.move.failingPlain": "Tes bots n'ont pas encore pu déménager dans le Cloud.",+ "cloudSend.move.updating": "My Cloud est en cours de mise à jour. Votre déménagement commence une fois la mise à jour terminée.",+ "cloudSend.move.failing": "Vos bots n'ont pas encore pu déménager dans le Cloud : {error}",+ "cloudSend.move.failingPlain": "Vos bots n'ont pas encore pu déménager dans le Cloud.","cloudSend.move.done": "Tout ce qui venait de cet ordinateur est ici : {list}.","cloudSend.move.doneAll": "Tout ce qui venait de cet ordinateur est ici.",- "cloudSend.move.phone": "Associer ton téléphone au Cloud",- "cloudSend.move.homeAgain": "Ton Cloud a pris fin, donc tes bots sont de retour sur cet ordinateur. Ce que tu as fait dans le Cloud revient aussi.",- "cloudSend.move.back": "Ton Cloud a pris fin, donc tes bots sont de retour sur cet ordinateur, avec ce que tu as fait dans le Cloud. Les identifiants et les clés ajoutés dans le Cloud ne sont pas revenus : ajoute-les ici à nouveau si tu en as besoin.",- "cloudSend.move.backLost": "Ton Cloud a pris fin, donc tes bots sont de retour sur cet ordinateur tels qu'ils étaient au moment du déménagement. Ce que tu as fait dans le Cloud depuis n'a pas pu revenir.",- "cloudSend.move.backGone": "Le Cloud où tes bots avaient déménagé a pris fin, donc ils sont de retour sur cet ordinateur tels qu'ils étaient au moment du déménagement. Leurs automatisations sont désactivées : active celles que tu veux.",- "cloudSend.move.elsewhere": "Tes bots sont revenus sur {name}. Cet ordinateur garde sa copie du {date}, avec les automatisations désactivées.",- "cloudSend.move.elsewhereEmpty": "Tes bots sont revenus sur {name}.",+ "cloudSend.move.phone": "Associer votre téléphone au Cloud",+ "cloudSend.move.homeAgain": "Votre Cloud a pris fin, donc vos bots sont de retour sur cet ordinateur. Ce que vous avez fait dans le Cloud revient aussi.",+ "cloudSend.move.back": "Votre Cloud a pris fin, donc vos bots sont de retour sur cet ordinateur, avec ce que vous avez fait dans le Cloud. Les identifiants et les clés ajoutés dans le Cloud ne sont pas revenus : ajoutez-les ici à nouveau si vous en avez besoin.",+ "cloudSend.move.backLost": "Votre Cloud a pris fin, donc vos bots sont de retour sur cet ordinateur tels qu'ils étaient au moment du déménagement. Ce que vous avez fait dans le Cloud depuis n'a pas pu revenir.",+ "cloudSend.move.backGone": "Le Cloud où vos bots avaient déménagé a pris fin, donc ils sont de retour sur cet ordinateur tels qu'ils étaient au moment du déménagement. Leurs automatisations sont désactivées : activez celles que vous voulez.",+ "cloudSend.move.elsewhere": "Vos bots sont revenus sur {name}. Cet ordinateur garde sa copie du {date}, avec les automatisations désactivées.",+ "cloudSend.move.elsewhereEmpty": "Vos bots sont revenus sur {name}.","homeScreen.openingNamed": "Ouverture de {name}…","homeScreen.offlineNamed": "Impossible de joindre {name} pour le moment.","homeScreen.signInNamed": "Connectez-vous pour ouvrir {name}",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex f9a56e5894..f3fde7a8e7 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -5537,6 +5537,7 @@"engineSetup.device.cancelled": "Login cancelado. Você pode pedir um novo código quando quiser.","engineSetup.device.expired": "Este código expirou. Peça um novo código para tentar novamente.","engineSetup.device.failed": "Não foi possível concluir o login. Tente novamente ou verifique a instalação do Codex.",+ "engineSetup.device.unreachable": "Perdemos a conexão com o servidor durante o login. Verifique a conexão e comece de novo.","engineSetup.device.invalidChallenge": "O Codex não devolveu um link e um código de login válidos da OpenAI. Cancele e tente novamente.","engineSetup.device.flowEnded": "Esta sessão de login não está mais disponível. Verifique se este navegador ainda está pareado com “Acesso total” e peça um novo código.","engineSetup.device.tryAgain": "Tentar novamente",