Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
i18n(pt-br): wire the new upstream strings
KesleyDEVbbb61c9b9cd7
diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex 02fa92a926..8ed546a906 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -634,12 +634,12 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst current = grant;if (cloudId !== null) {const cloud = otherOwnCloud(cloudId);- if (!current || !cloud) throw Object.assign(new Error("That Cloud is no longer one of yours."), { gone: true });- if (!cloud.origin || !["ready", "offline"].includes(cloud.status)) throw new Error(`${cloud.name} isn't ready to open yet.`);+ if (!current || !cloud) throw Object.assign(new Error(t("native.cloud.otherGone")), { gone: true });+ if (!cloud.origin || !["ready", "offline"].includes(cloud.status)) throw new Error(t("native.cloud.otherNotReady", { name: cloud.name }));let result;try { result = await request("pairing", { method: "POST", body: { cloudId }, token: current.token }); } catch (error) {- if (error?.status === 404 && !error.opaque) { void refresh().catch(() => {}); throw Object.assign(new Error(`${cloud.name} is no longer one of your Clouds.`), { gone: true }); }- if (error?.status === 409) throw new Error(`${cloud.name} isn't running right now.`);+ if (error?.status === 404 && !error.opaque) { void refresh().catch(() => {}); throw Object.assign(new Error(t("native.cloud.otherNoLongerYours", { name: cloud.name })), { gone: true }); }+ if (error?.status === 409) throw new Error(t("native.cloud.otherNotRunning", { name: cloud.name }));throw error;}const pairing = parsePairingGrant(result, cloud.origin, now());@@ -670,7 +670,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNasync addCloud({ tier, interval = "month", name, color = null } = {}) {const cleanName = cleanCloudListName(name);if (typeof tier !== "string" || !TIER.test(tier) || !ADD_INTERVALS.includes(interval) || !cleanName || !(color === null || CLOUD_SWATCHES.includes(color))) {- throw new Error("Invalid Cloud to add.");+ throw new Error(t("native.cloud.invalidAdd"));}const signedIn = grant;if (!signedIn || state().status !== "connected") return { outcome: "failed" };@@ -711,7 +711,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN* with the Admin's reason; `taken` when another of the plan's has that name; `unsupported` from an Admin without it. */async addOrganization({ name, color = null } = {}) {const cleanName = cleanCloudListName(name);- if (!cleanName || !(color === null || CLOUD_SWATCHES.includes(color))) throw new Error("Invalid organization to add.");+ if (!cleanName || !(color === null || CLOUD_SWATCHES.includes(color))) throw new Error(t("native.cloud.invalidOrganization"));const signedIn = grant;if (!signedIn || state().status !== "connected") return { outcome: "failed" };if (!value.organizations) return { outcome: "unsupported" };@@ -731,7 +731,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN* change: `saved` once the Admin keeps it (the session is read again, so every place follows); `refused` when the* Admin says it is someone else's to change; `unsupported` from an Admin without the route or the list. */async setCloudColor(cloudId, color) {- if (typeof cloudId !== "string" || !CLOUD_ID.test(cloudId) || !(color === null || CLOUD_SWATCHES.includes(color))) throw new Error("Invalid Cloud color.");+ if (typeof cloudId !== "string" || !CLOUD_ID.test(cloudId) || !(color === null || CLOUD_SWATCHES.includes(color))) throw new Error(t("native.cloud.invalidColor"));const signedIn = grant;if (!signedIn || state().status !== "connected") return { outcome: "failed" };if (!value.clouds?.some(cloud => cloud.id === cloudId && cloud.managed !== false)) return { outcome: "unsupported" };@@ -750,7 +750,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN* when it says that Cloud can't be removed now; `gone` when it is not theirs any more; `unsupported` from an Admin without* Remove from list (whose session never says `removable`). */async hideCloud(cloudId) {- if (typeof cloudId !== "string" || !CLOUD_ID.test(cloudId)) throw new Error("Invalid Cloud to remove.");+ if (typeof cloudId !== "string" || !CLOUD_ID.test(cloudId)) throw new Error(t("native.cloud.invalidRemove"));const signedIn = grant;if (!signedIn || state().status !== "connected") return { outcome: "failed" };if (!value.clouds?.some(cloud => cloud.id === cloudId && cloud.removable === true)) return { outcome: "unsupported" };diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex 713e733b2f..993e1cb47e 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -1,3 +1,4 @@+import nativeText from "./native-text.cjs";// The rail of places at the left of the window (the renderer's PlacesRail, drawn by the window's own chrome rail page,// chrome-rail.mjs) and its +: main builds the list, says who may read it, and does what a circle or + asks through// main's own switch and dialogs.@@ -109,7 +110,7 @@ export function addCloudView(state, offer) {/*** "“{name}” is ready", once per Cloud this app bought, unless its sheet shows it in the focused window; a click opens it.*/-export function createAddedCloudNotice({ Notification, focused, sheetOpen, open, shown = () => {} }) {+export function createAddedCloudNotice({ Notification, focused, sheetOpen, open, shown = () => {}, t = nativeText.englishText.t }) {const announced = new Set();return state => {const adding = state?.status === "connected" ? state.adding : null;@@ -117,7 +118,7 @@ export function createAddedCloudNotice({ Notification, focused, sheetOpen, open,if (!listed || !["ready", "offline"].includes(listed.status) || !listed.origin || announced.has(adding.cloudId)) return false;announced.add(adding.cloudId);if ((focused() && sheetOpen()) || !Notification.isSupported()) return false;- const note = new Notification({ title: `“${listed.name}” is ready`, body: "Click to open it." });+ const note = new Notification({ title: t("native.cloud.ready.quotedTitle", { name: listed.name }), body: t("native.cloud.ready.open") });note.on("click", () => open(adding.cloudId));note.show();shown();@@ -137,7 +138,7 @@ const CHOICES = Object.freeze(["cloud", "link", "address"]);* `places()` is railPlaces' list now; `open(id)` main's own switch; `add` the + sheet's fixed actions; `account()` the* MausBot Cloud sign-in; `targets()` the pages told when something changed.*/-export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets }) {+export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, beside = () => false, places, open, add, account, clipboard, openCloud, targets, t = nativeText.englishText.t }) {let sheetOpen = false, sent = "";const allowed = (channel, handler) => guard((event, ...args) => {if (!trusted(event)) throw new Error(`${channel} is only available in this app's window`);@@ -157,37 +158,37 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes// A Cloud the Admin is still making has no saved place: its own screen opens, by main's word for which Cloud it is.listed("workspaces:open", (_event, id) => {const place = places().find(entry => entry.id === plain(id) && entry.opens);- if (!place) throw new Error("That place isn't here any more.");+ if (!place) throw new Error(t("native.places.noLongerHere"));return place.id.startsWith(PENDING) ? openCloud(place.cloudId) : open(place.id);});// Remove from list, from a circle's menu (the page asked the person first): only a Cloud main listed as removable.listed("workspaces:remove", async (_event, id) => {const place = places().find(entry => entry.id === plain(id) && entry.removable && entry.cloudId);- if (!place) throw new Error("That place isn't here any more.");+ if (!place) throw new Error(t("native.places.noLongerHere"));const client = account();return { outcome: client?.hideCloud ? (await client.hideCloud(place.cloudId)).outcome : "unsupported" };});// A link pasted on +'s sheet goes to main's own Connect dialog, which checks it and names its host before connecting.listed("workspaces:add", (_event, choice, link) => {- if (!CHOICES.includes(choice) || !add.choices()[choice]) throw new Error("That isn't something to add here.");+ if (!CHOICES.includes(choice) || !add.choices()[choice]) throw new Error(t("native.places.cannotAdd"));const pasted = choice === "link" ? plain(link).trim().slice(0, 4096) : "";return pasted ? add.run(choice, pasted) : add.run(choice);});handle("cloud-add:state", () => view());handle("cloud-add:start", async (_event, tier, name, color) => {const client = account();- if (!client) throw new Error("Sign in to MausBot Cloud first.");+ if (!client) throw new Error(t("native.cloud.addSignIn"));const plans = (await client.offer().catch(() => null))?.plans ?? [];const cleanName = cleanCloudListName(plain(name)), swatch = CLOUD_SWATCHES.includes(color) ? color : null;- if (!plans.some(plan => plan.tier === plain(tier)) || !cleanName) throw new Error("Choose a plan and a name to continue.");+ if (!plans.some(plan => plan.tier === plain(tier)) || !cleanName) throw new Error(t("native.cloud.addPlanAndName"));const result = await client.addCloud({ tier: plain(tier), interval: "month", name: cleanName, color: swatch });return result.outcome === "blocked" ? { outcome: "blocked", blocked: result.blocked } : { outcome: result.outcome };});handle("cloud-add:organization", async (_event, name, color) => {const client = account();- if (!client) throw new Error("Sign in to MausBot Cloud first.");+ if (!client) throw new Error(t("native.cloud.addSignIn"));const cleanName = cleanCloudListName(plain(name)), swatch = CLOUD_SWATCHES.includes(color) ? color : null;- if (!cleanName) throw new Error("Give the organization a name to continue.");+ if (!cleanName) throw new Error(t("native.cloud.addOrganizationName"));const result = await client.addOrganization({ name: cleanName, color: swatch });return result.outcome === "blocked" ? { outcome: "blocked", blocked: result.blocked } : { outcome: result.outcome };});@@ -199,7 +200,7 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bes});handle("cloud-add:open", async () => {const adding = account()?.state().adding;- if (!adding?.cloudId) throw new Error("There is no new Cloud to open.");+ if (!adding?.cloudId) throw new Error(t("native.cloud.noNewCloud"));await openCloud(adding.cloudId);account()?.addDone();});diff --git a/electron/cloud-sync-main.mjs b/electron/cloud-sync-main.mjsindex 88a81740fd..704ee7d194 100644--- a/electron/cloud-sync-main.mjs+++ b/electron/cloud-sync-main.mjs@@ -12,10 +12,10 @@ const TOKEN_MS = 30 * 60_000;/** `stateDir`: Files' own folder under userData; the staging Admin keeps its own (cloud-account.mjs cloudTarget).* `lending`: main's pieces for lending to My Cloud ({ environment, sharing, validate }): each lent folder gets a copy,* and a folder added here is lent, read only (lent-folders.mjs). */-export function installCloudFiles({ app, ipcMain, dialog, shell, powerMonitor, fetch, localWorkspaceOnly, send, cloudOrigin, cloudAccount, localDataDir, power, lending: lendingParts = null, now = Date.now, stateDir = "cloud-sync" }) {+export function installCloudFiles({ app, ipcMain, dialog, shell, powerMonitor, fetch, localWorkspaceOnly, send, cloudOrigin, cloudAccount, localDataDir, power, lending: lendingParts = null, now = Date.now, stateDir = "cloud-sync", t }) {const lending = lendingParts ? lendingForFiles(lendingParts) : null;const dir = path.join(app.getPath("userData"), stateDir);- const service = createCloudFilesService({+ const service = createCloudFilesService({ t,settingsFile: path.join(dir, "settings.json"), stateFile: path.join(dir, "state.db"),documentsDir: app.getPath("documents"), homeDir: app.getPath("home"), localDataDir, cloudOrigin, fetch, ...(power ? { power } : {}),trashItem: (file) => shell.trashItem(file), markDownloaded: createDownloadMarker(),diff --git a/electron/cloud-sync.mjs b/electron/cloud-sync.mjsindex fdc19d90ab..a9808bc7fd 100644--- a/electron/cloud-sync.mjs+++ b/electron/cloud-sync.mjs@@ -58,7 +58,7 @@ const sleep = (ms, signal) => new Promise((resolve) => {export function createCloudFilesService({settingsFile, stateFile, documentsDir, localDataDir, homeDir = os.homedir(), platform = process.platform, hostname = os.hostname(),cloudOrigin, fetch: fetchImpl, trashItem, markDownloaded, openDashboard = async () => {},- createClient = createSyncClient, watch = watchFolder, freeBytes, now = Date.now, onChange = () => {}, power = createCloudPowerGate(),+ t, createClient = createSyncClient, watch = watchFolder, freeBytes, now = Date.now, onChange = () => {}, power = createCloudPowerGate(),lending = null, planDisk = () => null,}) {let settings = readSettings(settingsFile);@@ -221,7 +221,7 @@ export function createCloudFilesService({// lending is paused they wait on My Cloud, as they do while this computer is away.const lentFolder = current.lentId && !lent?.paused ? lent?.folders.find((entry) => entry.id === current.lentId) : null;const waiting = summary.folders.find((entry) => entry.id === current.id)?.staged ?? 0;- const landed = lentFolder && waiting > 0 ? await applyStaged({ client: cloud, folderId: current.id, folder: lentFolder, protectedPaths: lent.protectedPaths,+ const landed = lentFolder && waiting > 0 ? await applyStaged({ t, client: cloud, folderId: current.id, folder: lentFolder, protectedPaths: lent.protectedPaths,now, trashItem, markDownloaded, platform, stopper: passStopper }) : null;if (landed?.kept.length) update(folder.key, { kept: [...landed.kept, ...(current.kept ?? [])].slice(0, KEPT_MAX) });const result = await shareFolder({ client: cloud, state, folder: { id: current.id }, local: current.pcPath, now, approveDeletes, report });diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjsindex 11e6fb76a4..6215043aa1 100644--- a/electron/computer-sharing.mjs+++ b/electron/computer-sharing.mjs@@ -647,9 +647,9 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu* can't take them yet (paused, or not signed in there), so the move tries again later. */async lendProjects(paths) {const env = myCloud();- if (paused || !env || !verifiedCloud(env)) throw new Error("Lending to My Cloud waits until it is signed in and not paused.");+ if (paused || !env || !verifiedCloud(env)) throw new Error(t("native.lend.moveWaiting"));await lendAutomatically(Array.isArray(paths) ? paths.filter(where => typeof where === "string") : []);- if (records[env.id]?.enabled !== true) throw new Error("Lending to My Cloud did not start.");+ if (records[env.id]?.enabled !== true) throw new Error(t("native.lend.moveNotStarted"));},paused: () => paused,/** Every Cloud of the person's own stops using this computer, across restarts too, until resume(). */diff --git a/electron/data-dir-lease.mjs b/electron/data-dir-lease.mjsindex d2757bc2e9..ee5cc72fe9 100644--- a/electron/data-dir-lease.mjs+++ b/electron/data-dir-lease.mjs@@ -145,7 +145,8 @@ function sameMachine(record) {return boot !== null && typeof record.boot === "string" && record.boot === boot;}-function otherMachineAdvice(path) {+function otherMachineAdvice(path, t) {+ if (t) return t("native.boot.sharedFolderAdvice", { path: JSON.stringify(path) });return ` If OpenMausBot is not running on another computer or container that shares this folder, quit OpenMausBot, delete ${JSON.stringify(path)} and start again.`;}@@ -383,13 +384,13 @@ function prepareDataDir(dataDir, legacyDataDir) {return join(dataDir, LEASE_NAME);}-function assertNoLiveDelegatedChild(dataDir) {+function assertNoLiveDelegatedChild(dataDir, t) {const childLeasePath = join(dataDir, DELEGATED_CHILD_DIR, LEASE_NAME);const child = readOwner(childLeasePath);if (!child) return;if (!sameMachine(child)) {throw leaseError(- `This OpenMausBot data directory still has a delegated server on another machine. Delegated server lease: ${JSON.stringify(childLeasePath)}.${otherMachineAdvice(childLeasePath)}`,+ `This OpenMausBot data directory still has a delegated server on another machine. Delegated server lease: ${JSON.stringify(childLeasePath)}.${otherMachineAdvice(childLeasePath, t)}`,);}if (ownerIsAlive(child)) {@@ -458,7 +459,7 @@ function validateChildDelegation(dataDir, encoded) {function acquireDataDirLeaseInternal(dataDir, options = {}) {const leasePath = prepareDataDir(dataDir, options.legacyDataDir);- if (options.guardDelegatedChild !== false) assertNoLiveDelegatedChild(dataDir);+ if (options.guardDelegatedChild !== false) assertNoLiveDelegatedChild(dataDir, options.t);const owner = {version: 1,pid: process.pid,@@ -493,7 +494,7 @@ function acquireDataDirLeaseInternal(dataDir, options = {}) {if (!current) continue;if (!sameMachine(current)) {throw leaseError(- `This OpenMausBot data directory is already owned by a process on another machine. Lease record: ${JSON.stringify(leasePath)}.${otherMachineAdvice(leasePath)}`,+ `This OpenMausBot data directory is already owned by a process on another machine. Lease record: ${JSON.stringify(leasePath)}.${otherMachineAdvice(leasePath, options.t)}`,);}if (ownerIsAlive(current)) {diff --git a/electron/desktop-prefs.node-test.mjs b/electron/desktop-prefs.node-test.mjsindex 75611e2199..b418578e65 100644--- a/electron/desktop-prefs.node-test.mjs+++ b/electron/desktop-prefs.node-test.mjs@@ -308,7 +308,7 @@ test("production wiring: main answers this computer's page, My Cloud's own pagelet switched = async id => { calls.push(["switch", id]); }, loads = true;const context = vm.createContext({registerDesktopPrefs: value => { options = value; }, jsonFile: file => ({ read: () => file, write: () => {} }), ipcMain: {}, updatesConsent: null, cloudAccount: "the client",- nativeText: { prefs: { kept: true }, set: code => { calls.push(["language", code]); return code === "pt-br"; } }, applyNativeLanguage: () => calls.push("relabel"),+ nativeText: { prefs: { kept: true }, set: code => { calls.push(["language", code]); return code === "pt-br"; } }, applyNativeLanguage: () => calls.push("relabel"), talk: { relabel: () => calls.push("talk relabel") },path: { join: (...parts) => parts.join("/") }, app: { getPath: () => "/user-data" }, desktopDataDir: () => "/home/.openmausbot",navigateMainWindow: async url => { calls.push(["navigate", url]); return loads; },senderIsLocal: localOrigin.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed,@@ -336,7 +336,7 @@ test("production wiring: main answers this computer's page, My Cloud's own pageoptions.languageChanged("en", windows[0].webContents);assert.deepEqual(sent, [["home", "desktop-language:changed", "en"], ["rail", "desktop-language:changed", "en"]], "every other open window hears the pick, and the window's rail");options.onLanguage("pt-br"); options.onLanguage("en");- assert.deepEqual(calls.slice(2), [["language", "pt-br"], "relabel", ["language", "en"]], "main draws again only when the words change");+ assert.deepEqual(calls.slice(2), [["language", "pt-br"], "relabel", "talk relabel", ["language", "en"]], "main draws its native surfaces again only when the words change");const navigate = main.slice(main.indexOf("function navigateMainWindow(url) {"), main.indexOf("\n}\n", main.indexOf("function navigateMainWindow(url) {")) + 3);const load = vm.runInNewContext(`${navigate}; navigateMainWindow`, { mainWindow: { isDestroyed: () => false, loadURL: async url => { if (url.endsWith("fail")) throw new Error("ERR_CONNECTION_REFUSED"); } } });assert.equal(await load(`${LOCAL}/ok`), true); assert.equal(await load(`${LOCAL}/fail`), false, "a failed load answers false, never throws");diff --git a/electron/lending-indicator.mjs b/electron/lending-indicator.mjsindex f22f51a8aa..e0932f21db 100644--- a/electron/lending-indicator.mjs+++ b/electron/lending-indicator.mjs@@ -27,8 +27,8 @@ export function createLendingIndicator({ Tray, Menu, nativeImage, iconPath, onPatray.setContextMenu(Menu.buildFromTemplate([{ label: line, enabled: false },{ type: "separator" },- view.paused ? { label: "Resume", click: () => onResume() } : { label: "Pause", click: () => onPause() },- { label: "See activity", click: () => onActivity() },+ view.paused ? { label: t("native.lendTray.resume"), click: () => onResume() } : { label: t("native.lendTray.pause"), click: () => onPause() },+ { label: t("native.lendTray.activity"), click: () => onActivity() },]));};return {diff --git a/electron/lent-staged.mjs b/electron/lent-staged.mjsindex 1a55c38c17..81bf5d11eb 100644--- a/electron/lent-staged.mjs+++ b/electron/lent-staged.mjs@@ -1,3 +1,4 @@+import nativeText from "./native-text.cjs";// Bots' changes to a lent folder, made on My Cloud while this computer was away (server/lent-copies.ts), applied here// once it is back, under the same rules as a live write (electron/shared-computer-access.mjs): only a folder lent with// editing, never through a link, never inside .git or a protected place. A file the person did not touch since takes@@ -43,14 +44,14 @@ function keepPermissions(file, before) {* offline), thrown on. Answers how many changes landed and, for each one kept beside the person's own version, both* names.*/-export async function applyStaged({ client, folderId, folder, protectedPaths = [], now = Date.now, trashItem, markDownloaded = async () => {}, platform = process.platform, stopper = () => false }) {+export async function applyStaged({ client, folderId, folder, protectedPaths = [], now = Date.now, trashItem, markDownloaded = async () => {}, platform = process.platform, stopper = () => false, t = nativeText.englishText.t }) {const outcome = { applied: 0, kept: [], problem: null };if (folder.write !== true) return outcome;const changes = await client.staged(folderId);const protectedRoots = await protectedIdentities(protectedPaths);for (const change of changes) {try {- const landed = await applyOne({ client, folderId, folder, change, protectedRoots, now, trashItem, markDownloaded, platform });+ const landed = await applyOne({ client, folderId, folder, change, protectedRoots, now, trashItem, markDownloaded, platform, t });if (!landed) continue;await client.stagedDone(folderId, change.id, change.sha256);if (landed.beside) outcome.kept.push({ path: change.path, beside: landed.beside, at: now() });@@ -63,9 +64,9 @@ export async function applyStaged({ client, folderId, folder, protectedPaths = [return outcome;}-async function applyOne({ client, folderId, folder, change, protectedRoots, now, trashItem, markDownloaded, platform }) {- if (!validWirePath(change.path) || (platform === "win32" && windowsProblem(change.path))) throw new Error("This computer can't hold that name.");- if (insideGitInternals(folder.path, change.path)) throw new Error("Files inside .git are never changed from My Cloud.");+async function applyOne({ client, folderId, folder, change, protectedRoots, now, trashItem, markDownloaded, platform, t }) {+ if (!validWirePath(change.path) || (platform === "win32" && windowsProblem(change.path))) throw new Error(t("native.files.nameNotSupported"));+ if (insideGitInternals(folder.path, change.path)) throw new Error(t("native.files.gitProtected"));const target = await sharedPath(folder, change.path);await assertOutsideProtected(protectedRoots, target);fs.mkdirSync(path.dirname(target), { recursive: true });@@ -74,7 +75,7 @@ async function applyOne({ client, folderId, folder, change, protectedRoots, now,const temporary = path.join(path.dirname(target), `.${path.basename(target).slice(0, 180)}.omb-sync-${tag}`);try {await client.stagedFile(folderId, change.id, temporary);- if (await sha256File(temporary) !== change.sha256) throw new Error("The change was damaged on its way; it will be fetched again.");+ if (await sha256File(temporary) !== change.sha256) throw new Error(t("native.files.changeDamaged"));await markDownloaded(temporary);const before = fs.lstatSync(target, { throwIfNoEntry: false });if (before?.isFile() && before.nlink === 1) {@@ -94,7 +95,7 @@ async function applyOne({ client, folderId, folder, change, protectedRoots, now,return { applied: true };}// The person changed it, removed it, or something else is there now: theirs stays, the bot's lands beside it.- const beside = clashPath(change.path, now(), (candidate) => fs.existsSync(path.join(folder.path, ...candidate.split("/"))), BESIDE_LABEL);+ const beside = clashPath(change.path, now(), (candidate) => fs.existsSync(path.join(folder.path, ...candidate.split("/"))), t("native.files.newFromCloud"));const besideFile = await sharedPath(folder, beside);await assertOutsideProtected(protectedRoots, besideFile);renameWithRetry(temporary, besideFile);diff --git a/electron/main.mjs b/electron/main.mjsindex e370446fca..1a745830a7 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -1597,8 +1597,8 @@ let rememberedHome = null;function acquireDataDirLeaseFor(dir) {return dir === desktopDataDir()- ? acquireDataDirLease(dir, { legacyDataDir: path.join(app.getPath("home"), ".opengrokbot") })- : acquireDataDirLease(dir);+ ? acquireDataDirLease(dir, { t: nativeT, legacyDataDir: path.join(app.getPath("home"), ".opengrokbot") })+ : acquireDataDirLease(dir, { t: nativeT });}/** Pause the supervisor first, or its recovery forks on the wrong data dir; resume() stays in the finally. */@@ -2435,7 +2435,7 @@ ipcMain.handle("desktop:relaunch", localOnly("desktop:relaunch", (event) => {}));const talk = installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions.appleSpeech,- speech: { start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy }, packaged: app.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog });+ speech: { start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy }, packaged: app.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog, t: nativeT });ipcMain.handle("companion:state", localOnly("companion:state", () => desktopCompanionState()));function managedRemoteAccessRefusal() {@@ -2693,20 +2693,20 @@ const chromeRail = createChromeRail({ createView: options => new WebContentsViewurl: () => `${rendererOrigin()}${CHROME_RAIL_PATH}`, wanted: () => !desktopRemoteAccess && serverReady && railList().length > 0 });chromeRail.install(ipcMain);function railChanged() { chromeRail.refresh(); rail.changed(); }-const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),+const rail = installCloudRail({ t: nativeT, ipcMain, clipboard, openCloud: openOwnCloud, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null),guard: handler => (event, ...args) => (chromeRail.owns(event) ? handler(event, ...args) : workspaceOnly(handler)(event, ...args)),lists: event => chromeRail.owns(event), trusted: event => chromeRail.owns(event) || senderIsLocal(event), beside: () => chromeRail.shown(),targets: () => [mainWindow && !mainWindow.isDestroyed() ? mainWindow.webContents : null, { send: channel => chromeRail.send(channel), isDestroyed: () => false }],places: railList, open: id => workspaceMenuAction(() => switchEnvironment(id)),add: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),run: (choice, link) => (choice === "link" ? (link ? connectHostedWorkspace(link) : addServerFromClipboard()) : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });-const announceAddedCloud = createAddedCloudNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,+const announceAddedCloud = createAddedCloudNotice({ t: nativeT, Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,open: id => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });// A place's colour (place-look.mjs): the Admin's for a Cloud, this app's for This computer and a server connected by// hand; changed on the place's own page or from the window's rail, whatever that server runs.installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => savedPlace(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),setColor: (id, swatch) => ensureCloudAccount().setCloudColor(id, swatch), save: (id, color) => persistEnvironments(withPlaceColor(environmentsState, id, color)),- rail: { owns: event => chromeRail.owns(event), places: railList, saved: id => savedPlace(environmentsState, id) } });+ rail: { owns: event => chromeRail.owns(event), places: railList, saved: id => savedPlace(environmentsState, id) }, t: nativeT });ipcMain.handle("sharing:state", localWorkspaceOnly("sharing:state", async (_event, id) => {await requireSharedComputers();return sharingController().state(savedWorkspace(id).id);@@ -2735,7 +2735,7 @@ ipcMain.handle("sharing:save", localWorkspaceOnly("sharing:save", async (_event,return sharingController().save(env, grant, info);}));-const cloudSync = installCloudFiles({+const cloudSync = installCloudFiles({ t: nativeT,app, ipcMain, dialog, shell, powerMonitor, localWorkspaceOnly, localDataDir: desktopDataDir(),fetch: (...args) => session.defaultSession.fetch(...args),send: (channel, value) => { if (mainWindow && !mainWindow.isDestroyed()) mainWindow.webContents.send(channel, value); },@@ -2934,7 +2934,7 @@ app.whenReady().then(async () => {if (app.isPackaged) {try {// Acquire before either plaintext credential migration touches config.json.- desktopDataDirLease = acquireDataDirLease(bootDataDir, {+ desktopDataDirLease = acquireDataDirLease(bootDataDir, { t: nativeT,legacyDataDir: path.join(app.getPath("home"), ".opengrokbot"),});runningDataDir = bootDataDir;@@ -3031,7 +3031,7 @@ app.whenReady().then(async () => {for (const win of appWindows()) if (!win.isDestroyed() && win.webContents !== sender) win.webContents.send("desktop-language:changed", language);chromeRail.send("desktop-language:changed", language);},- onLanguage: language => { if (nativeText.set(language)) applyNativeLanguage(); },+ onLanguage: language => { if (nativeText.set(language)) { applyNativeLanguage(); talk.relabel(); } },page: event => senderIsLocal(event) ? "local" : cloudPageAsking(event) ?? (workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin()) ? "server" : null) });talk.start({ globalShortcut, screen, prefs: desktopPrefs, remote: () => Boolean(desktopRemoteAccess), away: () => homeWindow.current().kind !== "computer", starting: () => !serverReady, localRequest: localServerRequest, dataDir: () => runningDataDir });// Before the window, so the harness has the CUA descriptor on first render.@@ -3068,7 +3068,7 @@ app.whenReady().then(async () => {}desktopDataDirLease = null;try {- desktopDataDirLease = acquireDataDirLease(desktopDataDir(), {+ desktopDataDirLease = acquireDataDirLease(desktopDataDir(), { t: nativeT,legacyDataDir: path.join(app.getPath("home"), ".opengrokbot"),});runningDataDir = desktopDataDir();diff --git a/electron/native-language.node-test.mjs b/electron/native-language.node-test.mjsindex c3f72fe3bc..08dd9c3874 100644--- a/electron/native-language.node-test.mjs+++ b/electron/native-language.node-test.mjs@@ -62,6 +62,6 @@ test("a new language redraws main's menu, both trays, the window title and the bassert.deepEqual(calls, [["menu", "Servidor"], ["title", "OpenMausBot — Hospedado: Office (office.example.test)"], ["badge", "Nenhuma conversa não lida"]]);const said = (tray) => tray.menu.filter((item) => item.label).map((item) => item.label);assert.deepEqual(said(trays[0]), ["Abrir o OpenMaus Bot", "Sair do OpenMaus Bot"]);- assert.deepEqual(said(trays[1]), ["My Cloud com acesso a este PC", "Pause", "See activity"]);+ assert.deepEqual(said(trays[1]), ["My Cloud com acesso a este PC", "Pausar", "Ver atividade"]);assert.equal(trays[1].tip, "OpenMausBot: My Cloud com acesso a este PC");});diff --git a/electron/place-look.mjs b/electron/place-look.mjsindex e353ab3534..8adb5177b2 100644--- a/electron/place-look.mjs+++ b/electron/place-look.mjs@@ -1,3 +1,4 @@+import nativeText from "./native-text.cjs";// The colour of the place a page shows: drawn faintly at the top of its sidebar and on its circle in the rail, and// changed from its own Settings. A Cloud's colour (My Cloud, another of the person's own, a team's) is the Admin's, so// every app of theirs follows it: its owner or its team's Super admin and Admins change it there; everyone else sees it.@@ -77,13 +78,13 @@ export function pageLook(look) {* rail, which changes the colour of any place it lists with a colour to show (`workspaces:recolor`, its circle's id and* a swatch): `owns(event)` its page asks, `places()` railPlaces' list now, `saved(id)` that place (This computer's too).*/-export function installPlaceLook({ ipcMain, guard, place, session, setColor, save, rail = null }) {+export function installPlaceLook({ ipcMain, guard, place, session, setColor, save, rail = null, t = nativeText.englishText.t }) {const look = () => placeLook(place(), session());/** `entry`'s place (none: a server of theirs only the Admin lists) takes `swatch`; `now()` is its look at each step. */const recolor = async (entry, now, swatch) => {- if (!(swatch === null || CLOUD_SWATCHES.includes(swatch))) throw new Error("Choose one of the colors.");+ if (!(swatch === null || CLOUD_SWATCHES.includes(swatch))) throw new Error(t("native.places.chooseColor"));const current = now();- if (!current) throw new Error("This place has no color to change.");+ if (!current) throw new Error(t("native.places.noColor"));if (!current.change) return { outcome: "refused", look: pageLook(current) };if (current.change === "admin") {const result = await setColor(current.cloudId, swatch);@@ -96,7 +97,7 @@ export function installPlaceLook({ ipcMain, guard, place, session, setColor, savipcMain.handle("workspaces:color", guard((_event, swatch) => recolor(place(), look, swatch)));if (rail) ipcMain.handle("workspaces:recolor", (event, id, swatch) => {if (!rail.owns(event)) throw new Error("workspaces:recolor is only available to the window's rail");- if (!rail.places().some(listed => listed.id === id && listed.paint)) return Promise.reject(new Error("That place isn't here any more."));+ if (!rail.places().some(listed => listed.id === id && listed.paint)) return Promise.reject(new Error(t("native.places.noLongerHere")));const entry = rail.saved(id);const now = () => (entry ? placeLook(rail.saved(id) ?? entry, session()): listedLook(session().clouds?.find(cloud => `${SIGNED_IN}${cloud.id}` === id && cloud.managed === false) ?? null));diff --git a/electron/place-look.node-test.mjs b/electron/place-look.node-test.mjsindex d15f58eb02..07d835a713 100644--- a/electron/place-look.node-test.mjs+++ b/electron/place-look.node-test.mjs@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";import vm from "node:vm";+import nativeText from "./native-text.cjs";import { listedColors, parseCloudList } from "./cloud-list.mjs";import environments from "./environments.cjs";@@ -94,7 +95,7 @@ test("main's own wiring: This computer's page reads and changes its own colour,const start = source.indexOf("installPlaceLook({ ipcMain, guard: workspaceOnly"), end = source.indexOf('ipcMain.handle("sharing:state"', start);assert.ok(start >= 0 && end > start, "main installs the colour's channels");const handlers = new Map(), persisted = [];- const context = vm.createContext({ installPlaceLook, savedPlace: environments.savedPlace, withPlaceColor: environments.withPlaceColor,+ const context = vm.createContext({ installPlaceLook, nativeT: nativeText.englishText.t, savedPlace: environments.savedPlace, withPlaceColor: environments.withPlaceColor,ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, workspaceOnly: handler => handler,environmentsState: { environments: [typed], activeId: "local" }, desktopRemoteAccess: null, cloudAccount: null, myCloud: () => null,ensureCloudAccount: () => { throw new Error("This computer's colour never asks the Admin"); },diff --git a/electron/talk-main.mjs b/electron/talk-main.mjsindex d3050c9340..e03e574b40 100644--- a/electron/talk-main.mjs+++ b/electron/talk-main.mjs@@ -1,3 +1,4 @@+import nativeText from "./native-text.cjs";import skins from "./skin-overlay.cjs";import { createTalkPanel } from "./talk-panel.mjs";import { createTalkServer } from "./talk-server.mjs";@@ -11,7 +12,7 @@ export { isTalkPanel } from "./talk-panel.mjs";* is ready. `speech`: speech.mjs's start/stop/finish/busy. `packaged`: asks go to `localRequest`, this computer's own* server; in development to `devUrl`, whose Vite /api proxy reaches `pnpm dev:server`.*/-export function installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech, speech, packaged, devUrl, nativeImage, iconPath, openLink, reveal, log, fetch = globalThis.fetch }) {+export function installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech, speech, packaged, devUrl, nativeImage, iconPath, openLink, reveal, log, fetch = globalThis.fetch, t = nativeText.englishText.t }) {const callPresence = createCallPresence();let shortcut = null, session = null, panel = null, theme = null;@@ -51,7 +52,7 @@ export function installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, apstart({ globalShortcut, screen, prefs, remote, away, starting, localRequest, dataDir }) {const request = (route, init) => (packaged ? localRequest(route, init) : fetch(new URL(route, devUrl), init));try {- panel = createTalkPanel({ BrowserWindow, screen, nativeImage, iconPath, theme, onOpen: logged("open", () => session.open()), onDismiss: logged("dismiss", () => session.dismiss()) });+ panel = createTalkPanel({ t, BrowserWindow, screen, nativeImage, iconPath, theme, onOpen: logged("open", () => session.open()), onDismiss: logged("dismiss", () => session.dismiss()) });session = createTalkSession({speech,server: createTalkServer({ request, prefs, starting, serverKey: () => (packaged ? dataDir() : devUrl) ?? "local" }),@@ -76,6 +77,7 @@ export function installTalk({ ipcMain, localOnly, localOrHome, BrowserWindow, ap},/** Listening, or an ask on its way that has not been answered yet. */busy: () => session?.busy() ?? false,+ relabel: () => panel?.relabel(),close() {logged("close", () => session?.close())();logged("close", () => shortcut?.close())();diff --git a/electron/talk-main.node-test.mjs b/electron/talk-main.node-test.mjsindex 5bd0af37ca..0c8f25fdc7 100644--- a/electron/talk-main.node-test.mjs+++ b/electron/talk-main.node-test.mjs@@ -6,6 +6,7 @@ import test from "node:test";import assert from "node:assert/strict";import { createDesktopPrefs } from "./desktop-prefs.mjs";import { installTalk, isTalkPanel } from "./talk-main.mjs";+import { TALK_LABELS } from "./talk-panel.mjs";import { TALK_SHORTCUT_UNAVAILABLE } from "./talk-shortcut.mjs";const here = dirname(fileURLToPath(import.meta.url));@@ -14,6 +15,7 @@ const preload = readFileSync(join(here, "preload.cjs"), "utf8");const settle = async () => { for (let i = 0; i < 10; i += 1) await new Promise(resolve => setImmediate(resolve)); };const json = body => Promise.resolve(new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }));const names = windows => windows.map(win => win?.name ?? null);+const englishLabels = { labels: TALK_LABELS, dismiss: "Dismiss", release: "Let go to send" };function harness({ packaged = true, appleSpeech = true, remote = false, register, serve = () => undefined } = {}) {const h = { handlers: new Map(), guards: new Map(), started: [], stopped: [], finished: [], requests: [], links: [], reveals: 0, log: [],@@ -85,7 +87,7 @@ test("every list of the app's windows leaves the talk box out", () => {test("main hands the talk wiring its speech sinks, this computer's own server and window, and closes it first on quit", () => {assert.match(main, /const talk = installTalk\(\{ ipcMain, localOnly, localOrHome, BrowserWindow, appleSpeech: nativeActions\.appleSpeech,\s*speech: \{ start: startSpeech, stop: stopSpeech, finish: finishSpeech, busy: speechBusy \},/);- assert.match(main, /packaged: app\.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog \}\);/);+ assert.match(main, /packaged: app\.isPackaged, devUrl: DEV_URL, nativeImage, iconPath: APP_ICON, openLink: queueChatLink, reveal: revealForLink, log: slog, t: nativeT \}\);/);assert.match(main, /talk\.start\(\{ globalShortcut, screen, prefs: desktopPrefs, remote: \(\) => Boolean\(desktopRemoteAccess\), away: \(\) => homeWindow\.current\(\)\.kind !== "computer", starting: \(\) => !serverReady, localRequest: localServerRequest, dataDir: \(\) => runningDataDir \}\);/);assert.match(main, /app\.on\("before-quit", \(e\) => \{\s*talk\.close\(\);/);assert.doesNotMatch(main, /ipcMain\.handle\("(?:speech|talk-shortcut|call):/);@@ -274,7 +276,7 @@ test("a press while this computer's server is still starting says so", async ()h.start();h.press();await settle();- assert.deepEqual((await h.painted()).at(-1), { state: "error", text: "MausBot is still starting. Try again in a moment." });+ assert.deepEqual((await h.painted()).at(-1), { state: "error", text: "MausBot is still starting. Try again in a moment.", ...englishLabels });h.talk.close();});@@ -283,10 +285,10 @@ test("the box takes the light or dark of the skin the app painted last, before oh.talk.skin("meadow");h.start();h.press();- assert.deepEqual((await h.painted()).at(-1), { state: "listening", text: "", theme: "light" });+ assert.deepEqual((await h.painted()).at(-1), { state: "listening", text: "", theme: "light", ...englishLabels });h.talk.skin("midnight");await settle();- assert.deepEqual((await h.painted()).at(-1), { state: "listening", text: "", theme: "dark" });+ assert.deepEqual((await h.painted()).at(-1), { state: "listening", text: "", theme: "dark", ...englishLabels });h.talk.skin("no-such-skin");h.talk.skin(undefined);await settle();diff --git a/electron/talk-panel.mjs b/electron/talk-panel.mjsindex 469aa083c8..86e4d5def4 100644--- a/electron/talk-panel.mjs+++ b/electron/talk-panel.mjs@@ -1,3 +1,4 @@+import nativeText from "./native-text.cjs";import { fileURLToPath } from "node:url";export const TALK_PANEL = Object.freeze({ width: 400, margin: 24, minHeight: 56, maxHeight: 240, fadeMs: 180 });@@ -76,8 +77,9 @@ const LABELS=${labels};const card=document.getElementById("card"),label=document.getElementById("label"),text=document.getElementById("text");function render(view){document.body.className=["on",view.state,view.theme].filter(Boolean).join(" ");- label.textContent=LABELS[view.state]||"";- text.textContent=view.text||(view.state==="listening"?"Let go to send":"");+ label.textContent=(view.labels||LABELS)[view.state]||"";+ document.getElementById("close").setAttribute("aria-label",view.dismiss||"Dismiss");+ text.textContent=view.text||(view.state==="listening"?(view.release||"Let go to send"):"");return Math.ceil(card.getBoundingClientRect().height);}function fadeOut(){document.body.classList.remove("on")}@@ -93,7 +95,7 @@ function mascotPng(nativeImage, iconPath) {return icon.resize({ width: 2 * MASCOT_PX, height: 2 * MASCOT_PX, quality: "best" }).toPNG().toString("base64");}-export function createTalkPanel({ BrowserWindow, screen, nativeImage, iconPath, onOpen, onDismiss, theme: initialTheme = null }) {+export function createTalkPanel({ BrowserWindow, screen, nativeImage, iconPath, onOpen, onDismiss, theme: initialTheme = null, t = nativeText.englishText.t }) {let win = null;let loaded = false;let shown = false;@@ -161,7 +163,8 @@ export function createTalkPanel({ BrowserWindow, screen, nativeImage, iconPath,async function paint() {const target = win;const ticket = ++latest;- const payload = JSON.stringify({ state: view.state, text: replyPreview(view.text), ...(theme ? { theme } : {}) });+ const labels = { ...TALK_LABELS, listening: t("native.talk.listening"), sending: t("native.talk.sending"), thinking: t("native.talk.thinking"), "needs-you": t("native.talk.needsYou"), "still-working": t("native.talk.stillWorking") };+ const payload = JSON.stringify({ state: view.state, text: view.textCode ? t(view.textCode) : replyPreview(view.text), labels, dismiss: t("native.talk.dismiss"), release: t("native.talk.releaseToSend"), ...(theme ? { theme } : {}) });let height;try {height = await target.webContents.executeJavaScript(`render(${payload})`);@@ -179,6 +182,7 @@ export function createTalkPanel({ BrowserWindow, screen, nativeImage, iconPath,const repaint = () => void paint().catch(() => {});return {+ relabel() { if (win && loaded && view) repaint(); },render(next) {view = next;if (!win) {diff --git a/electron/talk-panel.node-test.mjs b/electron/talk-panel.node-test.mjsindex 10c8f1172c..06bd74c659 100644--- a/electron/talk-panel.node-test.mjs+++ b/electron/talk-panel.node-test.mjs@@ -3,14 +3,17 @@ import { EventEmitter } from "node:events";import { existsSync, readFileSync } from "node:fs";import test, { mock } from "node:test";import { fileURLToPath } from "node:url";+import nativeText from "./native-text.cjs";import { TALK_LABELS, TALK_PANEL, createTalkPanel, isTalkPanel, replyPreview, talkPanelBounds, talkPanelHtml } from "./talk-panel.mjs";const flush = () => new Promise(resolve => setImmediate(resolve));const pick = (object, keys) => Object.fromEntries(keys.map(key => [key, object[key]]));+const painted = win => JSON.parse(win.webContents.scripts.at(-1).slice(7, -1));+const englishLabels = { labels: TALK_LABELS, dismiss: "Dismiss", release: "Let go to send" };const APP_ICON = fileURLToPath(new URL("./resources/app-icon.png", import.meta.url));-function harness({ cursor = { x: 100, y: 100 }, workArea = { x: 0, y: 25, width: 1440, height: 875 }, loadFails = false, boundsFail = false, iconPath = APP_ICON, theme } = {}) {+function harness({ cursor = { x: 100, y: 100 }, workArea = { x: 0, y: 25, width: 1440, height: 875 }, loadFails = false, boundsFail = false, iconPath = APP_ICON, theme, t } = {}) {const made = [];const resized = [];const nativeImage = {@@ -50,7 +53,7 @@ function harness({ cursor = { x: 100, y: 100 }, workArea = { x: 0, y: 25, width:const screen = { getCursorScreenPoint: () => state.cursor, getDisplayNearestPoint: () => ({ workArea: state.workArea }) };const opened = [];const dismissed = [];- const panel = createTalkPanel({ BrowserWindow: FakeBrowserWindow, screen, nativeImage, iconPath, onOpen: () => opened.push(1), onDismiss: () => dismissed.push(1), theme });+ const panel = createTalkPanel({ BrowserWindow: FakeBrowserWindow, screen, nativeImage, iconPath, onOpen: () => opened.push(1), onDismiss: () => dismissed.push(1), theme, t });return { panel, made, opened, dismissed, state, resized };}@@ -78,7 +81,7 @@ test("the box is a non-activating panel on every Space, shown without focus on tassert.ok(win.url.startsWith("data:text/html"));win.webContents.emit("did-finish-load");await flush();- assert.match(win.webContents.scripts[0], /^render\(\{"state":"listening","text":""\}\)$/);+ assert.deepEqual(painted(win), { state: "listening", text: "", ...englishLabels });assert.deepEqual(win.bounds, { x: 1960, y: 780, width: 400, height: 96 });assert.deepEqual(win.calls.map(c => c[0]).filter(n => ["show", "focus", "showInactive"].includes(n)), ["showInactive"]);});@@ -93,7 +96,7 @@ test("later renders resize without showing again, and use only the latest view",assert.match(made[0].webContents.scripts[0], /"state":"thinking"/);panel.render({ state: "reply", text: "**Hi** there" });await flush();- assert.match(made[0].webContents.scripts[1], /^render\(\{"state":"reply","text":"Hi there"\}\)$/);+ assert.deepEqual(painted(made[0]), { state: "reply", text: "Hi there", ...englishLabels });assert.deepEqual(made[0].calls.filter(c => c[0] === "showInactive").length, 1);});@@ -260,10 +263,10 @@ test("the box takes the app's skin, light or dark, over macOS's appearance, andpanel.render({ state: "reply", text: "Hi" });made[0].webContents.emit("did-finish-load");await flush();- assert.equal(made[0].webContents.scripts.at(-1), 'render({"state":"reply","text":"Hi","theme":"light"})');+ assert.deepEqual(painted(made[0]), { state: "reply", text: "Hi", ...englishLabels, theme: "light" });panel.setTheme("dark");await flush();- assert.equal(made[0].webContents.scripts.at(-1), 'render({"state":"reply","text":"Hi","theme":"dark"})');+ assert.deepEqual(painted(made[0]), { state: "reply", text: "Hi", ...englishLabels, theme: "dark" });panel.setTheme("dark");await flush();assert.equal(made[0].webContents.scripts.length, 2, "the same skin again repaints nothing");@@ -295,3 +298,31 @@ test("a box that fails to place itself is not an unhandled rejection", async ()process.off("unhandledRejection", record);}});+++test("an open box follows the current language without translating a reply or caching labels in its page", async () => {+ const text = nativeText.createNativeText({ saved: "en" });+ const { panel, made } = harness({ t: text.t });+ panel.render({ state: "error", text: "Turn on Dictation in System Settings → Keyboard, then try again.", textCode: "native.talk.dictationOff" });+ made[0].webContents.emit("did-finish-load");+ await flush();+ assert.equal(painted(made[0]).text, "Turn on Dictation in System Settings → Keyboard, then try again.");+ const page = made[0].url;+ text.set("pt-br");+ panel.relabel();+ await flush();+ assert.equal(painted(made[0]).text, text.t("native.talk.dictationOff"));+ assert.equal(painted(made[0]).labels.listening, "Ouvindo…");+ assert.equal(painted(made[0]).labels.reply, "MausBot");+ assert.equal(painted(made[0]).dismiss, "Fechar");+ assert.equal(painted(made[0]).release, text.t("native.talk.releaseToSend"));+ panel.render({ state: "reply", text: "Turn on Dictation in System Settings → Keyboard, then try again." });+ await flush();+ assert.equal(painted(made[0]).text, "Turn on Dictation in System Settings → Keyboard, then try again.");+ text.set("en");+ panel.relabel();+ await flush();+ assert.deepEqual(painted(made[0]).labels, TALK_LABELS);+ assert.equal(made.length, 1);+ assert.equal(made[0].url, page);+});diff --git a/electron/talk-session.mjs b/electron/talk-session.mjsindex 87100a2832..228366ff5a 100644--- a/electron/talk-session.mjs+++ b/electron/talk-session.mjs@@ -32,6 +32,9 @@ const SERVER_NOTICES = new Map([["moved", TALK_TEXT.moved],]);+const SERVER_NOTICE_KEYS = new Map([["server-down", "native.talk.openMausBot"], ["starting", "native.talk.starting"], ["no-mausbot", "native.talk.setUpFirst"], ["moved", "native.talk.movedToCloud"]]);+const SPEECH_KEYS = new Map([["speech-not-authorized", "native.talk.permissions"], ["mic-failed", "native.talk.unavailable"], ["recognizer-unavailable", "native.talk.unavailable"], ["dictation-disabled", "native.talk.dictationOff"], ["helper-build-failed", "native.talk.unavailable"], ["helper-start-failed", "native.talk.unavailable"], ["unsupported-platform", "native.talk.unavailable"]]);+const UNDER_WAY = new Set(["listening", "sending", "thinking"]);export function createTalkSession({ speech, server, panel, voiceInUse, release, openChat, newSendId = randomUUID }) {@@ -45,10 +48,10 @@ export function createTalkSession({ speech, server, panel, voiceInUse, release,return ask;}- function show(ask, state, text) {+ function show(ask, state, text, textCode) {ask.state = state;try {- panel.render({ state, text });+ panel.render({ state, text, ...(textCode ? { textCode } : {}) });} catch {}}@@ -87,9 +90,9 @@ export function createTalkSession({ speech, server, panel, voiceInUse, release,ask.hideTimer = setTimeout(check, ms);}- function settle(ask, state, text, hideMs) {+ function settle(ask, state, text, hideMs, textCode) {clearTimeout(ask.answerTimer);- show(ask, state, text);+ show(ask, state, text, textCode);hideIn(ask, hideMs);}@@ -101,8 +104,8 @@ export function createTalkSession({ speech, server, panel, voiceInUse, release,function failed(ask, error) {const code = error instanceof TalkServerError ? error.code : null;if (code === "lost") stillWorking(ask);- else if (SERVER_NOTICES.has(code)) settle(ask, "error", SERVER_NOTICES.get(code), TALK_TIMING.noticeHideMs);- else settle(ask, "error", TALK_TEXT.failed, TALK_TIMING.replyHideMs);+ else if (SERVER_NOTICES.has(code)) settle(ask, "error", SERVER_NOTICES.get(code), TALK_TIMING.noticeHideMs, SERVER_NOTICE_KEYS.get(code));+ else settle(ask, "error", TALK_TEXT.failed, TALK_TIMING.replyHideMs, "native.talk.failed");}function follow(ask, update) {@@ -118,7 +121,7 @@ export function createTalkSession({ speech, server, panel, voiceInUse, release,if (!live(ask)) return;if (outcome === "done") settle(ask, "reply", ask.reply, TALK_TIMING.replyHideMs);else if (outcome === "needs-you") settle(ask, "needs-you", ask.reply, TALK_TIMING.replyHideMs);- else settle(ask, "error", TALK_TEXT.failed, TALK_TIMING.replyHideMs);+ else settle(ask, "error", TALK_TEXT.failed, TALK_TIMING.replyHideMs, "native.talk.failed");}function send(ask, prepared) {@@ -153,7 +156,7 @@ export function createTalkSession({ speech, server, panel, voiceInUse, release,end(info) {if (!listening()) return;const problem = SPEECH_PROBLEMS.get(info?.reason);- if (problem) settle(ask, "error", problem, TALK_TIMING.noticeHideMs);+ if (problem) settle(ask, "error", problem, TALK_TIMING.noticeHideMs, SPEECH_KEYS.get(info?.reason));else if (!ask.words.trim()) closeBox(ask);else send(ask, prepared);},@@ -168,7 +171,7 @@ export function createTalkSession({ speech, server, panel, voiceInUse, release,} catch {if (!listening()) return;speech.stop(ask.sink);- settle(ask, "error", TALK_TEXT.unavailable, TALK_TIMING.noticeHideMs);+ settle(ask, "error", TALK_TEXT.unavailable, TALK_TIMING.noticeHideMs, "native.talk.unavailable");return;}ask.listenTimer = setTimeout(() => { if (listening()) speech.finish(ask.sink); }, TALK_TIMING.maxListenMs);@@ -180,7 +183,7 @@ export function createTalkSession({ speech, server, panel, voiceInUse, release,press() {if (current && UNDER_WAY.has(current.state)) return;dismiss();- if (voiceInUse()) settle(begin("error"), "error", TALK_TEXT.busy, TALK_TIMING.noticeHideMs);+ if (voiceInUse()) settle(begin("error"), "error", TALK_TEXT.busy, TALK_TIMING.noticeHideMs, "native.talk.voiceBusy");else listen();},open() {diff --git a/electron/talk-session.node-test.mjs b/electron/talk-session.node-test.mjsindex 01a7165dad..b231bfdb19 100644--- a/electron/talk-session.node-test.mjs+++ b/electron/talk-session.node-test.mjs@@ -135,7 +135,7 @@ test("voice in use refuses without listening", () => {const h = harness({ busy: true }); h.session.press();assert.deepEqual(h.starts, []);assert.equal(h.prepares, 0);- assert.deepEqual(h.views, [{ state: "error", text: "Voice is in use in MausBot" }]);+ assert.deepEqual(h.views, [{ state: "error", text: "Voice is in use in MausBot", textCode: "native.talk.voiceBusy" }]);mock.timers.tick(3_999); assert.equal(h.closed, 0);mock.timers.tick(1); assert.equal(h.closed, 1);});@@ -162,17 +162,17 @@ test("words heard before a recognizer error are still sent", async () => {test("permission and setup problems say what to fix, in the composer's words: only a refused permission asks for access", async () => {const problems = [- ["speech-not-authorized", TALK_TEXT.permission],- ["mic-failed", TALK_TEXT.unavailable],- ["recognizer-unavailable", TALK_TEXT.unavailable],- ["dictation-disabled", TALK_TEXT.dictationOff],- ["helper-build-failed", TALK_TEXT.unavailable],- ["helper-start-failed", TALK_TEXT.unavailable],- ["unsupported-platform", TALK_TEXT.unavailable],+ ["speech-not-authorized", TALK_TEXT.permission, "native.talk.permissions"],+ ["mic-failed", TALK_TEXT.unavailable, "native.talk.unavailable"],+ ["recognizer-unavailable", TALK_TEXT.unavailable, "native.talk.unavailable"],+ ["dictation-disabled", TALK_TEXT.dictationOff, "native.talk.dictationOff"],+ ["helper-build-failed", TALK_TEXT.unavailable, "native.talk.unavailable"],+ ["helper-start-failed", TALK_TEXT.unavailable, "native.talk.unavailable"],+ ["unsupported-platform", TALK_TEXT.unavailable, "native.talk.unavailable"],];- for (const [reason, text] of problems) {+ for (const [reason, text, textCode] of problems) {const h = harness(); h.session.press(); release(h, { code: 1, reason }); await flush();- assert.deepEqual(h.views.at(-1), { state: "error", text }, reason);+ assert.deepEqual(h.views.at(-1), { state: "error", text, textCode }, reason);assert.equal(h.asks.length, 0, reason);mock.timers.tick(3_999); assert.equal(h.closed, 0, reason);mock.timers.tick(1); assert.equal(h.closed, 1, reason);@@ -181,19 +181,19 @@ test("permission and setup problems say what to fix, in the composer's words: ontest("a server that can't take asks says why and stops listening: down, still starting, no MausBot, or moved to My Cloud", async () => {const notices = [- ["server-down", "Open MausBot to talk"],- ["starting", TALK_TEXT.starting],- ["no-mausbot", TALK_TEXT.noMausbot],- ["moved", "MausBot lives on My Cloud now — talk to it there"],+ ["server-down", "Open MausBot to talk", "native.talk.openMausBot"],+ ["starting", TALK_TEXT.starting, "native.talk.starting"],+ ["no-mausbot", TALK_TEXT.noMausbot, "native.talk.setUpFirst"],+ ["moved", "MausBot lives on My Cloud now — talk to it there", "native.talk.movedToCloud"],];- for (const [code, text] of notices) {+ for (const [code, text, textCode] of notices) {const h = harness({ prepare: async () => { throw new TalkServerError(code); } });h.session.press(); await flush();assert.deepEqual(h.stops, [true], code);- assert.deepEqual(h.views.at(-1), { state: "error", text }, code);+ assert.deepEqual(h.views.at(-1), { state: "error", text, textCode }, code);say(h, "too late"); release(h); await flush();assert.equal(h.asks.length, 0, code);- assert.deepEqual(h.views.at(-1), { state: "error", text }, code);+ assert.deepEqual(h.views.at(-1), { state: "error", text, textCode }, code);mock.timers.tick(3_999); assert.equal(h.closed, 0, code);mock.timers.tick(1); assert.equal(h.closed, 1, code);}@@ -207,17 +207,17 @@ test("a server that goes away as the words are sent says Open MausBot to talk",fail(new TalkServerError("server-down")); await flush();assert.deepEqual(late.stops, []);assert.equal(late.asks.length, 0);- assert.deepEqual(late.views.at(-1), { state: "error", text: TALK_TEXT.serverDown });+ assert.deepEqual(late.views.at(-1), { state: "error", text: TALK_TEXT.serverDown, textCode: "native.talk.openMausBot" });mock.timers.tick(TALK_TIMING.noticeHideMs); assert.equal(late.closed, 1);const gone = harness({ ask: async () => { throw new TalkServerError("server-down"); } });gone.session.press(); say(gone, "hello"); release(gone); await flush();- assert.deepEqual(gone.views.at(-1), { state: "error", text: TALK_TEXT.serverDown });+ assert.deepEqual(gone.views.at(-1), { state: "error", text: TALK_TEXT.serverDown, textCode: "native.talk.openMausBot" });mock.timers.tick(TALK_TIMING.noticeHideMs); assert.equal(gone.closed, 1);const moved = harness({ ask: async () => { throw new TalkServerError("moved"); } });moved.session.press(); say(moved, "hello"); release(moved); await flush();- assert.deepEqual(moved.views.at(-1), { state: "error", text: TALK_TEXT.moved });+ assert.deepEqual(moved.views.at(-1), { state: "error", text: TALK_TEXT.moved, textCode: "native.talk.movedToCloud" });mock.timers.tick(TALK_TIMING.noticeHideMs); assert.equal(moved.closed, 1);});@@ -281,7 +281,7 @@ test("a lost stream shows Still working; a refused send shows the failure", asynconst refused = harness({ ask: async () => { throw new TalkServerError("refused"); } });refused.session.press(); say(refused, "summarise my inbox"); release(refused); await flush();- assert.deepEqual(refused.views.at(-1), { state: "error", text: TALK_TEXT.failed });+ assert.deepEqual(refused.views.at(-1), { state: "error", text: TALK_TEXT.failed, textCode: "native.talk.failed" });mock.timers.tick(11_999); assert.equal(refused.closed, 0);mock.timers.tick(1); assert.equal(refused.closed, 1);});@@ -289,7 +289,7 @@ test("a lost stream shows Still working; a refused send shows the failure", asyntest("a turn that fails shows the failure", async () => {const h = harness({ ask: async input => { input.onUpdate({ kind: "thinking" }); input.onUpdate({ kind: "done", ok: false, text: "" }); return "failed"; } });h.session.press(); say(h, "summarise my inbox"); release(h); await flush();- assert.deepEqual(h.views.at(-1), { state: "error", text: TALK_TEXT.failed });+ assert.deepEqual(h.views.at(-1), { state: "error", text: TALK_TEXT.failed, textCode: "native.talk.failed" });mock.timers.tick(11_999); assert.equal(h.closed, 0);mock.timers.tick(1); assert.equal(h.closed, 1);});@@ -445,7 +445,7 @@ test("speech that fails to start says Talking couldn't start, and a later pressconst h = harness();h.startFails = true;assert.doesNotThrow(() => h.session.press());- assert.deepEqual(h.views.at(-1), { state: "error", text: TALK_TEXT.unavailable });+ assert.deepEqual(h.views.at(-1), { state: "error", text: TALK_TEXT.unavailable, textCode: "native.talk.unavailable" });assert.deepEqual(h.stops, [true]);mock.timers.tick(3_999); assert.equal(h.closed, 0);mock.timers.tick(1); assert.equal(h.closed, 1);@@ -460,7 +460,7 @@ test("speech that fails to start says Talking couldn't start, and a later presskeyless.releaseFails = true;assert.doesNotThrow(() => keyless.session.press());assert.deepEqual(keyless.starts, []);- assert.deepEqual(keyless.views.at(-1), { state: "error", text: TALK_TEXT.unavailable });+ assert.deepEqual(keyless.views.at(-1), { state: "error", text: TALK_TEXT.unavailable, textCode: "native.talk.unavailable" });keyless.releaseFails = false;keyless.session.press();assert.equal(keyless.starts.length, 1);diff --git a/server/activity.test.ts b/server/activity.test.tsindex d0cecedea3..254e616448 100644--- a/server/activity.test.ts+++ b/server/activity.test.ts@@ -72,12 +72,7 @@ describe("describeTool", () => {...["screenshot", "get_screen_size", "click", "move", "drag", "type_text", "key_press", "scroll", "open_url", "exec", "computer_exec", "wait_for"].map((tool) => `mcp__computer__${tool}`),];const calls = ["apollo.people.search", "crunchbase.companies.lookup", "x.funding.rounds", "newsapi.news.everything", "tikhub.tiktok.user", "g.trends.daily", "serp.google.search", "moz.seo.backlinks", "fal.images.generate", "anyapi.x.search", "people.vendor.thing"];- const untranslated = new Map([- ["mcp__agents__delete_trigger", "Delete trigger"], ["mcp__agents__wait_until", "Wait until"],- ["mcp__agents__list_waits", "List waits"], ["mcp__agents__cancel_wait", "Cancel wait"],- ]);- for (const [name, label] of untranslated) expect(describedTool(name)).toEqual({ app: "Team", appKey: "activity.app.team", label });- const rows = [...named.filter((name) => !untranslated.has(name)).map((name) => describedTool(name)), ...calls.map((id) => describedTool("mcp__agents__research_call", { id }))];+ const rows = [...named.map((name) => describedTool(name)), ...calls.map((id) => describedTool("mcp__agents__research_call", { id }))];for (const row of rows) {expect(row.labelKey, row.label).toMatch(/^activity\.tool\./);expect(en[row.labelKey!], row.labelKey).toBe(row.label);@@ -93,6 +88,10 @@ describe("describeTool", () => {["extract", "Extract", "activity.tool.team.extract"],["message_person", "Message person", "activity.tool.team.messagePerson"],["report_bug", "Report bug", "activity.tool.team.reportBug"],+ ["delete_trigger", "Delete trigger", "activity.tool.team.deleteTrigger"],+ ["wait_until", "Wait until", "activity.tool.team.waitUntil"],+ ["list_waits", "List waits", "activity.tool.team.listWaits"],+ ["cancel_wait", "Cancel wait", "activity.tool.team.cancelWait"],])("names %s with its own activity key and unchanged English", (tool, label, labelKey) => {expect(describedTool(`mcp__agents__${tool}`)).toEqual({ app: "Team", appKey: "activity.app.team", label, labelKey });expect(describeTool(`mcp__agents__${tool}`)).toEqual({ app: "Team", label });diff --git a/server/activity.ts b/server/activity.tsindex bfbc32c768..a048f7ee85 100644--- a/server/activity.ts+++ b/server/activity.ts@@ -76,6 +76,10 @@ const RESEARCH_TOOL_LABELS: Record<string, Described> = {};const TEAM_ACTION_KEYS: Record<string, string> = {+ cancel_wait: "activity.tool.team.cancelWait",+ delete_trigger: "activity.tool.team.deleteTrigger",+ list_waits: "activity.tool.team.listWaits",+ wait_until: "activity.tool.team.waitUntil",add_mcp_server: "activity.tool.team.addMcpServer",ask_bot: "activity.tool.team.askBot",assignment_status: "activity.tool.team.assignmentStatus",diff --git a/server/body-deadline.test.ts b/server/body-deadline.test.tsindex d15e11d6c7..81c261581d 100644--- a/server/body-deadline.test.ts+++ b/server/body-deadline.test.ts@@ -40,7 +40,9 @@ describe("holdBodyDeadline", () => {const port = await listen(200);const answer = await send(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Length: 10\r\n\r\nab", []);expect(answer).toMatch(/^HTTP\/1\.1 408 Request Timeout/);- expect(answer).toContain("The request took too long.");+ const [, body] = answer.split("\r\n\r\n");+ expect(JSON.parse(body!)).toEqual({ error: "The request took too long. Check the connection and try again.", errorKey: "serverError.request.bodyTimeout" });+ expect(answer).toContain(`Content-Length: ${Buffer.byteLength(body!)}`);});it("gives a large upload time in proportion to its size", async () => {diff --git a/server/body-deadline.ts b/server/body-deadline.tsindex 22e3f0aab2..775932ab5f 100644--- a/server/body-deadline.ts+++ b/server/body-deadline.ts@@ -1,10 +1,11 @@+import { userError } from "./user-errors.ts";import type { IncomingMessage, ServerResponse } from "node:http";export const BODY_DEADLINE_MS = 55_000;/** The slowest upload still let through: past this pace a large body is cut off, never held open. */const MIN_BODY_BYTES_PER_SECOND = 128 * 1024;const UNKNOWN_LENGTH_BYTES = 32 * 1024 * 1024;-const TIMED_OUT_BODY = JSON.stringify({ error: "The request took too long. Check the connection and try again." });+const TIMED_OUT_BODY = JSON.stringify({ ...userError("serverError.request.bodyTimeout") });const TIMED_OUT = `HTTP/1.1 408 Request Timeout\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(TIMED_OUT_BODY)}\r\n\r\n${TIMED_OUT_BODY}`;/** Ends a request whose body has not all arrived in time, as Node's own `requestTimeout` does: a 408 written on thediff --git a/server/browser-live.test.ts b/server/browser-live.test.tsindex 5d94682e7d..871d12aa81 100644--- a/server/browser-live.test.ts+++ b/server/browser-live.test.ts@@ -1,5 +1,5 @@import { EventEmitter } from "node:events";-import type { ServerResponse } from "node:http";+import { createServer, get, type ServerResponse } from "node:http";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { BrowserRuntime } from "./browser-runtime.ts";import { HOLD_LIMITS } from "./browser/hold.ts";@@ -1170,7 +1170,7 @@ describe("opening a view while the bot holds the browser", () => {const { res, opening } = start();await opening;expect(res.events("waiting")).toHaveLength(0);- expect(res.events("error")).toEqual([{ retryable: true, message: expect.stringMatching(/browser stopped responding/) }]);+ expect(res.events("error")).toEqual([{ retryable: true, message: "The browser stopped responding, so it is being restarted. The live view reconnects by itself.", errorKey: "serverError.browser.restartingUnresponsive" }]);expect(nativeClose).toHaveBeenCalledTimes(1);expect(nativeClose).toHaveBeenCalledWith("/engine", expect.objectContaining({ AGENT_BROWSER_SESSION: "profile-a" }));// The next view waits for that reset, then meets the fresh session.@@ -1180,6 +1180,41 @@ describe("opening a view while the bot holds the browser", () => {expect(nativeClose).toHaveBeenCalledTimes(1);});+ it("carries the restart error code and original English over an isolated HTTP event stream", async () => {+ vi.mocked(runtime.working).mockReturnValue(false);+ execute.mockRejectedValueOnce(busy());+ const server = createServer((_req, res) => {+ void live.open({ botId: "bot-a", session: "profile-a", owner: "admin-a", isCurrent: () => true, res,+ spec: { command: "/engine", env: { AGENT_BROWSER_SESSION: "profile-a" } } })+ .catch(error => res.destroy(error instanceof Error ? error : new Error(String(error))));+ });+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));+ try {+ const address = server.address();+ if (!address || typeof address === "string") throw new Error("The isolated SSE fixture has no TCP address");+ const received = await new Promise<{ status?: number; contentType?: string; body: string }>((resolve, reject) => {+ const request = get(`http://127.0.0.1:${address.port}/`, response => {+ let body = "";+ response.setEncoding("utf8");+ response.on("data", chunk => { body += chunk; });+ response.on("error", reject);+ response.on("end", () => resolve({ status: response.statusCode, contentType: response.headers["content-type"], body }));+ });+ request.on("error", reject);+ request.setTimeout(5_000, () => request.destroy(new Error("The isolated SSE fixture timed out")));+ });+ expect(received).toEqual({ status: 200, contentType: "text/event-stream", body: `event: error\ndata: ${JSON.stringify({+ retryable: true,+ message: "The browser stopped responding, so it is being restarted. The live view reconnects by itself.",+ errorKey: "serverError.browser.restartingUnresponsive",+ })}\n\n` });+ expect(nativeClose).toHaveBeenCalledOnce();+ } finally {+ server.closeAllConnections();+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));+ }+ });+it("keeps waiting, and resets nothing, while a bot call still works in the browser", async () => {vi.useFakeTimers();execute.mockRejectedValueOnce(busy()).mockResolvedValue(output(ready));diff --git a/server/browser-live.ts b/server/browser-live.tsindex 152aca1e3a..04d792456b 100644--- a/server/browser-live.ts+++ b/server/browser-live.ts@@ -1,3 +1,4 @@+import { userError, userErrorFields } from "./user-errors.ts";import { execFile } from "node:child_process";import { randomUUID } from "node:crypto";import type { ServerResponse } from "node:http";@@ -61,7 +62,7 @@ export class BrowserBusyError extends BrowserLiveError {/** The engine left a status read unanswered with no bot or person working in it: it hung, and its session is being reset. */class BrowserUnresponsiveError extends BrowserLiveError {- constructor() { super("The browser stopped responding, so it is being restarted. The live view reconnects by itself.", 503); this.name = "BrowserUnresponsiveError"; }+ constructor() { super("The browser stopped responding, so it is being restarted. The live view reconnects by itself.", 503); this.name = "BrowserUnresponsiveError"; Object.assign(this, userErrorFields(userError("serverError.browser.restartingUnresponsive"))); }}/** A person's input or command went unanswered, but the engine answered a read queued behind it, so it has ended. */@@ -839,7 +840,7 @@ export class BrowserLive {if (options.res.headersSent) {const busy = error instanceof BrowserBusyError;const explained = busy || error instanceof BrowserUnresponsiveError;- this.send(viewer, { type: "error", retryable: !busy, message: explained ? error.message : "The browser stream could not start." });+ this.send(viewer, { type: "error", retryable: !busy, message: explained ? error.message : "The browser stream could not start.", ...userErrorFields(error) });this.close(viewer); return;}this.close(viewer, options.res.headersSent);diff --git a/server/chat-notices.ts b/server/chat-notices.tsindex fae31e95ae..52480c6af7 100644--- a/server/chat-notices.ts+++ b/server/chat-notices.ts@@ -120,6 +120,48 @@ export const CHAT_NOTICE = {"chat.notice.reportFull": "Not sent: {count} bug reports are already waiting to go to the MausBot team. Type @devs again once they have gone.","chat.notice.reportDropped": "A bug report from this conversation could not reach the MausBot team for a week, so it was dropped. Type @devs again to send a new one.",+ "chat.notice.copilotAccountRefused": "GitHub Copilot refused this request for the signed-in account. Check its Copilot plan and premium request allowance, then try again.",+ "chat.notice.acpQuietUsageLimit": "{name} reached a usage limit{said} and is waiting it out without replying, so this turn was stopped.",+ "chat.notice.acpQuietStuck": "{name} sent nothing for {quiet} with no tool running, no open request to its model and no CPU use, so the turn was stopped as stuck. Send the message again to retry.",+ "chat.notice.acpModelRequestFailed": "{name}'s model request failed: \"{message}\" {name} may retry or stop; no reply for {quiet} so far.",+ "chat.notice.acpModelFallback": "{displayName} no longer offers {wanted}, so this conversation uses {fallback}. Choose another model for this bot to stop seeing this.",+ "chat.notice.codexActionMayHaveRun": "{message} A tool action may have run. Check its effects before trying again.",+ "chat.notice.modelServerStoppedAnswering": "The model server at {host} stopped answering, so the reply was stopped.",+ "chat.notice.piModelNotConfirmed": "Pi did not confirm the selected model",+ "chat.notice.waitingApprovalElsewhere": "Waiting on your approval in @{name}",+ "chat.notice.waitingAnswerElsewhere": "Waiting on your answer in @{name}",+ "chat.notice.teammateNeedsInput": "{name} needs your input: {question}",+ "chat.notice.relayCouldNotContinue": "this conversation could not carry on — {error}",+ "chat.notice.provideSecretSecurely": "Securely provide the {label} from OpenMausBot on your phone or computer. It is never added to chat.",+ "chat.notice.inboxNotPassed": "Not passed to {from}",+ "chat.notice.engineSignedOut": "{name} is signed out.",+ "chat.notice.failoverSignedInAgain": "{engine} is signed in again, so this conversation is back on {engine}.",+ "chat.notice.failoverSignedOut": "{from} is signed out, so {to} took over.",+ "chat.notice.backupCardWaiting": "switched to {name}. Your request waits on a card above and continues on {name} once you act on it.",+ "chat.notice.backupRequestUnderWay": "switched to {name}. Your request is still under way here and continues on {name}.",+ "chat.notice.backupConversationBusy": "switched to {name}. This conversation is working, so your message was not sent again.",+ "chat.notice.backupQuestionWaiting": "switched to {name}. A teammate's question is waiting for your answer in this conversation, so your message was not sent again. Answer it, then send your message again.",+ "chat.notice.backupMessageMissing": "switched to {name}, but your message could not be found to send again. Send it again.",+ "chat.notice.backupContinuingLimit": "continuing on {name} after hitting the usage limit",+ "chat.notice.backupContinuingSignedOut": "continuing on {name} while {engine} is signed out",+ "chat.notice.backupCouldNotContinue": "could not continue on {name}: {error}",+ "chat.notice.waitDone.urlContains": "{label}: done. {url} now says “{text}”.",+ "chat.notice.waitDone.urlMissing": "{label}: done. {url} no longer says “{text}”.",+ "chat.notice.waitDone.fileExists": "{label}: done. {path} is there now.",+ "chat.notice.waitDone.fileMissing": "{label}: done. {path} is gone.",+ "chat.notice.waitDone.fileChanged": "{label}: done. {path} changed.",+ "chat.notice.waitDone.processRunning": "{label}: done. {process} is running.",+ "chat.notice.waitDone.processGone": "{label}: done. {process} stopped.",+ "chat.notice.waitDone.botIdle": "{label}: done. {botName} finished.",+ "chat.notice.waitBotGone": "Stopped waiting for {label}: {botName} no longer exists.",+ "chat.notice.waitExpiredOne": "Stopped waiting for {label} after {hours} hour.",+ "chat.notice.waitExpiredMany": "Stopped waiting for {label} after {hours} hours.",+ "chat.notice.computerDesktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.",+ "chat.notice.computerPermissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it",+ "chat.notice.computerNotReadyDetail": "OpenMausBot can't use this computer yet — {reason}",+ "chat.notice.computerNotReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.",+ "chat.notice.computerSystemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work",+ "chat.notice.computerAiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",} as const;export type ChatNoticeKey = keyof typeof CHAT_NOTICE;diff --git a/server/desktop-computer.ts b/server/desktop-computer.tsindex 1363f462ac..4f1ee186cf 100644--- a/server/desktop-computer.ts+++ b/server/desktop-computer.ts@@ -1,3 +1,4 @@+import { userErrorThrown } from "./user-errors.ts";// "This computer" is the desktop app's own computer, and only the server the app launched may drive it. The app proves// that by handing the driver connection to that one child over Electron's private utility-process port, which only the// app's main process can write to and which plain Node never has. No file, environment variable or HTTP route supplies@@ -59,3 +60,11 @@ export function thisComputerNotReady(desktop: DesktopComputer = desktopComputer,const permission = platform === "darwin" && /(?:Screen Recording|Accessibility).*required/i.test(reason);return `${THIS_COMPUTER_NOT_READY}${reason}${permission ? ". Relaunch OpenMausBot after granting the missing macOS permission." : ""}`;}++export function thisComputerNotReadyError(desktop: DesktopComputer = desktopComputer, platform: NodeJS.Platform = process.platform): Error {+ if (!desktop.granted()) return userErrorThrown("serverError.computer.desktopOnly");+ const reason = desktop.unavailableReason();+ if (!reason) return userErrorThrown("serverError.computer.permissionsThenRestart");+ const permission = platform === "darwin" && /(?:Screen Recording|Accessibility).*required/i.test(reason);+ return userErrorThrown(permission ? "serverError.computer.notReadyMacPermission" : "serverError.computer.notReadyDetail", { reason });+}diff --git a/server/drivers/acp/copilot.ts b/server/drivers/acp/copilot.tsindex 1a6986f3a5..00f74a1185 100644--- a/server/drivers/acp/copilot.ts+++ b/server/drivers/acp/copilot.ts@@ -219,6 +219,7 @@ const SUPPORT: AcpSupport = {isAuthenticated: (env, config) => copilotSignedIn(env, config),classifyError: classifyCopilotError,describeAccountError: describeCopilotAccountError,+ accountErrorText: code => code === "invalid_credentials" ? undefined : { key: "chat.notice.copilotAccountRefused" },buildPromptText: (turn) => (turn.system ? `${turn.system}\n\n${turn.text}` : turn.text),};diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 267ba37c80..8a928c3706 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -1,3 +1,5 @@+import { type ServerText } from "../../../shared/server-text.ts";+import { runtimeErrorText } from "../runtime-notice-error.ts";// The shared ACP (JSON-RPC 2.0 over stdio) driver; per-CLI quirks live in an AcpSupport.// ACP has no turn/completed: the session/prompt result (stopReason + usage) is the completion.// session/load replays history as ordinary session/update notifications, so nothing emits before@@ -20,7 +22,7 @@ import { runAcpOneShot } from "./background-text.ts";import { sanitizeAcpToolMessage } from "./tool-log.ts";import { stripLeakedSystemHarnessMessages } from "../../../shared/system-message-guard.ts";import {- classifyQuiet, describeQuiet, formatQuietLimit, lastSeenPhrase, LIMIT_WORDS, LogTail, promptIdleTimeoutMs, quietKey, quietNoticeMs, quietTickMs, quietVerdict, sampleProcessTree,+ classifyQuiet, describeQuiet, formatQuietLimit, quietNoticeText, lastSeenPhrase, LIMIT_WORDS, LogTail, promptIdleTimeoutMs, quietKey, quietNoticeMs, quietTickMs, quietVerdict, sampleProcessTree,type LogSignal, type ProcessSample, type QuietState,} from "./quiet-status.ts";import { readSessionReport } from "./session-reports.ts";@@ -223,6 +225,7 @@ export interface AcpSupport {/** Plain words for an account failure (bad key, no credit, a used-up* quota, no subscription) in place of the provider's raw RPC text. */describeAccountError?(code: AccountErrorCode, model?: string): string;+ accountErrorText?(code: AccountErrorCode): ServerText | undefined;/** Compose the session/prompt text. Default prepends the persona. */buildPromptText?(turn: SendTurnInput): string;/** Rewrite a picker id (`omlx::model`) into the CLI-native id before spawn and session/select. */@@ -586,7 +589,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>emit({...base(threadId, current.turnId),type: "runtime.notice",- message: describeQuiet(support.displayName, next, quietMs, promptIdleTimeoutMs()),+ message: describeQuiet(support.displayName, next, quietMs, promptIdleTimeoutMs()), text: quietNoticeText(support.displayName, next, quietMs),});};const timer = setInterval(() => { void tick(); }, tickMs);@@ -1370,7 +1373,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>});if (pick.accountModels) accountModels = pick.accountModels;staleProcess = pick.staleProcess;- if (pick.notice) emit({ ...base(threadId, turnId), type: "runtime.notice", message: pick.notice });+ if (pick.notice) emit({ ...base(threadId, turnId), type: "runtime.notice", message: pick.notice, text: pick.noticeText });({ turn: cliTurn, variant, reportedModel } = pick);current.turn = cliTurn;selectedModel = await modelControls.select(request, sessionId, INIT_TIMEOUT);@@ -1578,6 +1581,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (!state.stopped) emit({...base(threadId, turnId), type: "runtime.error",...(accountError && support.describeAccountError ? { message: support.describeAccountError(code, cliTurn.model) } : engineFailure(support.displayName, message) ?? { message }),+ text: accountError ? support.accountErrorText?.(code) : runtimeErrorText(e),...(needsAuth ? { setup: true } : {}), ...((e as any)?.acpPromptStall === true ? { stalled: true } : {}),...((e as any)?.acpUsageLimit === true || (code === "quota_or_region_restriction" && LIMIT_WORDS.test(message)) ? { limit: "engine" as const } : {}), // waited out, or the engine gave up: another AI can carry on});diff --git a/server/drivers/acp/quiet-status.ts b/server/drivers/acp/quiet-status.tsindex 6d84f6e90b..0b000aeb1a 100644--- a/server/drivers/acp/quiet-status.ts+++ b/server/drivers/acp/quiet-status.ts@@ -1,3 +1,4 @@+import { RuntimeNoticeError } from "../runtime-notice-error.ts";// What a quiet ACP agent is doing. ACP has no "still working" message, and agents go silent for minutes// (Qwen Code 0.24 while it waits out a rate limit, retries, or runs a slow call), so a quiet turn is// probed from the agent's debug log and its process tree's connections and CPU.@@ -346,10 +347,10 @@ export function quietVerdict(input: {const limited = input.logged && waitingOutLimit(input.logged.signal) && input.now - input.logged.at >= limitQuietMs() ? input.logged.signal : null;if (limited) {const said = limited.kind === "provider-error" ? ` (“${limited.message}”)` : "";- return { next, noSignsSince, stop: Object.assign(new Error(`${input.name} reached a usage limit${said} and is waiting it out without replying, so this turn was stopped.`), { acpUsageLimit: true }) };+ return { next, noSignsSince, stop: Object.assign(new RuntimeNoticeError(`${input.name} reached a usage limit${said} and is waiting it out without replying, so this turn was stopped.`, "chat.notice.acpQuietUsageLimit", { name: input.name, said }), { acpUsageLimit: true }) };}if (noSignsSince !== null && input.now - noSignsSince >= noSignsStopMs()) {- return { next, noSignsSince, stop: Object.assign(new Error(`${input.name} sent nothing for ${formatQuietLimit(input.quietMs)} with no tool running, no open request to its model and no CPU use, so the turn was stopped as stuck. Send the message again to retry.`), { acpPromptStall: true }) };+ return { next, noSignsSince, stop: Object.assign(new RuntimeNoticeError(`${input.name} sent nothing for ${formatQuietLimit(input.quietMs)} with no tool running, no open request to its model and no CPU use, so the turn was stopped as stuck. Send the message again to retry.`, "chat.notice.acpQuietStuck", { name: input.name, quiet: formatQuietLimit(input.quietMs) }), { acpPromptStall: true }) };}return { next, noSignsSince, stop: null };}@@ -432,3 +433,7 @@ export function lastSeenPhrase(state: QuietState): string {case "unknown": return "no readable process state";}}++export function quietNoticeText(name: string, state: QuietState, quietMs: number) {+ return state.kind === "provider-error" ? { key: "chat.notice.acpModelRequestFailed", params: { name, message: state.message, quiet: minutes(quietMs) } } : undefined;+}diff --git a/server/drivers/acp/session-model-controls.ts b/server/drivers/acp/session-model-controls.tsindex 8d64d2b845..0f486710eb 100644--- a/server/drivers/acp/session-model-controls.ts+++ b/server/drivers/acp/session-model-controls.ts@@ -1,3 +1,4 @@+import { type ServerText } from "../../../shared/server-text.ts";import type { ModelCatalog, ModelVariantOption, SendTurnInput } from "../../contracts.ts";import { decodeInjectId } from "../local-inject.ts";import { acpModelOption, acpVariantOption, offeredModels } from "./config-options.ts";@@ -109,6 +110,7 @@ export interface SessionModelPick {staleProcess: boolean;/** Tell the person the session runs another model than the one picked; once per session for each such swap. */notice: string | null;+ noticeText?: ServerText;}/** The model this turn asks the live session for, before the setter runs: a legacy id the driver maps@@ -142,6 +144,7 @@ export function pickSessionModel(const staleProcess = Boolean(support.fallbackModel && wanted && !input.launchedThisTurn && offered.length&& !offered.includes(wanted) && catalog.options.some((option) => option.id === wanted || option.id === requested.model));let notice: string | null = null;+ let noticeText: ServerText | undefined;// A local injected model is never swapped for the account's fallback.if (support.fallbackModel && offered.length && !decodeInjectId(requested.model)&& !staleProcess && (!wanted || !offered.includes(wanted))) {@@ -150,6 +153,7 @@ export function pickSessionModel(const noticeKey = wanted ? `${wanted}\n${fallback}` : null;if (noticeKey && session.fallbackNotice !== noticeKey) {session.fallbackNotice = noticeKey;+ noticeText = { key: "chat.notice.acpModelFallback", params: { displayName: support.displayName, wanted: wanted!, fallback } };notice = `${support.displayName} no longer offers ${wanted}, so this conversation uses ${fallback}. ` +"Choose another model for this bot to stop seeing this.";}@@ -158,5 +162,5 @@ export function pickSessionModel(variant = undefined;}}- return { turn, variant, reportedModel, accountModels, staleProcess, notice };+ return { turn, variant, reportedModel, accountModels, staleProcess, notice, ...(noticeText ? { noticeText } : {}) };}diff --git a/server/drivers/codex-action-notice.ts b/server/drivers/codex-action-notice.tsnew file mode 100644index 0000000000..86ffe41372--- /dev/null+++ b/server/drivers/codex-action-notice.ts@@ -0,0 +1,5 @@+import { noticeFailure } from "../chat-notices.ts";++export function codexActionFailure(message: string, mayHaveRun: boolean) {+ return mayHaveRun ? noticeFailure("chat.notice.codexActionMayHaveRun", { message }) : { message };+}diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 3e20f4b42c..98420df835 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -1,3 +1,4 @@+import { codexActionFailure } from "./codex-action-notice.ts";import { codexToolSurfaceArgs } from "./codex-tool-surface.ts";import { codexShellDisabled, GUEST_CONFINED_CODEX_ARGS } from "./codex-guest.ts";import { TEAM_TOOLS_FAILED, teamToolsFailed } from "./team-tools.ts";@@ -1631,8 +1632,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {if (refused) loginRefused();emit({...base(threadId, turnId), type: "runtime.error",- message: earlyNotifications.some((event) => ["commandExecution", "fileChange", "mcpToolCall", "webSearch"].includes(event.params?.item?.type))- ? `${message} A tool action may have run. Check its effects before trying again.` : message,+ ...codexActionFailure(message, earlyNotifications.some((event) => ["commandExecution", "fileChange", "mcpToolCall", "webSearch"].includes(event.params?.item?.type))),...(needsAuth ? { setup: true } : codexLimitFacts(raw, route)),});await settle(false, needsAuth ? "auth_required" : verdict.reason === "provider_safety" ? "provider_safety" : "rpc_error");diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 3a07459cc5..53a160f4f8 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -1,3 +1,4 @@+import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts";import { createHash } from "node:crypto";import type {DriverCreateInput,@@ -319,7 +320,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)fetch(`${options.apiUrl}/models`, { headers: { authorization: `Bearer ${options.apiKey}` }, signal: AbortSignal.timeout(everyMs) }).then((response) => { misses = 0; void response.body?.cancel(); }).catch(() => {- if (++misses === LIVENESS_MISSES) stop(new Error(`The model server at ${new URL(options.apiUrl).host} stopped answering, so the reply was stopped.`));+ if (++misses === LIVENESS_MISSES) stop(new RuntimeNoticeError(`The model server at ${new URL(options.apiUrl).host} stopped answering, so the reply was stopped.`, "chat.notice.modelServerStoppedAnswering", { host: new URL(options.apiUrl).host }));});}, everyMs);timer.unref();@@ -508,6 +509,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)activeSignal.throwIfAborted();if (!sawChoice) throw new ChatProtocolError("provider returned no streaming completion choice");return { text, reasoning, usage, toolCalls: calls.finish(finishReason, malformedFrame), finishReason, protocolReasoning, protocolReasoningDetails: details.blocks };+ } catch (error) {+ if (timeoutController.signal.reason instanceof RuntimeNoticeError) throw timeoutController.signal.reason;+ throw error;} finally {if (idleTimer) clearTimeout(idleTimer);if (liveness) clearInterval(liveness);@@ -624,6 +628,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)let ok = false;let stopReason: string | null = null;let failure: string | undefined;+ let failureText: ReturnType<typeof runtimeErrorText>;let toolFailed = false;let correctiveRounds = 0;const denials: string[] = [];@@ -880,6 +885,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)} catch (value) {stopReason = abort.signal.aborted ? "interrupted" : stopReason ?? "error";failure = safeText(asError(value).message).slice(0, 2_000);+ failureText = runtimeErrorText(value);} finally {turnEntry.ending = true;approval.close();@@ -896,7 +902,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)if (failure && (!abort.signal.aborted || cleanupFailed)) {// "upstream" (an OpenAI-compatible URL) names no provider, and the Cloud trial credit reads its raw line.const words = options.httpErrorLabel === "upstream" ? { message: failure } : plainFailure(options.httpErrorLabel, failure);- emit({ ...base(turn.threadId, turnId), type: "runtime.error", ...words, terminal: !abort.signal.aborted });+ emit({ ...base(turn.threadId, turnId), type: "runtime.error", ...words, ...(!cleanupFailed && failureText ? { text: failureText } : {}), terminal: !abort.signal.aborted });}if (!ok && !abort.signal.aborted) {const continuable = classifyContinuable(stopReason, failure);diff --git a/server/drivers/openai-compat-idle.test.ts b/server/drivers/openai-compat-idle.test.tsindex 393a1ff88a..255941dc67 100644--- a/server/drivers/openai-compat-idle.test.ts+++ b/server/drivers/openai-compat-idle.test.ts@@ -86,7 +86,7 @@ it("stops waiting soon after a local server stops answering, long before the repconst done = await fixture.recorder.until((event) => event.type === "turn.completed", 10_000);expect(done).toMatchObject({ ok: false });expect(Date.now() - started).toBeLessThan(10_000);- expect(fixture.recorder.events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("stopped answering") });+ expect(fixture.recorder.events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("stopped answering"), text: { key: "chat.notice.modelServerStoppedAnswering", params: { host: expect.stringMatching(/^127\.0\.0\.1:\d+$/) } } });} finally {await fixture.close();}diff --git a/server/drivers/pi-model-id.ts b/server/drivers/pi-model-id.tsnew file mode 100644index 0000000000..5dca7cb7c0--- /dev/null+++ b/server/drivers/pi-model-id.ts@@ -0,0 +1,5 @@+export function piModelId(model: unknown): string | null {+ const entry = model as { provider?: unknown; id?: unknown } | null | undefined;+ return typeof entry?.provider === "string" && entry.provider && typeof entry.id === "string" && entry.id+ ? `${entry.provider}/${entry.id}` : null;+}diff --git a/server/drivers/pi.ts b/server/drivers/pi.tsindex 70812a0cec..24c130c906 100644--- a/server/drivers/pi.ts+++ b/server/drivers/pi.ts@@ -1,3 +1,5 @@+import { piModelId } from "./pi-model-id.ts";+import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts";// The pi coding agent (@earendil-works/pi-coding-agent) over its own stdio JSON-RPC mode// (`pi --mode rpc --no-session`), not ACP. pi is BYOK and reads ~/.pi/agent/auth.json itself, so// this driver holds no key; resumeCursor is pi's `sessionFile` (switch_session).@@ -106,11 +108,6 @@ interface PiModelEntry {name?: string;}-function piModelId(model: unknown): string | null {- const entry = model as Partial<PiModelEntry> | null | undefined;- return typeof entry?.provider === "string" && entry.provider && typeof entry.id === "string" && entry.id- ? `${entry.provider}/${entry.id}` : null;-}interface PiModelsResponse {type: "response";command: "get_available_models";@@ -851,10 +848,10 @@ export const PiDriver: ProviderDriver<PiConfig> = {const modelPromise = awaitResponse("set_model");send({ type: "set_model", provider: chosen.provider, modelId: chosen.modelId });confirmedModel = piModelId(await modelPromise);- if (!confirmedModel) throw new Error("Pi did not confirm the selected model");+ if (!confirmedModel) throw new RuntimeNoticeError("Pi did not confirm the selected model", "chat.notice.piModelNotConfirmed");} catch (error) {if (!settled) {- emit({ ...base(threadId, turnId), type: "runtime.error", message: String((error as Error).message) });+ emit({ ...base(threadId, turnId), type: "runtime.error", message: String((error as Error).message), text: runtimeErrorText(error) });await settle(false);}return { turnId };diff --git a/server/drivers/runtime-notice-error.test.ts b/server/drivers/runtime-notice-error.test.tsnew file mode 100644index 0000000000..67f3f038e9--- /dev/null+++ b/server/drivers/runtime-notice-error.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from "vitest";+import { chatNotice } from "../chat-notices.ts";+import { codexActionFailure } from "./codex-action-notice.ts";+import { piModelId } from "./pi-model-id.ts";+import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts";+import { describeQuiet, quietNoticeText, quietVerdict } from "./acp/quiet-status.ts";++describe("runtime notice provenance", () => {+ it("keeps only an app-owned error's code and redacts its params centrally", () => {+ const secret = `sk-ant-${"Ab1c".repeat(9)}`;+ const error = new RuntimeNoticeError("Pi did not confirm the selected model", "chat.notice.piModelNotConfirmed", { detail: secret });+ expect(error).toBeInstanceOf(Error);+ expect(error.message).toBe("Pi did not confirm the selected model");+ expect(runtimeErrorText(error)?.key).toBe("chat.notice.piModelNotConfirmed");+ expect(JSON.stringify(runtimeErrorText(error))).not.toContain(secret);+ expect(runtimeErrorText(new Error(error.message))).toBeUndefined();+ expect(runtimeErrorText({ text: error.text })).toBeUndefined();+ });++ it.each([false, true])("codes the tool-action suffix only when an action may have run (%s)", (mayHaveRun) => {+ const failure = codexActionFailure("Provider's own words", mayHaveRun);+ expect(failure.message).toBe(`Provider's own words${mayHaveRun ? " A tool action may have run. Check its effects before trying again." : ""}`);+ expect("text" in failure ? failure.text?.key : undefined).toBe(mayHaveRun ? "chat.notice.codexActionMayHaveRun" : undefined);+ });++ it.each([1_000, 89_000, 90_000, 180_000])("keeps the provider error's quiet duration at %i ms", (quietMs) => {+ const state = { kind: "provider-error", message: "Provider's own words" } as const;+ const words = quietNoticeText("Custom ACP", state, quietMs)!;+ expect(chatNotice("chat.notice.acpModelRequestFailed", words.params)).toBe(describeQuiet("Custom ACP", state, quietMs, 600_000));+ expect(quietNoticeText("Custom ACP", { kind: "unknown" }, quietMs)).toBeUndefined();+ });++ it("carries the quiet-stop classifications and their complete English sentences", () => {+ const verdict = quietVerdict({ name: "Custom ACP", next: { kind: "provider-error", message: "HTTP 429" }, logged: { signal: { kind: "provider-error", message: "HTTP 429" }, at: 0 }, now: 600_000, quietMs: 600_000, noSignsSince: null, stuckAfterMs: 600_000 });+ expect(verdict.stop).toMatchObject({ acpUsageLimit: true });+ const text = runtimeErrorText(verdict.stop)!;+ expect(text.key).toBe("chat.notice.acpQuietUsageLimit");+ expect(chatNotice("chat.notice.acpQuietUsageLimit", text.params)).toBe(verdict.stop?.message);+ const stuck = quietVerdict({ name: "Custom ACP", next: { kind: "no-signs" }, logged: null, now: 600_000, quietMs: 600_000, noSignsSince: 0, stuckAfterMs: 100_000 });+ expect(stuck.stop).toMatchObject({ acpPromptStall: true });+ expect(runtimeErrorText(stuck.stop)?.key).toBe("chat.notice.acpQuietStuck");+ });++ it.each([null, undefined, {}, { provider: "x" }, { id: "y" }, { provider: 1, id: "y" }, { provider: "", id: "y" }])("does not confirm a partial Pi model: %j", (model) => {+ expect(piModelId(model)).toBeNull();+ });++ it("keeps Pi's confirmed provider and model id verbatim", () => {+ expect(piModelId({ provider: "FixtureProvider", id: "CaseSensitiveModel", name: "Fixture" })).toBe("FixtureProvider/CaseSensitiveModel");+ });+});diff --git a/server/drivers/runtime-notice-error.ts b/server/drivers/runtime-notice-error.tsnew file mode 100644index 0000000000..9806dd1838--- /dev/null+++ b/server/drivers/runtime-notice-error.ts@@ -0,0 +1,15 @@+import type { ServerText } from "../../shared/server-text.ts";+import { noticeFailure, type ChatNoticeKey } from "../chat-notices.ts";++export class RuntimeNoticeError extends Error {+ readonly text: ServerText;++ constructor(message: string, key: ChatNoticeKey, params?: Record<string, string>) {+ super(message);+ this.text = noticeFailure(key, params).text;+ }+}++export function runtimeErrorText(error: unknown): ServerText | undefined {+ return error instanceof RuntimeNoticeError ? error.text : undefined;+}diff --git a/server/engine-standalone.ts b/server/engine-standalone.tsindex 82f4335889..2a8fc7055b 100644--- a/server/engine-standalone.ts+++ b/server/engine-standalone.ts@@ -1,3 +1,4 @@+import { userError, userErrorFields } from "./user-errors.ts";// An AI's own standalone build, installed without Node.js or npm. The release is pinned in code (URLs, archive and// program SHA-256, size, hosts, macOS signer), downloaded over HTTPS from those hosts only, and checked before anything// is unpacked. The new build must start before it replaces anything, the old folder is moved aside rather than deleted@@ -328,7 +329,7 @@ function checkRelease(release: StandaloneRelease, asset: StandaloneAsset): void|| typeof asset.executableSha256 !== "string" || !SHA256.test(asset.executableSha256)|| !safeArchivePath(asset.executable) || !Number.isSafeInteger(asset.approxBytes) || asset.approxBytes <= 0|| (release.macTeamId !== undefined && !TEAM_ID.test(release.macTeamId))- ) throw new StandaloneInstallError(`${release.name}'s install details are invalid. Nothing was downloaded.`);+ ) throw Object.assign(new StandaloneInstallError(`${release.name}'s install details are invalid. Nothing was downloaded.`), userErrorFields(userError("serverError.install.invalidDetails", { name: release.name })));}function trustedUrl(url: URL, hosts: readonly string[]): boolean {@@ -349,17 +350,17 @@ function warn(release: StandaloneRelease, detail: unknown): void {}function httpRefusal(name: string, status: number): StandaloneInstallError {- if (status === 404 || status === 410) return new StandaloneInstallError(`This version of ${name} is no longer available to download. Update OpenMausBot, then try again.`);- if (status === 403 || status === 429) return new StandaloneInstallError(`The download site is limiting downloads right now. Try again in a few minutes.`);- if (status >= 500) return new StandaloneInstallError(`${name}'s download site isn't answering right now. Try again later.`);- return new StandaloneInstallError(`${name} couldn't be downloaded. Check the internet connection and try again.`);+ if (status === 404 || status === 410) return Object.assign(new StandaloneInstallError(`This version of ${name} is no longer available to download. Update OpenMausBot, then try again.`), userErrorFields(userError("serverError.install.versionGone", { name: name })));+ if (status === 403 || status === 429) return Object.assign(new StandaloneInstallError(`The download site is limiting downloads right now. Try again in a few minutes.`), userErrorFields(userError("serverError.install.downloadLimited")));+ if (status >= 500) return Object.assign(new StandaloneInstallError(`${name}'s download site isn't answering right now. Try again later.`), userErrorFields(userError("serverError.install.siteNotAnswering", { name: name })));+ return Object.assign(new StandaloneInstallError(`${name} couldn't be downloaded. Check the internet connection and try again.`), userErrorFields(userError("serverError.install.downloadFailed", { name: name })));}/** Streams the asset to `destination` while hashing it; every hop must be HTTPS to a release host. */async function download(release: StandaloneRelease, asset: StandaloneAsset, destination: string, options: StandaloneInstallOptions): Promise<void> {const name = release.name;const cap = asset.approxBytes * 2;- const tooLarge = () => new StandaloneInstallError(`The ${name} download was larger than expected, so it was stopped. Nothing was installed.`);+ const tooLarge = () => Object.assign(new StandaloneInstallError(`The ${name} download was larger than expected, so it was stopped. Nothing was installed.`), userErrorFields(userError("serverError.install.downloadTooLarge", { name: name })));const controller = new AbortController();let timedOut = false;let stalled = false;@@ -382,7 +383,7 @@ async function download(release: StandaloneRelease, asset: StandaloneAsset, destlet response: Response;for (let hop = 0; ; hop += 1) {if (!trustedUrl(url, release.hosts)) {- throw new StandaloneInstallError(`The ${name} download did not come from its official site, so it was stopped. Nothing was installed.`);+ throw Object.assign(new StandaloneInstallError(`The ${name} download did not come from its official site, so it was stopped. Nothing was installed.`), userErrorFields(userError("serverError.install.unofficialDownload", { name: name })));}progressed();response = await (options.fetchImpl ?? fetch)(url.href, { redirect: "manual", signal: controller.signal });@@ -390,7 +391,7 @@ async function download(release: StandaloneRelease, asset: StandaloneAsset, destconst location = response.headers.get("location");await response.body?.cancel().catch(() => {});if (!location || hop >= MAX_REDIRECTS) {- throw new StandaloneInstallError(`The ${name} download kept redirecting, so it was stopped. Nothing was installed.`);+ throw Object.assign(new StandaloneInstallError(`The ${name} download kept redirecting, so it was stopped. Nothing was installed.`), userErrorFields(userError("serverError.install.redirects", { name: name })));}url = new URL(location, url);}@@ -416,16 +417,16 @@ async function download(release: StandaloneRelease, asset: StandaloneAsset, destawait handle.close();}if (hash.digest("hex") !== asset.sha256) {- throw new StandaloneInstallError(`The ${name} download failed its safety check, so nothing was installed. Try again later.`);+ throw Object.assign(new StandaloneInstallError(`The ${name} download failed its safety check, so nothing was installed. Try again later.`), userErrorFields(userError("serverError.install.safetyCheck", { name: name })));}} catch (error) {if (error instanceof StandaloneInstallError) throw error;- if (timedOut) throw new StandaloneInstallError(`The ${name} download took too long and was stopped. Check the internet connection and try again.`);+ if (timedOut) throw Object.assign(new StandaloneInstallError(`The ${name} download took too long and was stopped. Check the internet connection and try again.`), userErrorFields(userError("serverError.install.downloadTimeout", { name: name })));if (stalled) throw new StandaloneInstallError(`The ${name} download stopped partway. Check the internet connection and try again.`);// A file-system error (no space, a locked folder) is the caller's to describe; anything else is the network.if (typeof (error as NodeJS.ErrnoException).code === "string") throw error;warn(release, error instanceof Error && error.cause instanceof Error ? `${error.message}: ${error.cause.message}` : error);- throw new StandaloneInstallError(`${name} couldn't be downloaded. Check the internet connection and try again.`);+ throw Object.assign(new StandaloneInstallError(`${name} couldn't be downloaded. Check the internet connection and try again.`), userErrorFields(userError("serverError.install.downloadFailed", { name: name })));} finally {clearTimeout(timer);clearTimeout(stallTimer);@@ -467,13 +468,13 @@ async function normaliseModes(directory: string): Promise<void> {} else if (entry.isFile()) {await chmod(path, ((await stat(path)).mode & 0o111) !== 0 ? 0o755 : 0o644);} else {- throw new StandaloneInstallError("The archive contains an unexpected or unsafe file. Nothing was installed.");+ throw Object.assign(new StandaloneInstallError("The archive contains an unexpected or unsafe file. Nothing was installed."), userErrorFields(userError("serverError.install.unsafeArchive")));}}}async function unpack(release: StandaloneRelease, archivePath: string, staging: string, asset: StandaloneAsset): Promise<void> {- const unsafe = new StandaloneInstallError(`The ${release.name} download holds an unexpected or unsafe file, so nothing was installed.`);+ const unsafe = Object.assign(new StandaloneInstallError(`The ${release.name} download holds an unexpected or unsafe file, so nothing was installed.`), userErrorFields(userError("serverError.install.unsafeFile", { name: release.name })));try {if (asset.archive === "zip") await extractZip(archivePath, staging, { maxEntries: MAX_ZIP_MEMBERS });else if (asset.archive === "tar.gz") {@@ -587,7 +588,7 @@ async function realFolder(path: string, release: StandaloneRelease): Promise<voireturn;}if (!info.isDirectory()) {- throw new StandaloneInstallError(`OpenMausBot's folder for ${release.name} is not a plain folder (${path}), so nothing was changed. Move it away, then try again.`);+ throw Object.assign(new StandaloneInstallError(`OpenMausBot's folder for ${release.name} is not a plain folder (${path}), so nothing was changed. Move it away, then try again.`), userErrorFields(userError("serverError.install.notPlainFolder", { name: release.name, path: path })));}}@@ -597,7 +598,7 @@ async function checkBinFolder(binDir: string, release: StandaloneRelease): Promiawait realFolder(binDir, release);const folder = (await readdir(binDir, { withFileTypes: true })).find((entry) => entry.isDirectory());if (folder) {- throw new StandaloneInstallError(`OpenMausBot's folder for ${release.name} holds something it did not put there (${join(binDir, folder.name)}), so nothing was changed. Move it away, then try again.`);+ throw Object.assign(new StandaloneInstallError(`OpenMausBot's folder for ${release.name} holds something it did not put there (${join(binDir, folder.name)}), so nothing was changed. Move it away, then try again.`), userErrorFields(userError("serverError.install.unexpectedFolder", { name: release.name, path: join(binDir, folder.name) })));}}@@ -665,21 +666,21 @@ export function plainInstallError(release: StandaloneRelease, asset: StandaloneAconst { code, syscall } = error as NodeJS.ErrnoException;if (code === "ENOSPC") {const megabytes = Math.ceil((asset.approxBytes * 4) / 1024 / 1024);- return new StandaloneInstallError(`There is not enough free disk space to install ${release.name}. Free up about ${megabytes} MB, then try again.`);+ return Object.assign(new StandaloneInstallError(`There is not enough free disk space to install ${release.name}. Free up about ${megabytes} MB, then try again.`), userErrorFields(userError("serverError.install.diskSpace", { name: release.name, megabytes: megabytes })));}if (code === "EBUSY" || code === "ENOTEMPTY" || (code === "EPERM" && (syscall === "rename" || syscall === "unlink" || syscall === "rmdir"))) {- return new StandaloneInstallError(`${release.name} is open in another window. Close it, then try again.`);+ return Object.assign(new StandaloneInstallError(`${release.name} is open in another window. Close it, then try again.`), userErrorFields(userError("serverError.install.openElsewhere", { name: release.name })));}if (code === "EACCES" || code === "EPERM" || code === "EROFS") {- return new StandaloneInstallError(`OpenMausBot can't write to its folder for ${release.name}. Check the folder's permissions, then try again.`);+ return Object.assign(new StandaloneInstallError(`OpenMausBot can't write to its folder for ${release.name}. Check the folder's permissions, then try again.`), userErrorFields(userError("serverError.install.cannotWrite", { name: release.name })));}- return new StandaloneInstallError(`${release.name} couldn't be installed. Try again.`);+ return Object.assign(new StandaloneInstallError(`${release.name} couldn't be installed. Try again.`), userErrorFields(userError("serverError.install.failed", { name: release.name })));}async function installOnce(release: StandaloneRelease, options: StandaloneInstallOptions): Promise<StandaloneInstalled> {const key = options.platformKey ?? standalonePlatformKey();const asset = standaloneAssetFor(release, key);- if (!asset) throw new StandaloneInstallError(`${release.name} has no download for this computer.`);+ if (!asset) throw Object.assign(new StandaloneInstallError(`${release.name} has no download for this computer.`), userErrorFields(userError("serverError.install.noDownload", { name: release.name })));checkRelease(release, asset);const codesign = options.codesign ?? runCodesign;const engineDir = standaloneEngineDir(release.engine, options.baseDir);@@ -702,7 +703,7 @@ async function installOnce(release: StandaloneRelease, options: StandaloneInstal// The bytes are the pinned ones, so downloading them again would not help: say so and change nothing.const failure = await probeVersion(existing.executable, release);if (failure !== null) {- throw new StandaloneInstallError(`${release.name} is installed, but it doesn't start on this computer (${failure}). Nothing was changed.`);+ throw Object.assign(new StandaloneInstallError(`${release.name} is installed, but it doesn't start on this computer (${failure}). Nothing was changed.`), userErrorFields(userError("serverError.install.existingDoesNotStart", { name: release.name, failure: failure })));}const installed = await activate(engineDir, release, asset, existing.sha256);await prune(engineDir, versionDir, release.engine).catch(() => {});@@ -714,19 +715,19 @@ async function installOnce(release: StandaloneRelease, options: StandaloneInstalawait unpack(release, archivePath, staging, asset);const stagedProgram = executableIn(staging, asset.executable);if (!(await lstat(stagedProgram).catch(() => null))?.isFile()) {- throw new StandaloneInstallError(`The ${release.name} download did not contain the program it should, so nothing was installed.`);+ throw Object.assign(new StandaloneInstallError(`The ${release.name} download did not contain the program it should, so nothing was installed.`), userErrorFields(userError("serverError.install.programMissing", { name: release.name })));}if (process.platform !== "win32") await chmod(stagedProgram, 0o755);const programSha256 = await hashFile(stagedProgram);if (programSha256 !== asset.executableSha256) {- throw new StandaloneInstallError(`The ${release.name} download failed its safety check, so nothing was installed. Try again later.`);+ throw Object.assign(new StandaloneInstallError(`The ${release.name} download failed its safety check, so nothing was installed. Try again later.`), userErrorFields(userError("serverError.install.safetyCheck", { name: release.name })));}if (signedHere(key, release) && !(await macSignerOk(stagedProgram, release, codesign))) {- throw new StandaloneInstallError(`The downloaded ${release.name} is not signed by its maker, so nothing was installed.`);+ throw Object.assign(new StandaloneInstallError(`The downloaded ${release.name} is not signed by its maker, so nothing was installed.`), userErrorFields(userError("serverError.install.notSigned", { name: release.name })));}const failure = await probeVersion(stagedProgram, release);if (failure !== null) {- throw new StandaloneInstallError(`${release.name} was downloaded, but it doesn't start on this computer (${failure}). Nothing was installed.`);+ throw Object.assign(new StandaloneInstallError(`${release.name} was downloaded, but it doesn't start on this computer (${failure}). Nothing was installed.`), userErrorFields(userError("serverError.install.downloadDoesNotStart", { name: release.name, failure: failure })));}const record: InstallRecord = {engine: release.engine, version: release.version, sha256: asset.sha256, executable: asset.executable, executableSha256: programSha256, installedAt: Date.now(),diff --git a/server/host/ask-cards.ts b/server/host/ask-cards.tsindex af5c8e5784..0533a13870 100644--- a/server/host/ask-cards.ts+++ b/server/host/ask-cards.ts@@ -68,7 +68,7 @@ export function createAskCards(deps: AskCardsDeps) {if (!delegator || delegator.threadId === threadId || deps.copiedInto(delegator.threadId, asker.id, threadId)) return;const chip = store.appendMessage(delegator.threadId, { role: "bot", kind: "activity",from: { botId: asker.id, name: asker.name, color: asker.color },- tool: { name: `Waiting on your ${kind} in @${asker.name}` },+ tool: { name: `Waiting on your ${kind} in @${asker.name}`, nameCode: kind === "approval" ? "chat.notice.waitingApprovalElsewhere" : "chat.notice.waitingAnswerElsewhere", nameParams: { name: asker.name } },threadRef: { botId: asker.id, threadId, title: store.taskByThread(asker.id, threadId)?.title ?? asker.name },});waitingOnPersonChips.set(`${threadId}:${requestId}`, { threadId: delegator.threadId, messageId: chip.id, name: asker.name, kind });@@ -129,7 +129,7 @@ export function createAskCards(deps: AskCardsDeps) {store.appendMessage(liveParent.threadId, {role: "bot", kind: "activity",from: { botId: bot.id, name: bot.name, color: bot.color },- tool: { name: chip, ok: true },+ tool: { name: chip, ok: true, nameCode: "chat.notice.teammateNeedsInput", nameParams: { name: bot.name, question: question.slice(0, 180) } },...(node.groupId ? { comm: { groupId: node.groupId, threadId: node.threadId, withBotId: bot.id, withName: bot.name, withColor: bot.color } }: { threadRef: { botId: bot.id, threadId: node.threadId, title } }),});diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.tsindex d18d60f81a..9341244086 100644--- a/server/host/limit-takeover.test.ts+++ b/server/host/limit-takeover.test.ts@@ -288,7 +288,7 @@ describe("an AI that is signed out", () => {expect(instance.tell(KAI, CLAUDE_ON, { scope: "signed-out", backup: on("codex", "gpt-6") }), "once, not once a turn").toBeNull();signedOut(instance);expect(instance.carriedOn(KAI, "t2", CLAUDE_ON, on("codex", "gpt-6"), { scope: "signed-out" }))- .toEqual([{ name: "recovery: Claude is signed out, so Codex took over.", ok: true }]);+ .toEqual([{ name: "recovery: Claude is signed out, so Codex took over.", nameCode: "chat.notice.failoverSignedOut", nameParams: { from: "Claude", to: "Codex" }, ok: true }]);expect(told.map((entry) => entry.text)).toEqual(["Claude is signed out on the Cloud. Sign in again in Settings → AI to keep using it."]);expect(record.mock.calls.at(-1)![0]).toMatchObject({ threadId: "t2", why: "signed-out", resetsAt: null });@@ -297,7 +297,7 @@ describe("an AI that is signed out", () => {expect(instance.stillSignedOut("claude")).toBe(false);signedOut(instance);expect(instance.carriedOn(KAI, "t3", CLAUDE_ON, on("codex", "gpt-6"), { scope: "signed-out" }), "a new sign-out is told again").toEqual([- { name: "recovery: Claude is signed out, so Codex took over.", ok: true },+ { name: "recovery: Claude is signed out, so Codex took over.", nameCode: "chat.notice.failoverSignedOut", nameParams: { from: "Claude", to: "Codex" }, ok: true },{ name: "notice: Claude is signed out on the Cloud, so Kai is using Codex meanwhile. Sign in again in Settings → AI to keep using Claude.", ok: true, setup: true },]);});diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.tsindex 15bd579d60..a741c1ca2f 100644--- a/server/host/limit-takeover.ts+++ b/server/host/limit-takeover.ts@@ -1,3 +1,4 @@+import { type ServerToolText } from "../../shared/server-text.ts";// When the AI a bot runs on reaches its usage limit, or is signed out, the bot carries on with another AI the person has// set up until that limit resets or the AI is signed in again, without anyone being asked, and the person hears it once// for that stretch. What is held (an engine's limit on the reset clock, one model's own limit, a sign-in that expired)@@ -78,7 +79,7 @@ export function signedOutStop(stopReason: string | null | undefined, said: strinreturn stopReason === "auth_required" && !(said && (engineFailureKind(said) === "credits" || classifyError({ text: said }).reason === "quota"));}/** A row a conversation shows when its turn carried on elsewhere: `setup` marks the one signing in fixes. */-export interface CarriedOnRow { name: string; ok: boolean; setup?: boolean }+export interface CarriedOnRow extends ServerToolText { name: string; ok: boolean; setup?: boolean }export function createLimitTakeover(deps: LimitTakeoverDeps) {const now = deps.now ?? Date.now;@@ -274,7 +275,7 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) {const told = tell(bot, from, { ...facts, backup: to });const line = facts.scope === "signed-out" ? signedOutLine(refusedName(from, facts.scope), label(to, from)): failoverLine(refusedName(from, facts.scope), label(to, from), facts.resetsAt);- return [{ name: `recovery: ${line}`, ok: true }, ...(told && facts.scope === "signed-out" ? [{ name: `notice: ${told}`, ok: true, setup: true }] : [])];+ return [{ name: `recovery: ${line}`, ok: true, ...(facts.scope === "signed-out" ? { nameCode: "chat.notice.failoverSignedOut", nameParams: { from: refusedName(from, facts.scope), to: label(to, from) } } : {}) }, ...(told && facts.scope === "signed-out" ? [{ name: `notice: ${told}`, ok: true, setup: true }] : [])];},/** True once per bot for each stretch of this limit or sign-out: the one incident its Chief is told about, not one per* refused turn. */diff --git a/server/host/relayed-turn.ts b/server/host/relayed-turn.tsindex aa71c42c41..a641759717 100644--- a/server/host/relayed-turn.ts+++ b/server/host/relayed-turn.ts@@ -26,7 +26,7 @@ export function relayedTurn(deps: RelayedTurnDeps) {}const userMessage = deps.store.appendMessage(threadId, { role: "user", kind: "text", text, peerAsk, relay });void deps.startTurn(botId, text, { threadId, peerAsk, origin: OUTSIDE, userMessage }).catch((error: unknown) => {- deps.store.appendMessage(threadId, { role: "bot", kind: "activity", tool: failedTurnTool(`this conversation could not carry on — ${error instanceof Error ? error.message : String(error)}`) });+ deps.store.appendMessage(threadId, { role: "bot", kind: "activity", tool: failedTurnTool(`this conversation could not carry on — ${error instanceof Error ? error.message : String(error)}`, { text: { key: "chat.notice.relayCouldNotContinue", params: { error: error instanceof Error ? error.message : String(error) } } }) });});};}diff --git a/server/host/secret-cards.ts b/server/host/secret-cards.tsindex 9b3660475a..84eb3cd80d 100644--- a/server/host/secret-cards.ts+++ b/server/host/secret-cards.ts@@ -1,3 +1,4 @@+import { userError } from "../user-errors.ts";// The secure credential cards request_credential adds: the card on the conversation's visible branch, settling it,// resuming the turn it paused, and the value a paired phone sealed for this computer. No card, message or log holds the value.import { randomUUID } from "node:crypto";@@ -170,27 +171,27 @@ export function createSecretCards(deps: SecretCardsDeps) {/** A value typed into a custom card in the app: kept, then the paused turn resumes. */function saveCustomSecret(botId: string, threadId: string, messageId: string, raw: unknown): { status: number; body: Record<string, unknown> } {const message = secretMessage(botId, threadId, messageId);- if (!message?.secret) return { status: 404, body: { error: "no such credential request" } };+ if (!message?.secret) return { status: 404, body: { ...userError("serverError.secret.missing") } };const secret = message.secret;- if (!custom(secret)) return { status: 400, body: { error: "this card saves a key in Settings" } };+ if (!custom(secret)) return { status: 400, body: { ...userError("serverError.secret.settingsCard") } };if (phoneSecretSubmissions.has(phoneSecretSubmissionKey(threadId, message.id, secret.requestKey))) {- return { status: 409, body: { error: "this secret is currently being saved from a phone" } };+ return { status: 409, body: { ...userError("serverError.secret.savingFromPhone") } };}- if (secret.dismissed) return { status: 409, body: { error: "this request was declined" } };- if (secret.superseded) return { status: 409, body: { error: "this request was replaced by a newer one" } };- if (secret.stopped) return { status: 409, body: { error: "this request stopped with its task" } };- if (secret.provided || secret.savedAt !== undefined) return { status: 409, body: { error: "this secret was already saved" } };+ if (secret.dismissed) return { status: 409, body: { ...userError("serverError.secret.declined") } };+ if (secret.superseded) return { status: 409, body: { ...userError("serverError.secret.replaced") } };+ if (secret.stopped) return { status: 409, body: { ...userError("serverError.secret.taskStopped") } };+ if (secret.provided || secret.savedAt !== undefined) return { status: 409, body: { ...userError("serverError.secret.alreadySaved") } };const value = typeof raw === "string" ? raw.trim() : "";if (!value || Buffer.byteLength(value) > SECRET_VALUE_MAX_BYTES) {- return { status: 400, body: { error: `Enter the secret: up to ${SECRET_VALUE_MAX_BYTES} bytes.` } };+ return { status: 400, body: { ...userError("serverError.secret.valueSize", { bytes: SECRET_VALUE_MAX_BYTES }) } };}try {storeCustomSecret(message, botId, threadId, value);} catch (error) {console.warn(`secret card: could not keep a secret: ${error instanceof Error ? error.message : String(error)}`);- return { status: 500, body: { error: "The secret could not be kept safely. Nothing was saved." } };+ return { status: 500, body: { ...userError("serverError.secret.notKeptSafely") } };}- if (!resumeSecretCard(botId, threadId, message.id, "provided")) return { status: 409, body: { error: "this credential request is no longer available" } };+ if (!resumeSecretCard(botId, threadId, message.id, "provided")) return { status: 409, body: { ...userError("serverError.secret.unavailableLower") } };return { status: 200, body: currentSecretState(botId, threadId, message.id) ?? { provided: true, resumed: false } };}@@ -360,7 +361,7 @@ export function createSecretCards(deps: SecretCardsDeps) {const message = store.appendMessage(fromThreadId, {role: "bot",kind: "secret",- text: credentialDesktopHandoff(target.label),+ text: credentialDesktopHandoff(target.label), textCode: "chat.notice.provideSecretSecurely", textParams: { label: target.label },...(owner.group ? { from: { botId: from.id, name: from.name, color: from.color } } : {}),secret: {target: credentialId,@@ -395,7 +396,7 @@ export function createSecretCards(deps: SecretCardsDeps) {const message = store.appendMessage(threadId, {role: "bot",kind: "secret",- text: credentialDesktopHandoff(asked.label),+ text: credentialDesktopHandoff(asked.label), textCode: "chat.notice.provideSecretSecurely", textParams: { label: asked.label },...(room ? { from: { botId: from.id, name: from.name, color: from.color } } : {}),secret: {target: CUSTOM_SECRET_TARGET,diff --git a/server/host/sign-in-settle.ts b/server/host/sign-in-settle.tsindex 10eae66d72..ebafcc300e 100644--- a/server/host/sign-in-settle.ts+++ b/server/host/sign-in-settle.ts@@ -1,3 +1,4 @@+import { userError } from "../user-errors.ts";// How a sign-in card settles: Done or Cancel on the card, a saved login filling it, or the person's own line in the// conversation, which answers every sign-in request still open there.import { savedLoginResumePrompt } from "../../shared/logins.ts";@@ -35,13 +36,13 @@ export function createSignInSettle(deps: SignInSettleDeps) {const settle = (botId: string, threadId: string, messageId: string, outcome: "done" | "cancelled", saved?: { site: string }): SignInSettled => {const bot = store.bot(botId);const message = deps.signInMessage(botId, threadId, messageId);- if (!bot || !message?.signIn) return { status: 404, body: { error: "no such sign-in request" } };+ if (!bot || !message?.signIn) return { status: 404, body: { ...userError("serverError.signIn.requestMissing") } };const card = message.signIn;- if (card.superseded) return { status: 409, body: { error: "this sign-in request was superseded by a newer one" } };- if (card.answeredInChat) return { status: 409, body: { error: "this sign-in request was already answered in the chat" } };+ if (card.superseded) return { status: 409, body: { ...userError("serverError.signIn.requestReplaced") } };+ if (card.answeredInChat) return { status: 409, body: { ...userError("serverError.signIn.answeredInChat") } };const settled = signInOutcome(card);if (settled && settled !== outcome) {- return { status: 409, body: { error: `this sign-in request was already ${settled === "done" ? "marked done" : "cancelled"}` } };+ return { status: 409, body: { ...userError(settled === "done" ? "serverError.signIn.alreadyDone" : "serverError.signIn.alreadyCancelled") } };}if (settled && card.resumed) return { status: 200, body: { [outcome]: true, resumed: true } };if (!settled) handPlaceBack(bot, threadId, message.id, card.place);diff --git a/server/host/team-messages.ts b/server/host/team-messages.tsindex 8a2cddb6a4..981a00412d 100644--- a/server/host/team-messages.ts+++ b/server/host/team-messages.ts@@ -1,3 +1,4 @@+import { userErrorThrown } from "../user-errors.ts";// A Team Cloud's people as people a bot can name. Whatever is addressed to a teammate reaches their inbox// (person-inbox.ts): a tag of @Bob anywhere a teammate writes it, or in a bot's reply where Bob can see it, and// message_person ("tell Bob that…"), which passes one message, whose answer comes back to the conversation that asked.@@ -282,7 +283,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {const posted = store.appendMessage(threadId, { role: "user", kind: "text", text, replyToId, ...(line.sendId ? { sendId: line.sendId } : {}),...(line.sender ? { sender: line.sender } : {}), ...(line.reaction ? { reaction: line.reaction } : {}) });const back = answerFromInbox(threadId, null, item, text);- if (back.status !== 200) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `Not passed to ${item.from}`, ok: false, output: back.text } });+ if (back.status !== 200) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `Not passed to ${item.from}`, nameCode: "chat.notice.inboxNotPassed", nameParams: { from: item.from }, ok: false, output: back.text } });return { status: 202, message: posted };}@@ -331,7 +332,7 @@ export function createTeamMessages(deps: TeamMessagesDeps) {const repeated = store.messagesFor(threadId).some((message) => message.sendId === line.sendId);const passed = replyIn(auth, threadId, messageId, emoji, { ...line, reaction: emoji });if (!passed) return null;- if (passed.status >= 400) return Promise.reject(Object.assign(new Error(passed.error ?? "That answer can't be passed back."), { status: passed.status }));+ if (passed.status >= 400) return Promise.reject(Object.assign(passed.error ? new Error(passed.error) : userErrorThrown("serverError.inbox.answerNotPassed"), { status: passed.status }));return Promise.resolve(repeated ? { queued: false, repeated: true } : { queued: false });},/** The session's person's inbox as its panel lists it; null off a team or for someone without one. */diff --git a/server/index.ts b/server/index.tsindex 7bbe50a256..7b3dd0ee1e 100644--- a/server/index.ts+++ b/server/index.ts@@ -1,5 +1,6 @@// Import first: it reads a Cloud home's secrets off the launcher's pipe before any module can start a process.import { BOOT_CLOUD_SECRETS } from "./cloud-secrets-boot.ts";+import { startFailureText } from "./start-failure-text.ts";import { AsyncLocalStorage } from "node:async_hooks";import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";import { existsSync, realpathSync, rmSync } from "node:fs";@@ -84,7 +85,7 @@ import { groupTurnCwd } from "./room-cwd.ts";import { RoomTurnDeadline, RoomTurnStallRegistry, effectiveRoomTurnTimeoutMinutes, parseConversationTurnTimeout, roomTurnTimeoutMessage } from "./room-turn-timeout.ts";import { roomTurnEnd, type RoomClaimEnd } from "./room-turn-end.ts";import { applyHoldDirective, classifyHoldDirective, heldMemberLine, rememberHeldMessage, stopWordPlacement } from "./room-holds.ts";-import { refusalBody, userError, userErrorFields } from "./user-errors.ts";+import { refusalBody, userError, userErrorFields, userErrorThrown } from "./user-errors.ts";import { chatNotice, failedNoticeTool, noticeTool, resumedTool, runtimeNoticeTool } from "./chat-notices.ts";import type { ServerErrorBody } from "../shared/server-text.ts";import { emailSignInRoute } from "./routes/email-sign-in.ts";@@ -417,7 +418,7 @@ import {import { shellTimeoutHookResult } from "./shell-timeout-hint.ts";import { spillToolResult } from "./tool-result-spill.ts";import { gatedLocalComputer } from "./local-computer.ts";-import { desktopComputer, thisComputerNotReady } from "./desktop-computer.ts";+import { desktopComputer, thisComputerNotReadyError } from "./desktop-computer.ts";import { askToUseYourComputer, cancelYourComputerAsks, dismissStaleYourComputerCards, yourComputerCallFrom, yourComputerWaiting } from "./your-computer-consent.ts";import { discoverExistingPerBotLocalVms, localVmInventoryEntry } from "./local-vm-inventory.ts";import { createLocalVmUpdater, LOCAL_VM_UPDATING_PROBLEM, recoverLocalVms, VPS_OUTDATED_HINT, vpsDesktopOutdated, withoutHostWhileUpdating } from "./desktop-updates.ts";@@ -3647,7 +3648,7 @@ function createChannel(value: unknown): GroupRecord {}const name = body.name?.trim() || `${store.bot(memberIds[0])!.name} & co.`;if (name.length > 100) throw Object.assign(new Error("channel name must be at most 100 characters"), { status: 400 });- if (!fitsOnOneLine(name)) throw Object.assign(new Error("room name must fit on one line"), { status: 400 });+ if (!fitsOnOneLine(name)) throw Object.assign(Object.assign(new Error("room name must fit on one line"), userErrorFields(userError("serverError.room.nameOneLine"))), { status: 400 });let section: string | undefined;if (body.section !== undefined && body.section !== null) {if (typeof body.section !== "string") throw Object.assign(new Error("context must be a string"), { status: 400 });@@ -3700,7 +3701,7 @@ function updateChannel(groupId: string, value: unknown): GroupRecord {const name = body.name.trim();if (!name) throw Object.assign(new Error("room name must not be empty"), { status: 400 });if (name.length > 100) throw Object.assign(new Error("room name must be at most 100 characters"), { status: 400 });- if (!fitsOnOneLine(name)) throw Object.assign(new Error("room name must fit on one line"), { status: 400 });+ if (!fitsOnOneLine(name)) throw Object.assign(Object.assign(new Error("room name must fit on one line"), userErrorFields(userError("serverError.room.nameOneLine"))), { status: 400 });patch.name = name;}if (body.bulletin !== undefined) {@@ -5906,12 +5907,10 @@ function cloudComputerTools(botId: string, owner: TurnOwner, boxId: string | nul/** `ask`: the person did not pick this computer themselves (an Auto pin), so the first screen call asks them once. */async function mountHostComputer(owner: TurnOwner, botId: string, providerSupportsLocal: boolean, onRejected: (failure: string, error?: unknown) => void, ask = false, journal = false) {if (!shouldMountLocalComputer({ requested: "local", hostPlatform: process.platform, providerSupportsLocal })) {- throw new Error(providerSupportsLocal- ? "bots can't use this computer on this system — choose another place for this bot to work"- : "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work");+ throw userErrorThrown(providerSupportsLocal ? "serverError.computer.systemUnsupported" : "serverError.computer.aiUnsupported");}const cua = desktopComputer.connection();- if (!cua) throw new Error(thisComputerNotReady());+ if (!cua) throw thisComputerNotReadyError();await bindTurnComputer(owner, "computer:host");autoVmClaims.set(owner.threadId, {owner, lazy: true, label: "this computer", onRejected,@@ -8558,7 +8557,7 @@ async function startTurn(const shareNote = skillsHost.shareNote(bot, threadId, Boolean(privateWorkspace));const startupRecovery = (opts?.automaticRecoveryIndex ?? 0) < startupBackups(liveBot ?? bot, cfg.automaticRecovery).length;const held = limitTakeover.heldAtStart(bot, { instanceId, model }, startupRecovery); // a limit or a sign-out already known: straight to an AI that can carry on, with the reset only when one was named- if (held) throw held.scope === "signed-out" ? new TurnAuthenticationRefusedError(`signed-out-${randomUUID()}`, `${engineName(instanceId)} is signed out.`, true) : new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, held.resetsAt, held.scope, true);+ if (held) throw held.scope === "signed-out" ? Object.assign(new TurnAuthenticationRefusedError(`signed-out-${randomUUID()}`, `${engineName(instanceId)} is signed out.`, true), userErrorFields(userError("serverError.engine.signedOut", { name: engineName(instanceId) }))) : new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, held.resetsAt, held.scope, true);const dispatch = await guardTurnDispatch(shareNote.after(savedSteps.dispatch.sendTurn(instance, personLine && !opts?.unattended && !opts?.app?.context && !guestConfined ? { botId: bot.id, message: userMessage, turnText: text, placePicked: wants === "local" && placeSource !== "auto-pin" } : null, {threadId,botId: bot.id,@@ -8731,7 +8730,7 @@ async function startTurn(role: "bot",kind: "activity",turnSucceeded: false,- tool: failedTurnTool(message, e instanceof PlaceUnavailableError ? { place: e.row } : e instanceof TurnUsageLimitRefusedError ? { limitResetsAt: e.resetsAt } : e instanceof TurnAuthenticationRefusedError ? { setup: true } : {}),+ tool: failedTurnTool(message, { ...(e instanceof PlaceUnavailableError ? { place: e.row } : e instanceof TurnUsageLimitRefusedError ? { limitResetsAt: e.resetsAt } : e instanceof TurnAuthenticationRefusedError ? { setup: true } : {}), text: startFailureText(e) }),});const personTurn = opts?.automationSource === undefined && !opts?.commsDepth && !opts?.cardContinuation, told = personTurn && takeoverScope === "signed-out" ? limitTakeover.tell(bot, bot.modelSelection, { scope: "signed-out" }) : null; // a limit or a sign-out is heard once a stretch, not once a turnif (told) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${told}`, ok: true, setup: true } });@@ -8893,7 +8892,7 @@ const limitClock = new LimitResetClock({ file: join(DATA_DIR, "limit-holds.json"waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine) => limitClock.blockedUntil(engine), resetAt: (engine) => limitClock.resetAt(engine), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => [...(store.bot(botId)?.fallback ?? []), ...(cfg.automaticRecovery?.backup ? [cfg.automaticRecovery.backup] : [])], signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => limitFailovers.record(failover) });const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine) => limitClock.blockedUntil(engine), signedOut: (engine) => limitTakeover.stillSignedOut(engine), engineName,threadModel: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection ?? null,- note: (threadId, line) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true } }),+ note: (threadId, line, text) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true, ...(text ? { nameCode: text.key, nameParams: text.params } : {}) } }),switchBack: ({ botId, threadId, from, to }) => {const current = store.projectBotForTask(botId, threadId), checked = current ? checkedTaskModelSwitch(current, from, false, false, true) : null;return Boolean(checked?.ok && store.switchTaskModel(botId, threadId, checked.selection, false, false, { ...hostedModels?.resetTask(to, checked.selection), rewound: true }));@@ -9589,7 +9588,7 @@ async function undoAppliedChange(res: ServerResponse, threadId: string, requestI} else if (card.webhookRequest || card.appTriggerRequest) {result = card.webhookRequest ? webhookRequests.undo({ botId, threadId, requestId }) : await appTriggers.undo({ botId, threadId, requestId });} else if (card.waitRequest) {- result = card.undone ? { claimed: true, state: "already_undone" } : cancelWaitFromCard(botWaits, store, { botId, threadId, messageId: message.id, waitId: card.waitRequest.waitId }) ? { claimed: true, state: "undone" } : { claimed: true, state: "invalid", error: "This wait has already ended.", status: 409 };+ result = card.undone ? { claimed: true, state: "already_undone" } : cancelWaitFromCard(botWaits, store, { botId, threadId, messageId: message.id, waitId: card.waitRequest.waitId }) ? { claimed: true, state: "undone" } : { claimed: true, state: "invalid", ...userError("serverError.wait.alreadyEnded"), status: 409 };} else if (card.profileRequest || card.modelRequest) {const undone = (card.profileRequest ? profileRequests : modelRequests).undo({ botId, threadId, requestId });if (undone.claimed && undone.state === "undone") {@@ -9606,7 +9605,7 @@ async function undoAppliedChange(res: ServerResponse, threadId: string, requestI}if (!result.claimed) return json(res, 409, { error: "Only a change that applied on its own can be undone here." });if (result.state === "invalid") {- return json(res, result.status, { error: result.error, ...(result.stale ? { code: "changed-since" } : {}) });+ return json(res, result.status, { error: result.error, ...userErrorFields(result), ...(result.stale ? { code: "changed-since" } : {}) });}if (result.state === "undone") {appendDecision(DATA_DIR, {diff --git a/server/limit-failover.ts b/server/limit-failover.tsindex cdce147f1f..64b6bd72b0 100644--- a/server/limit-failover.ts+++ b/server/limit-failover.ts@@ -1,3 +1,4 @@+import { type ServerText } from "../shared/server-text.ts";// A conversation whose engine hit its usage limit, or was signed out, continues on the configured backup, and goes back to// its own engine once that limit has reset or it is signed in again.import { readFileSync } from "node:fs";@@ -81,7 +82,7 @@ export interface LimitFailoverDeps {/** Switches the thread back; false when that is not allowed now (a busy thread, a permission change). */switchBack: (failover: LimitFailover) => boolean;/** One plain line in the conversation. */- note: (threadId: string, line: string) => void;+ note: (threadId: string, line: string, text?: ServerText) => void;engineName: (engine: string) => string;}@@ -129,7 +130,7 @@ export class LimitFailovers {if (row.why === "signed-out" && this.deps.signedOut?.(row.from.instanceId)) return false;if (!this.deps.switchBack(row)) return false;this.forget(threadId);- this.deps.note(threadId, backLine(this.deps.engineName(row.from.instanceId), row.why));+ this.deps.note(threadId, backLine(this.deps.engineName(row.from.instanceId), row.why), row.why === "signed-out" ? { key: "chat.notice.failoverSignedInAgain", params: { engine: this.deps.engineName(row.from.instanceId) } } : undefined);return true;}diff --git a/server/new-bot-defaults.ts b/server/new-bot-defaults.tsindex 97c09f6fec..e47d0d1d9d 100644--- a/server/new-bot-defaults.ts+++ b/server/new-bot-defaults.ts@@ -1,3 +1,4 @@+import { userErrorThrown } from "./user-errors.ts";import { z } from "zod";import { profilePatchSchema, fitsOnOneLine } from "./bot-profile.ts";import { EFFORT_LEVELS, MAUS_COLOR_NAMES } from "../shared/wire.ts";@@ -108,12 +109,14 @@ export type BotRoutineTemplate = NewBotDefaults["routines"][number];export type BotSkillTemplate = NewBotDefaults["skills"][number];/** The first thing wrong, as one sentence: a field's own message, else which field is not valid. */-function settingsError(error: z.ZodError): string {+function settingsError(error: z.ZodError): Error {const issue = error.issues[0];- if (!issue) return "These bot settings are not valid.";- if (issue.code === "unrecognized_keys") return `unsupported bot field: ${issue.keys[0] ?? "unknown"}`;+ if (!issue) return userErrorThrown("serverError.botDefaults.invalid");+ if (issue.code === "too_big" && issue.path[0] === "name") return userErrorThrown("serverError.botDefaults.nameLength");+ if (issue.code === "too_big" && issue.path[0] === "section") return userErrorThrown("serverError.botDefaults.sectionLength");+ if (issue.code === "unrecognized_keys") return new Error(`unsupported bot field: ${issue.keys[0] ?? "unknown"}`);const field = issue.path.join(".");- return field && issue.message.startsWith(String(issue.path[0])) ? issue.message : `${field || "the bot"} is not valid`;+ return new Error(field && issue.message.startsWith(String(issue.path[0])) ? issue.message : `${field || "the bot"} is not valid`);}export function resolveBotCreationDefaults(saved: NewBotDefaults | undefined, body: Record<string, unknown>) {@@ -122,14 +125,14 @@ export function resolveBotCreationDefaults(saved: NewBotDefaults | undefined, bo}const template = newBotDefaultsSchema.parse(body.useDefaults === false ? {} : saved ?? {});const checked = botDefaultsProfileSchema.safeParse(body.settings === undefined ? {} : body.settings);- if (!checked.success) throw Object.assign(new Error(settingsError(checked.error)), { status: 400 });+ if (!checked.success) throw Object.assign(settingsError(checked.error), { status: 400 });const explicit = checked.data;const profile = { ...template.profile, ...explicit };for (const key of ["name", "title", "description", "modelSelection", "section"] as const) {if (Object.hasOwn(body, key)) Object.assign(profile, { [key]: key === "section" && body[key] === null ? "" : body[key] });}const resolved = botDefaultsProfileSchema.safeParse(profile);- if (!resolved.success) throw Object.assign(new Error(settingsError(resolved.error)), { status: 400 });+ if (!resolved.success) throw Object.assign(settingsError(resolved.error), { status: 400 });if (!resolved.data.name?.trim()) delete resolved.data.name;return { ...template, profile: resolved.data };}diff --git a/server/postiz/connection.ts b/server/postiz/connection.tsindex fd10177683..9ab4a10d6f 100644--- a/server/postiz/connection.ts+++ b/server/postiz/connection.ts@@ -1,3 +1,4 @@+import { userError, type UserError } from "../user-errors.ts";// The `postiz` MCP server entry the Apps card manages: Postiz Cloud's OAuth endpoint for a sign-in, or a Postiz server's// key endpoint for an organisation API key. A saved key is sent only to the entry at the address it was saved for.import { POSTIZ_CLOUD, POSTIZ_SERVER } from "../../shared/postiz.ts";@@ -9,7 +10,7 @@ const SIGN_IN_PATH = "/mcp-oauth-dynamic";const KEY_PATH = "/mcp";const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);-export type PostizAddress = { ok: true; address: string } | { ok: false; error: string };+export type PostizAddress = { ok: true; address: string } | ({ ok: false } & UserError);/** https anywhere, plain http only to this computer (and never on a Cloud, whose own loopback is not the person's).* A pasted MCP address is accepted for its server; one with the key in it is refused, so the key never sits in config. */@@ -20,19 +21,17 @@ export function postizAddress(input: string | null | undefined, options: { loopbtry {url = new URL(raw);} catch {- return { ok: false, error: "Enter your Postiz server's address, starting with https://." };+ return { ok: false, ...userError("serverError.postiz.addressHttps") };}- if (url.protocol !== "https:" && url.protocol !== "http:") return { ok: false, error: "Enter your Postiz server's address, starting with https://." };- if (url.username || url.password) return { ok: false, error: "Leave any user name or password out of the Postiz address." };- if (url.search || url.hash) return { ok: false, error: "Enter the Postiz address without anything after ? or #." };+ if (url.protocol !== "https:" && url.protocol !== "http:") return { ok: false, ...userError("serverError.postiz.addressHttps") };+ if (url.username || url.password) return { ok: false, ...userError("serverError.postiz.addressNoCredentials") };+ if (url.search || url.hash) return { ok: false, ...userError("serverError.postiz.addressNoQuery") };if (url.protocol === "http:" && !(options.loopback && LOOPBACK.has(url.hostname))) {- return { ok: false, error: options.loopback- ? "Use an https:// address. Plain http:// works only for a Postiz server on this computer."- : "Use your Postiz server's https:// address." };+ return { ok: false, ...userError(options.loopback ? "serverError.postiz.addressLocalHttp" : "serverError.postiz.addressUseHttps") };}const path = url.pathname.replace(/\/+$/u, "");if (/\/(?:mcp|sse)\/[^/]+$/u.test(path)) {- return { ok: false, error: "That address has a key in it. Enter the server address alone, and paste the key in its own box." };+ return { ok: false, ...userError("serverError.postiz.addressContainsKey") };}return { ok: true, address: `${url.origin}${path.replace(/\/mcp(?:-oauth(?:-[a-z]+)?)?$/u, "")}` };}diff --git a/server/postiz/service.ts b/server/postiz/service.tsindex a1cafbddc0..7c91eeb9dd 100644--- a/server/postiz/service.ts+++ b/server/postiz/service.ts@@ -1,3 +1,4 @@+import { userError, userErrorFields } from "../user-errors.ts";// The Postiz connection as the Apps card and Settings → API keys see it. It is one `postiz` MCP server entry, so the// MCP gate, each bot's server selection and a Team Cloud's scopes treat it like any other.// Security: a key is checked before it is saved and only ever sent to the address it was saved for; no answer carries a@@ -11,7 +12,7 @@ import { isRemoteMcpServer, parseStoredMcpServer, type StoredMcpServer, type Stoimport { postizAddress, postizCloud, postizEntryMethod, postizKeyUrl, postizSignInUrl, savedPostizAddress } from "./connection.ts";export type PostizProblem = "address" | "unreachable" | "key_rejected" | "not_postiz" | "taken" | "busy" | "managed_policy";-export type PostizRefusal = { status: number; error: string; code: PostizProblem };+export type PostizRefusal = { status: number; error: string; errorKey?: string; errorParams?: import("../../shared/server-text.ts").ServerTextParams; code: PostizProblem };export type PostizKeyCheck = { ok: true; tools: number } | ({ ok: false } & PostizRefusal);export interface PostizDeps {@@ -117,7 +118,7 @@ export function createPostiz(deps: PostizDeps) {/** Initialize and tools/list with this key: nothing is saved, no tool runs. */const checkKey = async (rawAddress: string | undefined, key: string, signal?: AbortSignal): Promise<PostizKeyCheck> => {const address = postizAddress(rawAddress, { loopback: deps.loopback });- if (!address.ok) return { ok: false, status: 400, code: "address", error: address.error };+ if (!address.ok) return { ok: false, status: 400, code: "address", error: address.error, ...userErrorFields(address) };const target = server(postizKeyUrl(address.address), true);const refusal = deps.mcpPolicyRefusal(POSTIZ_SERVER, target);if (refusal) return { ok: false, status: 403, code: "managed_policy", error: refusal };@@ -132,7 +133,7 @@ export function createPostiz(deps: PostizDeps) {/** Sets the `postiz` entry up for Postiz Cloud's sign-in, still off: the MCP sign-in routes run the sign-in, and the* card turns it on once its tools load. */prepareSignIn(): { ok: true; status: PostizStatus } | ({ ok: false } & PostizRefusal) {- if (deps.mcpConfigBusy.get()) return { ok: false, status: 409, code: "busy", error: "MCP servers are being updated. Try again in a moment." };+ if (deps.mcpConfigBusy.get()) return { ok: false, status: 409, code: "busy", ...userError("serverError.postiz.mcpUpdating") };if (method() === "taken") return { ok: false, ...taken };const url = postizSignInUrl();const refusal = deps.mcpPolicyRefusal(POSTIZ_SERVER, server(url, false));@@ -150,7 +151,7 @@ export function createPostiz(deps: PostizDeps) {const cfg = deps.cfg();if (patch.postiz.url !== undefined) {const address = postizAddress(patch.postiz.url, { loopback: deps.loopback });- if (!address.ok) return { status: 400, code: "address", error: address.error };+ if (!address.ok) return { status: 400, code: "address", error: address.error, ...userErrorFields(address) };patch.postiz.url = address.address === postizCloud() ? "" : address.address;}const key = patch.postiz.key?.trim();@@ -182,7 +183,7 @@ export function createPostiz(deps: PostizDeps) {/** Signs out and removes the entry, with every person's own sign-in and key for it. The key itself is removed by* the save that stores it (the desktop's encrypted store, or this server's config). */async disconnect(): Promise<{ ok: true; status: PostizStatus } | ({ ok: false } & PostizRefusal)> {- if (deps.mcpConfigBusy.get()) return { ok: false, status: 409, code: "busy", error: "MCP servers are being updated. Try again in a moment." };+ if (deps.mcpConfigBusy.get()) return { ok: false, status: 409, code: "busy", ...userError("serverError.postiz.mcpUpdating") };const how = method();if (how === "taken") return { ok: false, ...taken };const current = entry();diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.tsindex d0cea49a5e..aa541211d6 100644--- a/server/quota-switch.test.ts+++ b/server/quota-switch.test.ts@@ -211,7 +211,7 @@ describe("quota switch", () => {expect(message).toMatchObject({ id: messageId, text: "how's the weather", dataContext: { cardId: "sales" } });expect(replyTo).toMatchObject({ id: quoted });expect(spoken).toEqual({});- expect(notices()).toContainEqual({ name: "notice: continuing on Codex after hitting the usage limit", ok: true });+ expect(notices()).toContainEqual({ name: "notice: continuing on Codex after hitting the usage limit", nameCode: "chat.notice.backupContinuingLimit", nameParams: { name: "Codex", engine: "Claude" }, ok: true });expect(told).toEqual([{ botId: bot.id, from: defaultSelection(), facts: { scope: "engine", backup: CODEX } }]);expect(moves, "so it goes back once the limit resets").toEqual([{ threadId: bot.threadId, from: defaultSelection(), to: CODEX }]);});@@ -231,7 +231,7 @@ describe("quota switch", () => {await limited({ messageId: said("hi") });expect(thread().modelSelection).toEqual({ instanceId: "claude", model: "claude-plan" });expect(resend).toHaveBeenCalledTimes(1);- expect(notices()).toContainEqual({ name: "notice: continuing on Claude claude-plan after hitting the usage limit", ok: true });+ expect(notices()).toContainEqual({ name: "notice: continuing on Claude claude-plan after hitting the usage limit", nameCode: "chat.notice.backupContinuingLimit", nameParams: { name: "Claude claude-plan", engine: "Claude" }, ok: true });expect(told[0]!.facts).toEqual({ scope: "credits", backup: { instanceId: "claude", model: "claude-plan" } });});@@ -332,7 +332,7 @@ describe("quota switch", () => {await ranOut(turn);expect(thread().modelSelection).toEqual(CODEX);expect(resend).not.toHaveBeenCalled();- expect(notices()).toEqual([{ name: "notice: switched to Codex. Your request is still under way here and continues on Codex.", ok: true }]);+ expect(notices()).toEqual([{ name: "notice: switched to Codex. Your request is still under way here and continues on Codex.", nameCode: "chat.notice.backupRequestUnderWay", nameParams: { name: "Codex" }, ok: true }]);});describe("an AI that is signed out", () => {@@ -362,7 +362,7 @@ describe("quota switch", () => {await signedOut({ messageId });expect(notices()).toEqual([{ name: `notice: ${NOTICE}`, ok: true, setup: true },- { name: "notice: continuing on Codex while Claude is signed out", ok: true },+ { name: "notice: continuing on Codex while Claude is signed out", nameCode: "chat.notice.backupContinuingSignedOut", nameParams: { name: "Codex", engine: "Claude" }, ok: true },]);expect(scopes).toEqual(["signed-out"]);expect(thread().modelSelection).toEqual(CODEX);diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex 2efb891deb..48033c9209 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -1,3 +1,4 @@+import { type ServerText } from "../shared/server-text.ts";// Security invariants: only an "answer" may name an engine (a decline, or typed words matching no option, is "Not now"),// so a bot's own shell with decline-only service trust can never switch the engine or resend the person's message.// A request the job runtime still holds is never sent again: the runtime reruns its root itself.@@ -100,9 +101,9 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {/** A second press while the engine is read is the same answer, never another. */const answering = new Map<string, Promise<QuotaAnswer>>();- const notice = (threadId: string, text: string, ok: boolean, setup = false): void => {+ const notice = (threadId: string, text: string, ok: boolean, setup = false, words?: ServerText): void => {// `notice:` makes it a status row every client shows, never a folded tool step; `setup`: signing in fixes it.- store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ok, ...(setup ? { setup: true } : {}) } });+ store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ...(words ? { nameCode: words.key, nameParams: words.params } : {}), ok, ...(setup ? { setup: true } : {}) } });};const openCard = (threadId: string): Message | undefined => store.messagesFor(threadId)@@ -172,19 +173,19 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {const why = scope === "signed-out" ? `while ${nameOf(current)} is signed out` : "after hitting the usage limit";const held = heldBy(botId, threadId, rootOf(threadId, request));const original = held ? undefined : resendable(store, threadId, request.messageId);- if (held === "card") notice(threadId, `switched to ${name}. Your request waits on a card above and continues on ${name} once you act on it.`, true);- else if (held === "runtime") notice(threadId, `switched to ${name}. Your request is still under way here and continues on ${name}.`, true);- else if (held === "busy") notice(threadId, `switched to ${name}. This conversation is working, so your message was not sent again.`, true);+ if (held === "card") notice(threadId, `switched to ${name}. Your request waits on a card above and continues on ${name} once you act on it.`, true, false, { key: "chat.notice.backupCardWaiting", params: { name } });+ else if (held === "runtime") notice(threadId, `switched to ${name}. Your request is still under way here and continues on ${name}.`, true, false, { key: "chat.notice.backupRequestUnderWay", params: { name } });+ else if (held === "busy") notice(threadId, `switched to ${name}. This conversation is working, so your message was not sent again.`, true, false, { key: "chat.notice.backupConversationBusy", params: { name } });else if (held === "question") {- notice(threadId, `switched to ${name}. A teammate's question is waiting for your answer in this conversation, so your message was not sent again. Answer it, then send your message again.`, false);+ notice(threadId, `switched to ${name}. A teammate's question is waiting for your answer in this conversation, so your message was not sent again. Answer it, then send your message again.`, false, false, { key: "chat.notice.backupQuestionWaiting", params: { name } });} else if (!original) {- notice(threadId, `switched to ${name}, but your message could not be found to send again. Send it again.`, false);+ notice(threadId, `switched to ${name}, but your message could not be found to send again. Send it again.`, false, false, { key: "chat.notice.backupMessageMissing", params: { name } });} else {- notice(threadId, `continuing on ${name} ${why}`, true);+ notice(threadId, `continuing on ${name} ${why}`, true, false, { key: scope === "signed-out" ? "chat.notice.backupContinuingSignedOut" : "chat.notice.backupContinuingLimit", params: { name, engine: nameOf(current) } });try {await deps.resend(botId, threadId, original, original.replyToId ? store.messagesFor(threadId).find((message) => message.id === original.replyToId) : undefined, spokenLineFields(original.via, original.callId));} catch (error) {- if (store.taskByThread(botId, threadId)) notice(threadId, `could not continue on ${name}: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`, false);+ if (store.taskByThread(botId, threadId)) notice(threadId, `could not continue on ${name}: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`, false, false, { key: "chat.notice.backupCouldNotContinue", params: { name, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) } });}}return true;diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 87445c24a7..c0eba4e851 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -418,14 +418,14 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerm = path.match(/^\/api\/bots\/([\w-]+)\/helper-followup$/);if (m && method === "POST") {const bot = store.bot(m[1]!);- if (!bot?.defaultBot || bot.hidden) return json(res, 404, { error: "no such MausBot" });- if (!mayFollowUp(bot, auth)) return json(res, 403, { error: "only MausBot's own person can do this" });+ if (!bot?.defaultBot || bot.hidden) return json(res, 404, { ...userError("serverError.setup.mausbotMissing") });+ if (!mayFollowUp(bot, auth)) return json(res, 403, { ...userError("serverError.setup.mausbotOwnerOnly") });const parsed = helperFollowupBody.safeParse(await readBody(req));if (!parsed.success) return json(res, 400, { error: "body must be { ai, apps?, threadId? }" });const threadId = parsed.data.threadId ?? bot.threadId;if (store.botByThread(threadId)?.id !== bot.id) return json(res, 404, { error: "no such conversation" });const next = helperFollowup(store.messagesFor(threadId), () => followupFacts(bot, parsed.data, store.bots, routines?.listRoutines() ?? []));- if (!next) return json(res, 409, { error: "this conversation has no intro to follow up" });+ if (!next) return json(res, 409, { ...userError("serverError.setup.noIntroToFollowUp") });if ("existing" in next) return json(res, 200, { message: next.existing });return json(res, 201, { message: store.appendMessage(threadId, next.append) });}diff --git a/server/routes/config.ts b/server/routes/config.tsindex e356b9b671..1736857ed1 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -39,7 +39,7 @@ import { parseSkillMd } from "../skills.ts";import type { Store } from "../store.ts";import * as tts from "../tts/index.ts";import * as vps from "../vps-computer.ts";-import { refusalBody, userError } from "../user-errors.ts";+import { refusalBody, userError, userErrorFields } from "../user-errors.ts";import type { ServerErrorBody } from "../../shared/server-text.ts";import type { Postiz } from "../postiz/service.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -366,7 +366,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {}}const postizRefusal = await postiz?.configCheck(patch);- if (postizRefusal) return json(res, postizRefusal.status, { error: postizRefusal.error, code: postizRefusal.code });+ if (postizRefusal) return json(res, postizRefusal.status, { error: postizRefusal.error, code: postizRefusal.code, ...userErrorFields(postizRefusal) });const newBoatToken = patch.box?.token;if (newBoatToken?.trim()) {const check = await boat.verifyToken(newBoatToken);diff --git a/server/routes/inbox.test.ts b/server/routes/inbox.test.tsindex 4268bc6b3d..3d1632fe09 100644--- a/server/routes/inbox.test.ts+++ b/server/routes/inbox.test.ts@@ -33,7 +33,7 @@ it("answers each member with their own inbox, which a client session may read anconst line = mine.body.rows[0].id as string;expect((await call("POST", `/api/inbox/${line}/read`)).body.rows[0]).toMatchObject({ unread: false, tab: "info" });expect((await call("POST", `/api/inbox/${line}/done`)).body.rows[0]).toMatchObject({ tab: "done" });- expect(await call("POST", `/api/inbox/${line}/done`, session(PHILIPP.email)), "someone else's line").toMatchObject({ status: 404 });+ expect(await call("POST", `/api/inbox/${line}/done`, session(PHILIPP.email)), "someone else's line").toMatchObject({ status: 404, body: { error: "That line is not in your inbox.", errorKey: "serverError.inbox.lineMissing" } });expect((await call("GET", "/api/inbox", session(PHILIPP.email))).body.rows).toEqual([]);expect(await call("DELETE", "/api/inbox")).toMatchObject({ status: 405 });expect((await call("GET", "/api/needs-you")).out).toBe(PASS);@@ -49,10 +49,10 @@ it("refuses to mark an open ask done, which only its answer settles", async () =f.team.route({ kind: "approval", botId: "reporter", botName: "Reporter", threadId: "rep-shared", title: "Reporter needs approval", body: "Run: rm -rf ./build" });const [ask] = (await call("GET", "/api/inbox")).body.rows;expect(ask).toMatchObject({ tab: "needs-you", card: { requestId: "req-1" } });- expect(await call("POST", `/api/inbox/${ask.id}/done`)).toMatchObject({ status: 409 });+ expect(await call("POST", `/api/inbox/${ask.id}/done`)).toMatchObject({ status: 409, body: { error: "This waits on your answer: answer it, or close it, where it asks.", errorKey: "serverError.inbox.answerRequired" } });});it("has no inbox off a team", async () => {const { call } = setup({ team: false });- expect(await call("GET", "/api/inbox")).toMatchObject({ status: 404 });+ expect(await call("GET", "/api/inbox")).toMatchObject({ status: 404, body: { error: "There is no inbox here.", errorKey: "serverError.inbox.missing" } });});diff --git a/server/routes/inbox.ts b/server/routes/inbox.tsindex 6955d6a3db..8555578f45 100644--- a/server/routes/inbox.ts+++ b/server/routes/inbox.ts@@ -1,3 +1,4 @@+import { userError } from "../user-errors.ts";import type { InboxView } from "../../shared/inbox.ts";import type { RequestAuth } from "../request-auth.ts";import { PASS, type RouteHandler } from "./table.ts";@@ -16,15 +17,15 @@ export function createInboxRoutes(deps: InboxRouteDeps): RouteHandler {if (path === "/api/inbox") {if (method !== "GET") return json(res, 405, { error: "method not allowed" });const view = deps.view(auth);- return view ? json(res, 200, view) : json(res, 404, { error: "There is no inbox here." });+ return view ? json(res, 200, view) : json(res, 404, { ...userError("serverError.inbox.missing") });}const m = /^\/api\/inbox\/([\w-]+)\/(read|done)$/.exec(path);if (!m) return PASS;if (method !== "POST") return json(res, 405, { error: "method not allowed" });const marked = m[2] === "read" ? (deps.markRead(auth, m[1]!) ? "done" : "unknown") : deps.markDone(auth, m[1]!);- if (marked === "unknown") return json(res, 404, { error: "That line is not in your inbox." });- if (marked === "an ask") return json(res, 409, { error: "This waits on your answer: answer it, or close it, where it asks." });+ if (marked === "unknown") return json(res, 404, { ...userError("serverError.inbox.lineMissing") });+ if (marked === "an ask") return json(res, 409, { ...userError("serverError.inbox.answerRequired") });const view = deps.view(auth);- return view ? json(res, 200, view) : json(res, 404, { error: "There is no inbox here." });+ return view ? json(res, 200, view) : json(res, 404, { ...userError("serverError.inbox.missing") });};}diff --git a/server/routes/instances.ts b/server/routes/instances.tsindex 52493d4c6d..3ec0cfb648 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -1,3 +1,4 @@+import { userError, userErrorFields } from "../user-errors.ts";import { randomUUID } from "node:crypto";import { providerIconError } from "../../shared/provider-icon.ts";import {@@ -237,7 +238,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {} catch (error) {const requestedStatus = error && typeof error === "object" ? (error as { status?: unknown }).status : undefined;const status = typeof requestedStatus === "number" && [400, 401, 404, 409, 413, 415].includes(requestedStatus) ? requestedStatus : 500;- return json(res, status, { error: error instanceof Error ? error.message : String(error) });+ return json(res, status, { error: error instanceof Error ? error.message : String(error), ...userErrorFields(error) });}}@@ -290,7 +291,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {resetPathCache();return json(res, 200, { ok: true, version: result.version });} catch (error) {- return json(res, 500, { error: error instanceof Error ? error.message : String(error) });+ return json(res, 500, { error: error instanceof Error ? error.message : String(error), ...userErrorFields(error) });} finally {claudeUpdatesInFlight.delete(target.cli);// Even a failed update may have replaced the executable.@@ -306,7 +307,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {return json(res, 415, { error: "content-type must be application/json" });}const parsed = instanceSettingsSchema.safeParse(await readBody(req, 16384));- if (!parsed.success) return json(res, 400, { error: "Supply a valid CLI path, account name, configuration directory, boolean tools setting or a reply wait of 1 to 60 minutes." });+ if (!parsed.success) return json(res, 400, { ...userError("serverError.instance.settingsInvalid") });const body = parsed.data;const instanceId = instancePatch[1];if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });@@ -330,7 +331,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {entry.config = { ...entry.config as Record<string, unknown>, tools: body.tools };}if (body.replyWaitMinutes !== undefined) {- if (entry.driver !== "openai-compat") return json(res, 400, { error: "The reply wait is available for OpenAI-compatible servers only." });+ if (entry.driver !== "openai-compat") return json(res, 400, { ...userError("serverError.instance.replyWaitUnsupported") });const { replyWaitMinutes: _previous, ...rest } = entry.config as Record<string, unknown>;entry.config = body.replyWaitMinutes === null ? rest : { ...rest, replyWaitMinutes: body.replyWaitMinutes };}@@ -375,7 +376,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {try { await providerAuthSessions.signOut(live, auth.kind === "session" ? auth.session.id : "loopback"); }catch (error) {if ((error as { code?: unknown }).code !== "chatgpt_revocation_unconfirmed") {- return json(res, 409, { error: error instanceof Error ? error.message : String(error) });+ return json(res, 409, { error: error instanceof Error ? error.message : String(error), ...userErrorFields(error) });}}}diff --git a/server/routes/mcp-servers.ts b/server/routes/mcp-servers.tsindex c9ff1a5178..f389a6fa5f 100644--- a/server/routes/mcp-servers.ts+++ b/server/routes/mcp-servers.ts@@ -1,3 +1,4 @@+import { userError } from "../user-errors.ts";import type { ChatAppsMcp } from "../chat-apps-mcp.ts";import type { CloudHomeConfig } from "../cloud-home.ts";import type { AppConfig } from "../config.ts";@@ -59,7 +60,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {const MAX_CONCURRENT_MCP_PROBES = 2;const personalHeaderRefusal = (name: string, server: StoredMcpServer) =>deps.teamConnections.personMcp().includes(name) && isRemoteMcpServer(server) && Object.values(server.headers).some((value) => value !== "")- ? "Personal MCP header values cannot be saved in shared configuration. Save your key in your personal connection."+ ? userError("serverError.mcp.personalHeadersShared"): null;let mcpProbesInFlight = 0;return async ({ req, res, path, method, auth, json, readBody }) => {@@ -90,7 +91,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {const personal = deps.teamConnections.personMcp().includes(name);if (personal && isRemoteMcpServer(target) && !target.oauth && Object.keys(target.headers).length > 0) {const member = auth.kind === "session" ? sessionMember(auth.session) : null;- if (!member) return json(res, 403, { error: "Sign in to the team to test your own connection." });+ if (!member) return json(res, 403, { ...userError("serverError.mcp.testSignInFirst") });const person = personKey({ id: "", email: member.member.email });oauth = deps.teamConnections.people.oauth(person);const key = deps.teamConnections.people.key(person, name, target.url);@@ -183,7 +184,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {const parsed = parseMcpServerMutation(name, mcpServerBody(body));if (!parsed.ok) return json(res, 400, { error: parsed.error });const personalRefusal = personalHeaderRefusal(name, parsed.server);- if (personalRefusal) return json(res, 400, { error: personalRefusal });+ if (personalRefusal) return json(res, 400, personalRefusal);const refusal = mcpPolicyRefusal(name, parsed.server);if (refusal) return json(res, 403, { error: refusal, code: "managed_policy" });persistMcpServers({ ...current, [name]: parsed.server });@@ -221,7 +222,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {return json(res, 400, { error: `You can add at most ${MAX_MCP_SERVERS} MCP servers.` });}const personalRefusal = names.map((name) => personalHeaderRefusal(name, parsed.servers[name]!)).find(Boolean);- if (personalRefusal) return json(res, 400, { error: personalRefusal });+ if (personalRefusal) return json(res, 400, personalRefusal);const refused = names.filter(name => mcpPolicyRefusal(name, parsed.servers[name] as object));if (refused.length) return json(res, 403, { error: `${mcpPolicyRefusal(refused[0]!, parsed.servers[refused[0]!] as object)} Not approved: ${refused.join(", ")}.`, code: "managed_policy" });persistMcpServers({ ...current, ...parsed.servers });@@ -270,7 +271,7 @@ export function createMcpServerRoutes(deps: McpServerRouteDeps): RouteHandler {const parsed = parseMcpServerMutation(name, body, existing.server);if (!parsed.ok) return json(res, 400, { error: parsed.error });const personalRefusal = personalHeaderRefusal(name, parsed.server);- if (personalRefusal) return json(res, 400, { error: personalRefusal });+ if (personalRefusal) return json(res, 400, personalRefusal);const refusal = mcpPolicyRefusal(name, parsed.server);if (refusal) return json(res, 403, { error: refusal, code: "managed_policy" });persistMcpServers({ ...current, [name]: parsed.server });diff --git a/server/routes/postiz.ts b/server/routes/postiz.tsindex 4a10b1d17b..22e9803fa0 100644--- a/server/routes/postiz.ts+++ b/server/routes/postiz.ts@@ -1,3 +1,4 @@+import { userError, userErrorFields } from "../user-errors.ts";// The Apps card's Postiz routes, for the owner or an admin (request-auth.ts leaves every one off a client's list):// GET /api/postiz the connection: how it signs in and where, never a key or a token// POST /api/postiz/sign-in the `postiz` server set up for Postiz Cloud's sign-in; /api/mcp/servers/postiz/sign-in runs it@@ -15,18 +16,18 @@ export function createPostizRoutes(deps: PostizRouteDeps): RouteHandler {const { postiz } = deps;return async ({ req, res, path, method, auth, json, readBody }) => {if (path !== "/api/postiz" && !path.startsWith("/api/postiz/")) return PASS;- if (!auth.scopes.includes("admin")) return json(res, 403, { error: "Only the owner or an admin can manage the Postiz connection." });+ if (!auth.scopes.includes("admin")) return json(res, 403, { ...userError("serverError.postiz.adminOnly") });res.setHeader("Cache-Control", "no-store");if (path === "/api/postiz") {if (method === "GET") return json(res, 200, postiz.status());if (method !== "DELETE") return json(res, 405, { error: "method not allowed" });const done = await postiz.disconnect();- return done.ok ? json(res, 200, done.status) : json(res, done.status, { error: done.error, code: done.code });+ return done.ok ? json(res, 200, done.status) : json(res, done.status, { error: done.error, code: done.code, ...userErrorFields(done) });}if (method !== "POST") return json(res, 405, { error: "method not allowed" });if (path === "/api/postiz/sign-in") {const prepared = postiz.prepareSignIn();- return prepared.ok ? json(res, 200, prepared.status) : json(res, prepared.status, { error: prepared.error, code: prepared.code });+ return prepared.ok ? json(res, 200, prepared.status) : json(res, prepared.status, { error: prepared.error, code: prepared.code, ...userErrorFields(prepared) });}if (path === "/api/postiz/check") {const controller = new AbortController();@@ -44,10 +45,10 @@ export function createPostizRoutes(deps: PostizRouteDeps): RouteHandler {}const body = await readBody(req, 8_192);const key = typeof body?.key === "string" ? body.key.trim() : "";- if (!key || key.length > 512 || /\s/u.test(key)) return json(res, 400, { error: "Paste the Postiz API key alone.", code: "key_rejected" });- if (body?.address !== undefined && typeof body.address !== "string") return json(res, 400, { error: "Send the Postiz address as text.", code: "address" });+ if (!key || key.length > 512 || /\s/u.test(key)) return json(res, 400, { ...userError("serverError.postiz.keyAlone"), code: "key_rejected" });+ if (body?.address !== undefined && typeof body.address !== "string") return json(res, 400, { ...userError("serverError.postiz.addressAsText"), code: "address" });const checked = await postiz.checkKey(body?.address, key);- return checked.ok ? json(res, 200, checked) : json(res, checked.status, { ok: false, error: checked.error, code: checked.code });+ return checked.ok ? json(res, 200, checked) : json(res, checked.status, { ok: false, error: checked.error, code: checked.code, ...userErrorFields(checked) });}return json(res, 404, { error: "not found" });};diff --git a/server/routes/secret-cards.test.ts b/server/routes/secret-cards.test.tsindex fe35f1f32a..4040ce35f2 100644--- a/server/routes/secret-cards.test.ts+++ b/server/routes/secret-cards.test.ts@@ -63,6 +63,14 @@ describe("POST /api/bots/<bot>/secret-cards/<card>/save", () => {expect(ctx.json).toHaveBeenCalledExactlyOnceWith(ctx.res, 200, { provided: true, resumed: true });});+ it("keeps the unowned conversation refusal as uncoded English", async () => {+ const { handler, saveCustomSecret } = route({ context: team(null, "p:bob") });+ const ctx = context({ threadId: "thread-1", value: "sk_live_canary" });+ await handler(ctx);+ expect(saveCustomSecret).not.toHaveBeenCalled();+ expect(ctx.json).toHaveBeenCalledExactlyOnceWith(ctx.res, 403, { error: "Only a workspace admin can enter this secret." });+ });+it.each([["a form post", { contentType: "text/plain" }, 415],["a conversation the session cannot see", { visible: false }, 404],diff --git a/server/routes/secret-cards.ts b/server/routes/secret-cards.tsindex d9ef094cb1..d3e4b80511 100644--- a/server/routes/secret-cards.ts+++ b/server/routes/secret-cards.ts@@ -1,3 +1,4 @@+import { userError } from "../user-errors.ts";// POST /api/bots/<bot>/secret-cards/<message>/provide with a phone's sealed envelope, .../save with {threadId, value}// for a custom secret typed in the app, and .../(provided|resume|dismiss) with {threadId}; and the agents tool's// /api/internal/request-credential. A value is never echoed back, logged or added to the card.@@ -21,13 +22,17 @@ export interface SecretAnswerContext {}/** Stricter than an ordinary card: only the conversation's own person, never another member or an admin on their behalf. */-export function secretAnswerRefusal(auth: RequestAuth, context: SecretAnswerContext): string | null {- if (auth.kind === "loopback") return auth.trust === "service" ? "A local service cannot enter a secret. Enter it in OpenMausBot." : null;+function codedSecretAnswerRefusal(auth: RequestAuth, context: SecretAnswerContext): { error: string } | null {+ if (auth.kind === "loopback") return auth.trust === "service" ? userError("serverError.secret.localService") : null;const admin = auth.scopes.includes("admin");- if (context.personalCloud) return admin ? null : "Only the owner of this Cloud can enter this secret.";+ if (context.personalCloud) return admin ? null : userError("serverError.secret.cloudOwnerOnly");if (!context.shared) return null;- if (context.owner) return context.owner === context.person ? null : "Only the person this conversation belongs to can enter this secret.";- return admin ? null : "Only a workspace admin can enter this secret.";+ if (context.owner) return context.owner === context.person ? null : userError("serverError.secret.conversationOwnerOnly");+ return admin ? null : { error: "Only a workspace admin can enter this secret." };+}++export function secretAnswerRefusal(auth: RequestAuth, context: SecretAnswerContext): string | null {+ return codedSecretAnswerRefusal(auth, context)?.error ?? null;}export interface SecretCardRouteDeps {@@ -51,9 +56,9 @@ export function createSecretCardRoutes(deps: SecretCardRouteDeps): RouteHandlerconst raw = await readBody(req, SECRET_VALUE_MAX_BYTES * 4);const fields = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : {};const threadId = String(fields.threadId ?? "");- if (!deps.threadVisible(auth, threadId) || !secretMessage(m[1]!, threadId, m[2]!)) return json(res, 404, { error: "no such credential request" });- const refusal = secretAnswerRefusal(auth, deps.answerContext(auth, m[1]!, threadId));- if (refusal) return json(res, 403, { error: refusal });+ if (!deps.threadVisible(auth, threadId) || !secretMessage(m[1]!, threadId, m[2]!)) return json(res, 404, { ...userError("serverError.secret.missing") });+ const refusal = codedSecretAnswerRefusal(auth, deps.answerContext(auth, m[1]!, threadId));+ if (refusal) return json(res, 403, refusal);const result = deps.cards.saveCustomSecret(m[1]!, threadId, m[2]!, fields.value);return json(res, result.status, result.body);}@@ -76,8 +81,8 @@ export function createSecretCardRoutes(deps: SecretCardRouteDeps): RouteHandlerreturn json(res, 400, { error: "The encrypted credential request is invalid" });}if (parsed.data.target === CUSTOM_SECRET_TARGET) {- const refusal = secretAnswerRefusal(auth, deps.answerContext(auth, m[1], parsed.data.threadId));- if (refusal) return json(res, 403, { error: refusal });+ const refusal = codedSecretAnswerRefusal(auth, deps.answerContext(auth, m[1], parsed.data.threadId));+ if (refusal) return json(res, 403, refusal);}const state = await provideSecretFromPhone({...parsed.data,@@ -94,47 +99,47 @@ export function createSecretCardRoutes(deps: SecretCardRouteDeps): RouteHandlerconst body = await readBody(req);const threadId = String(body.threadId ?? "");const message = secretMessage(m[1], threadId, m[2]);- if (!message?.secret) return json(res, 404, { error: "no such credential request" });+ if (!message?.secret) return json(res, 404, { ...userError("serverError.secret.missing") });if (phoneSecretSubmissions.has(phoneSecretSubmissionKey(threadId, message.id, message.secret.requestKey),)) {- return json(res, 409, { error: "this credential is currently being saved from a phone" });+ return json(res, 409, { ...userError("serverError.secret.credentialSavingFromPhone") });}if (m[3] === "provided") {- if (message.secret.dismissed) return json(res, 409, { error: "this credential request was dismissed" });- if (message.secret.superseded) return json(res, 409, { error: "this credential request was superseded by a newer one" });+ if (message.secret.dismissed) return json(res, 409, { ...userError("serverError.secret.credentialDismissed") });+ if (message.secret.superseded) return json(res, 409, { ...userError("serverError.secret.credentialSuperseded") });if (!secretSaved(message.secret)) {- return json(res, 409, { error: `${message.secret.label} was not saved yet` });+ return json(res, 409, { ...userError("serverError.secret.notSavedYet", { label: message.secret.label }) });}if (!resumeSecretCard(m[1], threadId, message.id, "provided")) {- return json(res, 409, { error: "this credential request is no longer available" });+ return json(res, 409, { ...userError("serverError.secret.unavailableLower") });}const state = currentSecretState(m[1], threadId, message.id);- if (!state) return json(res, 409, { error: "this credential request is no longer available" });+ if (!state) return json(res, 409, { ...userError("serverError.secret.unavailableLower") });return json(res, 200, state);}if (m[3] === "resume") {- if (message.secret.superseded) return json(res, 409, { error: "this credential request was superseded by a newer one" });+ if (message.secret.superseded) return json(res, 409, { ...userError("serverError.secret.credentialSuperseded") });const outcome = credentialResumeOutcome(message.secret);if (!outcome) {- return json(res, 409, { error: "this credential request is not ready to resume" });+ return json(res, 409, { ...userError("serverError.secret.notReadyToResume") });}if (outcome === "provided" && !secretSaved(message.secret)) {- return json(res, 409, { error: `${message.secret.label} is no longer configured` });+ return json(res, 409, { ...userError("serverError.secret.noLongerConfigured", { label: message.secret.label }) });}if (!resumeSecretCard(m[1], threadId, message.id, outcome)) {- return json(res, 409, { error: "this credential request is no longer available" });+ return json(res, 409, { ...userError("serverError.secret.unavailableLower") });}const state = currentSecretState(m[1], threadId, message.id);- if (!state) return json(res, 409, { error: "this credential request is no longer available" });+ if (!state) return json(res, 409, { ...userError("serverError.secret.unavailableLower") });return json(res, 200, { resumed: state.resumed });}- if (message.secret.superseded) return json(res, 409, { error: "this credential request was superseded by a newer one" });+ if (message.secret.superseded) return json(res, 409, { ...userError("serverError.secret.credentialSuperseded") });if (!message.secret.provided && !resumeSecretCard(m[1], threadId, message.id, "dismissed")) {- return json(res, 409, { error: "this credential request is no longer available" });+ return json(res, 409, { ...userError("serverError.secret.unavailableLower") });}const state = currentSecretState(m[1], threadId, message.id);- if (!state) return json(res, 409, { error: "this credential request is no longer available" });+ if (!state) return json(res, 409, { ...userError("serverError.secret.unavailableLower") });return json(res, 200, { dismissed: true, resumed: state.resumed });}return PASS;diff --git a/server/routes/setup-request.test.ts b/server/routes/setup-request.test.tsindex c5118686fd..c1425e01cf 100644--- a/server/routes/setup-request.test.ts+++ b/server/routes/setup-request.test.ts@@ -80,7 +80,7 @@ describe("the Set me up route", () => {const s = setup(null, { hold: new Promise<void>((resolve) => { release = resolve; }) });const first = s.call("POST", { threadId: s.bot.threadId, text: "Research and digging into topics" });await Promise.resolve();- expect(await s.call("POST", { threadId: s.bot.threadId, text: "Research and digging into topics" })).toEqual({ status: 409, body: { error: "That answer is already on its way." } });+ expect(await s.call("POST", { threadId: s.bot.threadId, text: "Research and digging into topics" })).toEqual({ status: 409, body: { error: "That answer is already on its way.", errorKey: "serverError.chat.answerSent" } });expect(await s.call("POST", { threadId: s.bot.threadId })).toMatchObject({ status: 409 });release();expect(await first).toMatchObject({ status: 200 });diff --git a/server/routes/setup-request.ts b/server/routes/setup-request.tsindex e24964d9f6..482eea89a5 100644--- a/server/routes/setup-request.ts+++ b/server/routes/setup-request.ts@@ -52,7 +52,7 @@ export function createSetupRequestRoutes(deps: SetupRequestRouteDeps): RouteHand}if (deps.store.taskByThread(botId, threadId) && !deps.canSetUp(botId, threadId)) return json(res, 409, userError("serverError.setup.noTools"));const key = `${botId}:${threadId}`;- if (picking.has(key)) return json(res, 409, { error: "That answer is already on its way." });+ if (picking.has(key)) return json(res, 409, { ...userError("serverError.chat.answerSent") });const asked = askForSetup(deps.store, botId, threadId, deps.language(), deps.presser(auth), picked !== undefined);if (!asked.ok) return json(res, asked.status, refusalBody(asked));if (picked === undefined) return json(res, 200, asked);diff --git a/server/routes/sidebar-sections.ts b/server/routes/sidebar-sections.tsindex 3dfba67932..7bc3df18a5 100644--- a/server/routes/sidebar-sections.ts+++ b/server/routes/sidebar-sections.ts@@ -61,10 +61,9 @@ export function createSidebarSectionRoutes(deps: SidebarSectionRouteDeps): Route}}const result = store.updateTeamMembers(section, parsed.data.addBotIds, parsed.data.removeBotIds);- if (!result.ok) return json(res, result.reason === "unavailable" ? 404 : 409, { error:- result.reason === "chief-conflict" ? "A department can have only one Chief of Staff. Change the Chief before moving this bot."- : result.reason === "membership-changed" ? "Department membership changed. Reopen the dialog and try again."- : "One or more bots are unavailable" });+ if (!result.ok) return json(res, result.reason === "unavailable" ? 404 : 409, result.reason === "chief-conflict" ? userError("serverError.department.moveChiefConflict")+ : result.reason === "membership-changed" ? userError("serverError.department.membershipChanged")+ : { error: "One or more bots are unavailable" });return json(res, 200, { sections: store.sections, bots: result.bots.map(wireBot) });}if (method === "POST" && path === "/api/sidebar-sections") {diff --git a/server/routes/team-connections.ts b/server/routes/team-connections.tsindex eadae101b4..81bbe7b88d 100644--- a/server/routes/team-connections.ts+++ b/server/routes/team-connections.ts@@ -1,3 +1,4 @@+import { userError } from "../user-errors.ts";// A Team Cloud's connections, the team's or each person's.// PUT /api/team/connection-scopes { kind: "app" | "mcp", id, scope: "team" | "person" } an admin: who connects it// GET /api/team/my-connections the person's own, and what is theirs to connect@@ -146,9 +147,9 @@ export function createTeamConnectionRoutes(deps: TeamConnectionRouteDeps): Routeconst body = await readBody(req, 4096);const value = typeof body?.value === "string" ? body.value.trim() : "";if (value.length < 8 || value.length > 512 || !/^[\x21-\x7e]+(?: [\x21-\x7e]+)?$/.test(value)) return json(res, 400, { error: "Paste the key alone." });- if (body?.url !== undefined && (typeof body.url !== "string" || !body.url)) return json(res, 400, { error: "Send the MCP server address as text." });+ if (body?.url !== undefined && (typeof body.url !== "string" || !body.url)) return json(res, 400, { ...userError("serverError.mcp.addressAsText") });const current = server(name);- if (!current || !isRemoteMcpServer(current) || (body?.url !== undefined && current.url !== body.url)) return json(res, 409, { error: "The MCP server address changed. Reload the server and try again." });+ if (!current || !isRemoteMcpServer(current) || (body?.url !== undefined && current.url !== body.url)) return json(res, 409, { ...userError("serverError.mcp.addressChanged") });const headerKeys = Object.keys(current.headers);deps.host.people.putKey(person, email, name, { url: current.url, ...personKeyHeader(headerKeys, value) });return json(res, 200, { ok: true });diff --git a/server/routes/threads.ts b/server/routes/threads.tsindex 7b45b2f245..44a3bf1139 100644--- a/server/routes/threads.ts+++ b/server/routes/threads.ts@@ -1,3 +1,4 @@+import { userError } from "../user-errors.ts";import { basename, join } from "node:path";import type { WireBot, WireGroup } from "../../shared/wire.ts";@@ -376,7 +377,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {if (m && method === "DELETE") {const name = m[1]!;if (!UPLOADED_NAME.test(name) || !deps.uploads.owns(auth, name)) return json(res, 404, { error: "no such attachment" });- if (deps.attachmentInUse(name)) return json(res, 409, { error: "This file is already in a message, so it stays." });+ if (deps.attachmentInUse(name)) return json(res, 409, { ...userError("serverError.attachment.alreadyInMessage") });deleteAttachment(join(ATTACHMENTS_DIR, name));return json(res, 200, { ok: true });}diff --git a/server/routine-lines.ts b/server/routine-lines.tsindex 8595f83ed8..a08e0a3dbe 100644--- a/server/routine-lines.ts+++ b/server/routine-lines.ts@@ -19,6 +19,7 @@ export const ROUTINE_LINE = {"routines.server.part.rateLimited": "a rate limit","routines.server.part.provider": "a temporary error","routines.server.part.failed": "a failure",+ "routines.server.backupSignedOut": "Starting again on the backup AI: this bot's AI is signed out",} as const;export type RoutineLineKey = keyof typeof ROUTINE_LINE;diff --git a/server/routine-recovery.ts b/server/routine-recovery.tsindex 5b5f48100c..0f3ab135e6 100644--- a/server/routine-recovery.ts+++ b/server/routine-recovery.ts@@ -189,7 +189,7 @@ export function recoverRun(run: RoutineRun, failure: string, facts: RoutineFailu}// A signed-out AI's run starts again on the backup the person chose; its start there says once that it needs signing in.if (verdict.cause === "signed_out" && facts.backupReady && requeueOnce(run, "failed", failure, now, now + RETRY_MS)) {- run.attention = "Starting again on the backup AI: this bot's AI is signed out";+ attend(run, codedLine("attention", "routines.server.backupSignedOut"));return { queued: true };}const first = firstNotice(notices, run.botId, verdict.cause, now);diff --git a/server/start-failure-text.test.ts b/server/start-failure-text.test.tsnew file mode 100644index 0000000000..823c4c5bb7--- /dev/null+++ b/server/start-failure-text.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import { chatNotice } from "./chat-notices.ts";+import { createDesktopComputer, DESKTOP_COMPUTER_GRANT, thisComputerNotReady, thisComputerNotReadyError } from "./desktop-computer.ts";+import { startFailureText } from "./start-failure-text.ts";+import { userErrorFields, userErrorThrown, type UserErrorKey } from "./user-errors.ts";++const pairs: Array<[UserErrorKey, string]> = [+ ["serverError.computer.desktopOnly", "chat.notice.computerDesktopOnly"],+ ["serverError.computer.permissionsThenRestart", "chat.notice.computerPermissionsThenRestart"],+ ["serverError.computer.notReadyDetail", "chat.notice.computerNotReadyDetail"],+ ["serverError.computer.notReadyMacPermission", "chat.notice.computerNotReadyMacPermission"],+ ["serverError.computer.systemUnsupported", "chat.notice.computerSystemUnsupported"],+ ["serverError.computer.aiUnsupported", "chat.notice.computerAiUnsupported"],+ ["serverError.engine.signedOut", "chat.notice.engineSignedOut"],+];++describe("coded start failures", () => {+ it.each(pairs)("carries %s to its notice without recognizing a message", (errorKey, noticeKey) => {+ const error = userErrorThrown(errorKey, { name: "Fixture AI", reason: "Fixture permission" });+ const words = startFailureText(error)!;+ expect(words.key).toBe(noticeKey);+ expect(words.params).toEqual(userErrorFields(error).errorParams);+ expect(chatNotice(noticeKey as Parameters<typeof chatNotice>[0], words.params)).toBe(error.message);+ expect(startFailureText(new Error(error.message))).toBeUndefined();+ });++ it.each([null, undefined, new Error("vendor failure"), userErrorThrown("serverError.secret.missing")])("does not classify a different failure: %s", (error) => {+ expect(startFailureText(error)).toBeUndefined();+ });++ it("keeps the uncoded diagnostic's exact English for each desktop grant state", () => {+ const desktop = createDesktopComputer({ platform: "darwin" });+ const check = (key: UserErrorKey) => {+ const error = thisComputerNotReadyError(desktop, "darwin");+ expect(error.message).toBe(thisComputerNotReady(desktop, "darwin"));+ expect(userErrorFields(error).errorKey).toBe(key);+ };+ check("serverError.computer.desktopOnly");+ desktop.receive({ type: DESKTOP_COMPUTER_GRANT, connection: null });+ check("serverError.computer.permissionsThenRestart");+ for (const [reason, key] of [["Fixture driver unavailable", "serverError.computer.notReadyDetail"], ["Screen Recording required", "serverError.computer.notReadyMacPermission"]] as const) {+ desktop.receive({ type: DESKTOP_COMPUTER_GRANT, connection: { mode: "unavailable", reason } });+ check(key);+ }+ });+});diff --git a/server/start-failure-text.ts b/server/start-failure-text.tsnew file mode 100644index 0000000000..448f9fcc7c--- /dev/null+++ b/server/start-failure-text.ts@@ -0,0 +1,18 @@+import type { ServerText } from "../shared/server-text.ts";+import { userErrorFields } from "./user-errors.ts";++const START_FAILURE = {+ "serverError.computer.desktopOnly": "chat.notice.computerDesktopOnly",+ "serverError.computer.permissionsThenRestart": "chat.notice.computerPermissionsThenRestart",+ "serverError.computer.notReadyDetail": "chat.notice.computerNotReadyDetail",+ "serverError.computer.notReadyMacPermission": "chat.notice.computerNotReadyMacPermission",+ "serverError.computer.systemUnsupported": "chat.notice.computerSystemUnsupported",+ "serverError.computer.aiUnsupported": "chat.notice.computerAiUnsupported",+ "serverError.engine.signedOut": "chat.notice.engineSignedOut",+} as const;++export function startFailureText(error: unknown): ServerText | undefined {+ const fields = userErrorFields(error);+ if (!fields.errorKey || !Object.hasOwn(START_FAILURE, fields.errorKey)) return undefined;+ return { key: START_FAILURE[fields.errorKey as keyof typeof START_FAILURE], ...(fields.errorParams ? { params: fields.errorParams } : {}) };+}diff --git a/server/user-errors.ts b/server/user-errors.tsindex cb9b39c9f2..0790c76901 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -104,6 +104,93 @@ export const USER_ERROR = {"serverError.approval.pending": "Finish this bot's pending approval change first","serverError.approval.provider": "Use the bot's provider on this thread before applying its approval level","serverError.engineCheck.timeout": "{name} didn't answer within {seconds} seconds.",+ "serverError.request.bodyTimeout": "The request took too long. Check the connection and try again.",+ "serverError.browser.restartingUnresponsive": "The browser stopped responding, so it is being restarted. The live view reconnects by itself.",+ "serverError.computer.desktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.",+ "serverError.computer.permissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it",+ "serverError.computer.notReadyDetail": "OpenMausBot can't use this computer yet — {reason}",+ "serverError.computer.notReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.",+ "serverError.install.invalidDetails": "{name}'s install details are invalid. Nothing was downloaded.",+ "serverError.install.versionGone": "This version of {name} is no longer available to download. Update OpenMausBot, then try again.",+ "serverError.install.downloadLimited": "The download site is limiting downloads right now. Try again in a few minutes.",+ "serverError.install.siteNotAnswering": "{name}'s download site isn't answering right now. Try again later.",+ "serverError.install.downloadFailed": "{name} couldn't be downloaded. Check the internet connection and try again.",+ "serverError.install.downloadTooLarge": "The {name} download was larger than expected, so it was stopped. Nothing was installed.",+ "serverError.install.unofficialDownload": "The {name} download did not come from its official site, so it was stopped. Nothing was installed.",+ "serverError.install.redirects": "The {name} download kept redirecting, so it was stopped. Nothing was installed.",+ "serverError.install.safetyCheck": "The {name} download failed its safety check, so nothing was installed. Try again later.",+ "serverError.install.downloadTimeout": "The {name} download took too long and was stopped. Check the internet connection and try again.",+ "serverError.install.unsafeArchive": "The archive contains an unexpected or unsafe file. Nothing was installed.",+ "serverError.install.unsafeFile": "The {name} download holds an unexpected or unsafe file, so nothing was installed.",+ "serverError.install.notPlainFolder": "OpenMausBot's folder for {name} is not a plain folder ({path}), so nothing was changed. Move it away, then try again.",+ "serverError.install.unexpectedFolder": "OpenMausBot's folder for {name} holds something it did not put there ({path}), so nothing was changed. Move it away, then try again.",+ "serverError.install.diskSpace": "There is not enough free disk space to install {name}. Free up about {megabytes} MB, then try again.",+ "serverError.install.openElsewhere": "{name} is open in another window. Close it, then try again.",+ "serverError.install.cannotWrite": "OpenMausBot can't write to its folder for {name}. Check the folder's permissions, then try again.",+ "serverError.install.failed": "{name} couldn't be installed. Try again.",+ "serverError.install.noDownload": "{name} has no download for this computer.",+ "serverError.install.existingDoesNotStart": "{name} is installed, but it doesn't start on this computer ({failure}). Nothing was changed.",+ "serverError.install.programMissing": "The {name} download did not contain the program it should, so nothing was installed.",+ "serverError.install.notSigned": "The downloaded {name} is not signed by its maker, so nothing was installed.",+ "serverError.install.downloadDoesNotStart": "{name} was downloaded, but it doesn't start on this computer ({failure}). Nothing was installed.",+ "serverError.secret.missing": "no such credential request",+ "serverError.secret.settingsCard": "this card saves a key in Settings",+ "serverError.secret.savingFromPhone": "this secret is currently being saved from a phone",+ "serverError.secret.declined": "this request was declined",+ "serverError.secret.replaced": "this request was replaced by a newer one",+ "serverError.secret.taskStopped": "this request stopped with its task",+ "serverError.secret.alreadySaved": "this secret was already saved",+ "serverError.secret.valueSize": "Enter the secret: up to {bytes} bytes.",+ "serverError.secret.notKeptSafely": "The secret could not be kept safely. Nothing was saved.",+ "serverError.secret.unavailableLower": "this credential request is no longer available",+ "serverError.signIn.requestMissing": "no such sign-in request",+ "serverError.signIn.requestReplaced": "this sign-in request was superseded by a newer one",+ "serverError.signIn.answeredInChat": "this sign-in request was already answered in the chat",+ "serverError.signIn.alreadyDone": "this sign-in request was already marked done",+ "serverError.signIn.alreadyCancelled": "this sign-in request was already cancelled",+ "serverError.inbox.answerNotPassed": "That answer can't be passed back.",+ "serverError.room.nameOneLine": "room name must fit on one line",+ "serverError.computer.systemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work",+ "serverError.computer.aiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",+ "serverError.wait.alreadyEnded": "This wait has already ended.",+ "serverError.botDefaults.nameLength": "name must be at most 100 characters",+ "serverError.botDefaults.sectionLength": "section must be at most 60 characters",+ "serverError.botDefaults.invalid": "These bot settings are not valid.",+ "serverError.postiz.addressHttps": "Enter your Postiz server's address, starting with https://.",+ "serverError.postiz.addressNoCredentials": "Leave any user name or password out of the Postiz address.",+ "serverError.postiz.addressNoQuery": "Enter the Postiz address without anything after ? or #.",+ "serverError.postiz.addressLocalHttp": "Use an https:// address. Plain http:// works only for a Postiz server on this computer.",+ "serverError.postiz.addressUseHttps": "Use your Postiz server's https:// address.",+ "serverError.postiz.addressContainsKey": "That address has a key in it. Enter the server address alone, and paste the key in its own box.",+ "serverError.postiz.mcpUpdating": "MCP servers are being updated. Try again in a moment.",+ "serverError.setup.mausbotMissing": "no such MausBot",+ "serverError.setup.mausbotOwnerOnly": "only MausBot's own person can do this",+ "serverError.setup.noIntroToFollowUp": "this conversation has no intro to follow up",+ "serverError.inbox.missing": "There is no inbox here.",+ "serverError.inbox.lineMissing": "That line is not in your inbox.",+ "serverError.inbox.answerRequired": "This waits on your answer: answer it, or close it, where it asks.",+ "serverError.instance.settingsInvalid": "Supply a valid CLI path, account name, configuration directory, boolean tools setting or a reply wait of 1 to 60 minutes.",+ "serverError.instance.replyWaitUnsupported": "The reply wait is available for OpenAI-compatible servers only.",+ "serverError.mcp.personalHeadersShared": "Personal MCP header values cannot be saved in shared configuration. Save your key in your personal connection.",+ "serverError.mcp.testSignInFirst": "Sign in to the team to test your own connection.",+ "serverError.postiz.adminOnly": "Only the owner or an admin can manage the Postiz connection.",+ "serverError.postiz.keyAlone": "Paste the Postiz API key alone.",+ "serverError.postiz.addressAsText": "Send the Postiz address as text.",+ "serverError.secret.localService": "A local service cannot enter a secret. Enter it in OpenMausBot.",+ "serverError.secret.cloudOwnerOnly": "Only the owner of this Cloud can enter this secret.",+ "serverError.secret.conversationOwnerOnly": "Only the person this conversation belongs to can enter this secret.",+ "serverError.secret.credentialSavingFromPhone": "this credential is currently being saved from a phone",+ "serverError.secret.credentialDismissed": "this credential request was dismissed",+ "serverError.secret.credentialSuperseded": "this credential request was superseded by a newer one",+ "serverError.secret.notSavedYet": "{label} was not saved yet",+ "serverError.secret.notReadyToResume": "this credential request is not ready to resume",+ "serverError.secret.noLongerConfigured": "{label} is no longer configured",+ "serverError.department.moveChiefConflict": "A department can have only one Chief of Staff. Change the Chief before moving this bot.",+ "serverError.department.membershipChanged": "Department membership changed. Reopen the dialog and try again.",+ "serverError.mcp.addressAsText": "Send the MCP server address as text.",+ "serverError.mcp.addressChanged": "The MCP server address changed. Reload the server and try again.",+ "serverError.attachment.alreadyInMessage": "This file is already in a message, so it stays.",+ "serverError.engine.signedOut": "{name} is signed out.",} as const;export type UserErrorKey = keyof typeof USER_ERROR;diff --git a/server/wait-host.test.ts b/server/wait-host.test.tsindex 73617203ec..9b1272b064 100644--- a/server/wait-host.test.ts+++ b/server/wait-host.test.ts@@ -58,9 +58,9 @@ describe("the store side of waits", () => {});it("posts a wait's line once, marks the chat unread and notifies only when it fired", () => {- expect(host.post(wait, { status: "fired", text: "the build: done. ci passed." })).toBe(true);- expect(host.post(wait, { status: "fired", text: "the build: done. ci passed." })).toBe(true);- expect(store.lines).toEqual([{ role: "bot", kind: "text", text: "the build: done. ci passed.", wait: { id: "w1", status: "fired" } }]);+ expect(host.post(wait, { status: "fired", text: "the build: done. /tmp/x is there now." })).toBe(true);+ expect(host.post(wait, { status: "fired", text: "the build: done. /tmp/x is there now." })).toBe(true);+ expect(store.lines).toEqual([{ role: "bot", kind: "text", text: "the build: done. /tmp/x is there now.", textCode: "chat.notice.waitDone.fileExists", textParams: { label: "the build", path: "/tmp/x" }, wait: { id: "w1", status: "fired" } }]);expect(store.patchTask).toHaveBeenCalledWith("bot-1", "t-1", { unread: true });expect(wrote).toHaveBeenCalledTimes(1);host.post({ ...wait, id: "w2" }, { status: "expired", text: "Stopped waiting for the build after 24 hours." });diff --git a/server/wait-host.ts b/server/wait-host.tsindex 6045be5d97..0205f4d010 100644--- a/server/wait-host.ts+++ b/server/wait-host.ts@@ -1,3 +1,5 @@+import { waitNoticeText } from "./wait-notice-text.ts";+import { redactParams } from "../shared/redact.ts";import type { Notification } from "../shared/notification.ts";import { buildNotification } from "./notify.ts";import type { RoutineManager, RoutineRun } from "./routines.ts";@@ -62,7 +64,8 @@ export function createWaitHost(deps: WaitHostDeps): Pick<WaitManagerOptions, "soif (deps.threadBusy(wait.botId, wait.threadId)) return false;const posted = store.messagesFor(wait.threadId).some((m) => m.wait?.id === wait.id && m.wait.status === notice.status);if (posted) return true;- store.appendMessage(wait.threadId, { role: "bot", kind: "text", text: notice.text, wait: { id: wait.id, status: notice.status } });+ const words = waitNoticeText(wait, notice);+ store.appendMessage(wait.threadId, { role: "bot", kind: "text", text: notice.text, textCode: words?.key, textParams: words?.params && redactParams(words.params), wait: { id: wait.id, status: notice.status } });store.patchTask(wait.botId, wait.threadId, { unread: true });deps.wrote(bot, wait.threadId);if (notice.status === "fired") deps.notify(buildNotification("wait", bot, wait.threadId, notice.text, { avatarUrl: bot.avatarUrl }));diff --git a/server/wait-notice-text.test.ts b/server/wait-notice-text.test.tsnew file mode 100644index 0000000000..692a13747a--- /dev/null+++ b/server/wait-notice-text.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from "vitest";+import { chatNotice } from "./chat-notices.ts";+import { waitNoticeText } from "./wait-notice-text.ts";+import type { WaitCondition, WaitRecord } from "./waits.ts";++const HOUR = 3_600_000;+const wait = (condition: WaitCondition): WaitRecord => ({ id: "w", botId: "b", threadId: "t", label: "the build", condition, createdAt: 100, expiresAt: 100 + HOUR, nextCheckAt: 100, errors: 0 });+const cases: Array<[WaitCondition, string, string]> = [+ [{ kind: "url_contains", url: "https://example.test/build", text: "Ready" }, "urlContains", "https://example.test/build now says “Ready”."],+ [{ kind: "url_missing", url: "https://example.test/build", text: "Building", sawText: true }, "urlMissing", "https://example.test/build no longer says “Building”."],+ [{ kind: "file_exists", path: "/fixture/Report.txt" }, "fileExists", "/fixture/Report.txt is there now."],+ [{ kind: "file_missing", path: "/fixture/Report.txt" }, "fileMissing", "/fixture/Report.txt is gone."],+ [{ kind: "file_changed", path: "/fixture/Report.txt", before: null }, "fileChanged", "/fixture/Report.txt changed."],+ [{ kind: "process_running", process: "CaseSensitiveBuild" }, "processRunning", "CaseSensitiveBuild is running."],+ [{ kind: "process_gone", process: "CaseSensitiveBuild" }, "processGone", "CaseSensitiveBuild stopped."],+ [{ kind: "bot_idle", botId: "peer", botName: "Scout", sawBusy: true }, "botIdle", "Scout finished."],+];++describe("wait notice codes", () => {+ it.each(cases)("rebuilds the unchanged fired line for %j", (condition, suffix, detail) => {+ const text = `the build: done. ${detail}`;+ const words = waitNoticeText(wait(condition), { status: "fired", text })!;+ expect(words.key).toBe(`chat.notice.waitDone.${suffix}`);+ expect(chatNotice(words.key as Parameters<typeof chatNotice>[0], words.params)).toBe(text);+ });++ it.each([1, 24])("rebuilds expiration after %i hours", (hours) => {+ const record = wait({ kind: "file_exists", path: "/fixture/Report.txt" });+ record.expiresAt = record.createdAt + hours * HOUR;+ const text = `Stopped waiting for the build after ${hours} hour${hours === 1 ? "" : "s"}.`;+ const words = waitNoticeText(record, { status: "expired", text })!;+ expect(words.key).toBe(hours === 1 ? "chat.notice.waitExpiredOne" : "chat.notice.waitExpiredMany");+ expect(chatNotice(words.key as Parameters<typeof chatNotice>[0], words.params)).toBe(text);+ });++ it("codes only a known reason for a stopped wait, without recognizing English", () => {+ const notice = { status: "stopped", text: "Stopped waiting for the build: Scout no longer exists." } as const;+ const words = waitNoticeText(wait({ kind: "bot_idle", botId: "peer", botName: "Scout", sawBusy: true }), notice)!;+ expect(words.key).toBe("chat.notice.waitBotGone");+ expect(chatNotice("chat.notice.waitBotGone", words.params)).toBe(notice.text);+ expect(waitNoticeText(wait({ kind: "file_missing", path: "/fixture/Report.txt" }), notice)).toBeUndefined();+ });+});diff --git a/server/wait-notice-text.ts b/server/wait-notice-text.tsnew file mode 100644index 0000000000..92e71fda4a--- /dev/null+++ b/server/wait-notice-text.ts@@ -0,0 +1,24 @@+import type { ServerText } from "../shared/server-text.ts";+import type { WaitNotice, WaitRecord } from "./waits.ts";++const FIRED_KEY = {+ url_contains: "urlContains", url_missing: "urlMissing", file_exists: "fileExists", file_missing: "fileMissing",+ file_changed: "fileChanged", process_running: "processRunning", process_gone: "processGone", bot_idle: "botIdle",+} as const;++export function waitNoticeText(wait: WaitRecord, notice: WaitNotice): ServerText | undefined {+ const params = { label: wait.label };+ if (notice.status === "expired") {+ const hours = Math.round((wait.expiresAt - wait.createdAt) / 3_600_000);+ return { key: hours === 1 ? "chat.notice.waitExpiredOne" : "chat.notice.waitExpiredMany", params: { ...params, hours } };+ }+ const condition = wait.condition;+ if (notice.status === "stopped") return condition.kind === "bot_idle" ? { key: "chat.notice.waitBotGone", params: { ...params, botName: condition.botName } } : undefined;+ const key = `chat.notice.waitDone.${FIRED_KEY[condition.kind]}`;+ switch (condition.kind) {+ case "url_contains": case "url_missing": return { key, params: { ...params, url: condition.url, text: condition.text } };+ case "file_exists": case "file_missing": case "file_changed": return { key, params: { ...params, path: condition.path } };+ case "process_running": case "process_gone": return { key, params: { ...params, process: condition.process } };+ case "bot_idle": return { key, params: { ...params, botName: condition.botName } };+ }+}diff --git a/server/waits.e2e.test.ts b/server/waits.e2e.test.tsindex 4a8ee94474..66887f2c35 100644--- a/server/waits.e2e.test.ts+++ b/server/waits.e2e.test.ts@@ -67,8 +67,9 @@ it("waits for a file with no AI, posts once in the asked chat, notifies, and conexpect((await transcript()).find((m) => m.id === cards[1].id).card).toMatchObject({ undone: true, waitRequest: { settled: "cancelled" } });writeFileSync(gate, "finish"); await settledTurn();writeFileSync(report, "done"); writeFileSync(other, "x");- await expect.poll(async () => (await transcript()).filter((m) => m.wait?.status === "fired").map((m) => m.text), { timeout: 30_000 })- .toEqual([`the report: done. ${report} is there now.`]);+ await expect.poll(async () => (await transcript()).filter((m) => m.wait?.status === "fired").map((m) => ({ text: m.text, textCode: m.textCode, textParams: m.textParams })), { timeout: 30_000 })+ .toEqual([{ text: `the report: done. ${report} is there now.`, textCode: "chat.notice.waitDone.fileExists", textParams: { label: "the report", path: report } }]);+ expect(await api("POST", `/api/threads/${bot.threadId}/undo`, { requestId: cards[0].card.requestId }, 409)).toEqual({ error: "This wait has already ended.", errorKey: "serverError.wait.alreadyEnded" });await expect.poll(async () => (await transcript()).some((m) => m.role === "user" && m.text?.includes("[Wait finished: the report] Say the report is ready.")), { timeout: 40_000 }).toBe(true);expect((await api("GET", "/api/notifications")).notifications.filter((n: any) => n.kind === "wait")).toMatchObject([{ title: "Scout's wait is over" }]);await new Promise((resolve) => setTimeout(resolve, 7_000));diff --git a/src/App.tsx b/src/App.tsxindex d227b16b01..d0ac3da525 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -65,7 +65,7 @@ import { ChatNotice } from "@/components/ChatErrorBanner";import { loadingLine } from "@/lib/app-loading";import { useAiSwitchKeeper } from "@/lib/ai-switch";import { useChiefStepOpen } from "@/lib/default-bot";-import { SESSION_ENDED_REASON, useSessionEnded } from "@/lib/session-ended";+import { useSessionEnded } from "@/lib/session-ended";import { PairPage } from "./pair/PairPage";import { WebPanelPage } from "@/components/WebPanelPage";@@ -459,6 +459,6 @@ function Application() {export default function App() {const ended = useSessionEnded();- if (ended) return <PairPage initialCode={null} reason={SESSION_ENDED_REASON} />;+ if (ended) return <PairPage initialCode={null} reason={t("pair.sessionEnded")} />;return <WorkspaceBackupRecovery><Application /></WorkspaceBackupRecovery>;}diff --git a/src/components/ApprovalCard.tsx b/src/components/ApprovalCard.tsxindex 8697d4491f..c7827fb4a3 100644--- a/src/components/ApprovalCard.tsx+++ b/src/components/ApprovalCard.tsx@@ -3,7 +3,7 @@ import { Check, Clock3, ShieldCheck, Undo2, X } from "lucide-react";import { api, ApiError, StoreContext, type Bot, type Message, type OptionCardData } from "@/state/store";import { shareLearnedSkillsMode } from "@/lib/feature-flags";import { cn } from "@/lib/cn";-import { t, tFromServer } from "@/lib/i18n";+import { activeLocale, t, tFromServer } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import { SkillRequestPreview } from "@/components/SkillRequestPreview";import { composioActionPhrase, outboundSummary } from "@/lib/approval-summary";@@ -200,11 +200,13 @@ export function appliedChange(card: OptionCardData, name: string): { line: strinfunction AppliedChangeLine({card,name,+ originalName,threadId,summary,}: {card: OptionCardData;name: string;+ originalName?: string;threadId?: string;summary: { line: string; canUndo: boolean; cancels?: boolean };}) {@@ -305,7 +307,7 @@ function AppliedChangeLine({aria-label={t("approval.aria.appliedDetails")}className="mt-1.5 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-2xl bg-inset px-4 py-3 font-mono text-[13px] leading-relaxed text-ink">- {card.subtitle}+ {activeLocale() !== "en" && card.waitRequest ? t("approval.applied.waitFollowUp", { name: originalName ?? name, followUp: card.waitRequest.followUp ?? "" }) : card.subtitle}</pre>)}</div>@@ -425,7 +427,7 @@ export function ApprovalCard({const applied = card.autoApplied === true && card.answered === "allow" && !card.held? appliedChange(card, bot?.name ?? t("approval.someone")): undefined;- if (applied) return <AppliedChangeLine card={card} name={bot?.name ?? t("approval.someone")} threadId={threadId} summary={applied} />;+ if (applied) return <AppliedChangeLine card={card} name={bot?.name ?? t("approval.someone")} originalName={message.from?.name} threadId={threadId} summary={applied} />;const settled = card.answered;const expired = card.expired === true || staleRoutineCard(card);const via = card.answeredBy?.via;diff --git a/src/components/ApprovalCard.wait-details.test.ts b/src/components/ApprovalCard.wait-details.test.tsnew file mode 100644index 0000000000..13f23c2058--- /dev/null+++ b/src/components/ApprovalCard.wait-details.test.ts@@ -0,0 +1,54 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { setLocale, t } from "@/lib/i18n";+import * as session from "@/lib/session";+import type { Message } from "@/state/store";+import { ApprovalCard } from "./ApprovalCard";++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+let host: HTMLDivElement;+let root: Root;+beforeEach(() => {+ vi.spyOn(session, "readSessionState").mockResolvedValue({ kind: "loopback" });+ host = document.createElement("div");+ document.body.append(host);+ root = createRoot(host);+});+afterEach(() => {+ act(() => root.unmount());+ host.remove();+ vi.restoreAllMocks();+ setLocale("en");+});++const waiting = (persistedAuthor: boolean): Message => ({+ id: "wait-card", at: 1, role: "bot", kind: "options",+ ...(persistedAuthor ? { from: { botId: "pepper", name: "Pepper", color: "green" } } : {}),+ card: {+ title: "Waiting: the build", subtitle: "Then Pepper will: Deploy it.",+ options: [], answered: "allow", dismissed: true, autoApplied: true, requestId: "w1", tool: "wait_until",+ waitRequest: { waitId: "w1", label: "the build", followUp: "Deploy it." },+ },+});++describe.each(["en", "pt-br"] as const)("%s wait details", (locale) => {+ it.each([+ ["renamed", false], ["missing", false], ["renamed", true], ["missing", true],+ ] as const)("opens after the bot is %s, with persisted author %s", async (change, persistedAuthor) => {+ setLocale(locale);+ const message = waiting(persistedAuthor);+ await act(async () => root.render(createElement(ApprovalCard, { bot: { name: "Pepper" }, message, threadId: "t1" })));+ const bot = change === "renamed" ? { name: "Renamed Pepper" } : undefined;+ await act(async () => root.render(createElement(ApprovalCard, { bot, message, threadId: "t1" })));+ const details = [...host.querySelectorAll("button")].find(button => button.textContent === t("approval.applied.details"));+ expect(details).toBeDefined();+ await act(async () => details!.click());+ const content = host.querySelector("pre")?.textContent;+ const localizedName = persistedAuthor ? "Pepper" : bot?.name ?? "Alguém";+ expect(content).toBe(locale === "en" ? message.card!.subtitle : `Próxima ação de ${localizedName}: Deploy it.`);+ expect(message.card!.subtitle).toBe("Then Pepper will: Deploy it.");+ });+});diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex b01058499b..bfeb9fe718 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -737,7 +737,7 @@ const MessagesList = memo(function MessagesList({}switch (richRowKind(m)) {case "secret":- return m.secret ? <SecretRequestCard botId={botId} color={botColor} threadId={threadId} message={m} /> : null;+ return m.secret ? <SecretRequestCard botId={botId} botName={botName} color={botColor} threadId={threadId} message={m} /> : null;case "signin":return m.signIn ? <SignInRequestCard botId={botId} botName={botName} color={botColor} threadId={threadId} message={m} /> : null;case "connector":diff --git a/src/components/McpServersPanel.tsx b/src/components/McpServersPanel.tsxindex fdd353f711..90abfe5047 100644--- a/src/components/McpServersPanel.tsx+++ b/src/components/McpServersPanel.tsx@@ -226,7 +226,7 @@ export function McpServersPanel({ embedded = false, whopCard = false, hideWhop =if (connections.mcp.some((connection: { name: string }) => connection.name === item.name)) {const headers = (body.headers ?? {}) as Record<string, string | true>;if (Object.keys(headers).length > 1) {- throw new Error("Personal MCP connections support one header. Remove the extra headers before saving.");+ throw new Error(t("mcp.personal.oneHeader"));}const value = Object.values(headers)[0];ownKey = typeof value === "string" ? value : undefined;diff --git a/src/components/SecretRequestCard.test.ts b/src/components/SecretRequestCard.test.tsindex 2ec687a936..be208f9601 100644--- a/src/components/SecretRequestCard.test.ts+++ b/src/components/SecretRequestCard.test.ts@@ -25,6 +25,9 @@ vi.mock("@/state/store", async (original) => ({vi.mock("@/lib/analytics", () => ({ track: fixture.track }));import { SecretRequestCard } from "./SecretRequestCard";+import { setLocale } from "@/lib/i18n";++afterEach(() => setLocale("en"));const secretCard = (secret: Record<string, unknown>): Message => ({id: "secret-card",@@ -202,6 +205,33 @@ describe("SecretRequestCard key analytics", () => {});describe("SecretRequestCard custom secrets", () => {+ it.each(["file", "ref"] as const)("localizes the stopped %s delivery using its recorded author, not the saved description's words", (delivery) => {+ const message: Message = { ...secretCard({ target: "customSecret", reason: "To create test charges.", description: "Original saved description.", helpUrl: "", delivery, stopped: true }), from: { botId: "bot-1", name: "Scout", color: "green" } };+ const render = () => renderToStaticMarkup(createElement(SecretRequestCard, { botId: "bot-1", threadId: "thread-1", message }));+ expect(render()).toContain('title="Original saved description."');+ setLocale("pt-br");+ const html = render();+ expect(html).toContain("To create test charges.");+ expect(html).toContain(delivery === "file" ? "Os comandos de Scout podem ler" : "Scout recebe uma referência de uso único");+ expect(html).not.toContain("Original saved description.");+ setLocale("en");+ expect(render()).toContain('title="Original saved description."');+ });++ it.each(["file", "ref"] as const)("uses the direct chat's bot name for stopped %s delivery without a group author", (delivery) => {+ const message = secretCard({ target: "customSecret", stopped: true, description: "Saved direct chat description.", delivery });+ const render = () => renderToStaticMarkup(createElement(SecretRequestCard, { botId: "bot-1", botName: "Scout", threadId: "thread-1", message }));+ expect(render()).toContain('title="Saved direct chat description."');+ setLocale("pt-br");+ expect(render()).toContain(delivery === "file" ? "Os comandos de Scout podem ler" : "Scout recebe uma referência de uso único");+ expect(render()).not.toContain("Saved direct chat description.");+ });++ it("keeps an older card's description when no recorded author is available", () => {+ setLocale("pt-br");+ expect(view({ target: "customSecret", stopped: true, description: "Saved legacy description", delivery: "file" })).toContain('title="Saved legacy description"');+ });+it("says what the bot may do with it, in the bot's words and plainly, with no key link", () => {const file = view({ target: "customSecret", label: "Stripe secret key", reason: "To create test charges.", description: "To create test charges. Scout's commands can read it.", helpUrl: "", delivery: "file" });expect(file).toContain("To create test charges.");diff --git a/src/components/SecretRequestCard.tsx b/src/components/SecretRequestCard.tsxindex 46e432977f..9742d9ff07 100644--- a/src/components/SecretRequestCard.tsx+++ b/src/components/SecretRequestCard.tsx@@ -4,7 +4,7 @@ import { ExternalLink, KeyRound, Loader2, LockKeyhole, RefreshCw, X } from "luciimport { CUSTOM_SECRET_TARGET, credentialResumeOutcome, credentialSaveRequest, desktopCredentialSlot, isConfigCredentialTarget } from "../../shared/credential-request";import { credentialProvider } from "@/lib/analytics-allowlist";import { cn } from "@/lib/cn";-import { t } from "@/lib/i18n";+import { activeLocale, t } from "@/lib/i18n";import { keySaved, keySaveFailure, savedKeyResult } from "@/lib/product-events";import { api, useStore, type Bot, type ConfigStatus, type Message } from "@/state/store";import { ASK_FIELD, askPrimary, ASK_QUIET_BUTTON, AskCard, AskSettledLine, returnFocusToComposer } from "./AskCard";@@ -14,11 +14,13 @@ import { productName } from "@/lib/brand";export function SecretRequestCard({botId,+ botName,color,threadId,message,}: {botId: string;+ botName?: string;color?: Bot["color"];threadId: string;message: Message;@@ -38,6 +40,9 @@ export function SecretRequestCard({const declined = outcome === "dismissed";const superseded = secret.superseded === true;const stopped = secret.stopped === true;+ const authorName = message.from?.name ?? botName;+ const deliveryDescription = custom && authorName ? t(secret.delivery === "file" ? "secretCard.delivery.fileNamed" : "secretCard.delivery.refNamed", { botName: authorName }) : null;+ const customDescription = activeLocale() !== "en" && deliveryDescription ? [secret.reason, deliveryDescription].filter(Boolean).join(" ") : secret.description;const description = superseded? t("chat.secret.superseded"): provided@@ -48,7 +53,7 @@ export function SecretRequestCard({: t("chat.secret.savedWaiting"): declined? t("chat.secret.declined", { app: productName() })- : custom && secret.reason ? secret.reason : secret.description;+ : custom && secret.reason ? secret.reason : customDescription;const footerLabel = stopped? t("chat.secret.stopped"): declined@@ -155,7 +160,7 @@ export function SecretRequestCard({if (stopped && !provided) {return (<AskSettledLine icon={<X size={13} />} ariaLabel={secret.label}>- <span className="text-ink-secondary" title={secret.description}>{secret.label}</span>+ <span className="text-ink-secondary" title={customDescription}>{secret.label}</span><span> · {t("chat.secret.stopped")}</span></AskSettledLine>);diff --git a/src/components/browser/StreamSurface.test.ts b/src/components/browser/StreamSurface.test.tsindex 0423ef56a8..d6b726a142 100644--- a/src/components/browser/StreamSurface.test.ts+++ b/src/components/browser/StreamSurface.test.ts@@ -4,6 +4,7 @@ import { createRoot, type Root } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { PreviewStreamControl, PreviewStreamEvents, PreviewStreamInput } from "@/lib/browser-stream-client";+import { setLocale } from "@/lib/i18n";import { controlPill } from "./ChromeRow";import { letterbox, mapToPage, mapToSurface, StreamSurface } from "./StreamSurface";@@ -40,6 +41,7 @@ afterEach(() => {host.remove();vi.restoreAllMocks();vi.unstubAllGlobals();+ setLocale("en");});const control = (controller: PreviewStreamControl["controller"], more: Partial<PreviewStreamControl> = {}): PreviewStreamControl => ({ canOperate: true, controller, generation: 1, dialog: null, ...more });@@ -73,6 +75,29 @@ const pointer = (canvas: HTMLCanvasElement, type: string, x: number, y: number)const button = (label: string) => [...host.querySelectorAll("button")].find((candidate) => (candidate.getAttribute("aria-label") ?? candidate.textContent) === label)!;describe("the picture and the page", () => {+ it.each([+ ["en", "The browser stopped responding, so it is being restarted. The live view reconnects by itself."],+ ["pt-br", "O navegador parou de responder e está sendo reiniciado. A visualização ao vivo se reconecta sozinha."],+ ] as const)("renders the coded browser restart in %s without changing the event", async (locale, expected) => {+ setLocale(locale);+ const onMessage = vi.fn();+ const { events } = await mount({ onMessage });+ const notice = { type: "notice", message: "The browser stopped responding, so it is being restarted. The live view reconnects by itself.", errorKey: "serverError.browser.restartingUnresponsive" };+ await act(async () => events().onMessage?.(notice));+ expect(host.querySelector('[role="alert"]')?.textContent).toBe(expected);+ expect(onMessage).toHaveBeenCalledExactlyOnceWith(notice);+ expect(notice.message).toBe("The browser stopped responding, so it is being restarted. The live view reconnects by itself.");+ });++ it("keeps uncoded notices and unknown server keys as the original fallback", async () => {+ setLocale("pt-br");+ const { events } = await mount();+ for (const errorKey of [undefined, "serverError.unknown", "approval.applied.waitFollowUp"]) {+ await act(async () => events().onMessage?.({ type: "notice", message: "Original browser diagnostic", ...(errorKey ? { errorKey } : {}) }));+ }+ expect([...host.querySelectorAll('[role="alert"]')].map(alert => alert.textContent)).toEqual(Array(3).fill("Original browser diagnostic"));+ });+it("maps a point through the letterbox both ways, and refuses one outside the picture", () => {expect(letterbox({ width: 1600, height: 1200 }, { width: 3200, height: 2000 })).toEqual({ width: 1600, height: 1000, left: 0, top: 100 });const rect = { left: 10, top: 20, width: 1600, height: 1200 };diff --git a/src/components/browser/StreamSurface.tsx b/src/components/browser/StreamSurface.tsxindex cdc58f8163..f4998c1a57 100644--- a/src/components/browser/StreamSurface.tsx+++ b/src/components/browser/StreamSurface.tsx@@ -35,6 +35,7 @@ import {} from "@/lib/browser-stream-client";import { copyText } from "@/lib/copy-text";import { t } from "@/lib/i18n";+import { serverErrorText } from "@/lib/server-error";import { AgentCursor } from "./AgentCursor";import { AuthPrompt } from "./AuthPrompt";import { SelectPopup, type SelectPopupOption } from "./SelectPopup";@@ -410,7 +411,7 @@ export function StreamSurface(props: {} else if (message.type === "authPromptClosed") {setAuthPrompt((shown) => (shown && shown.id !== message.id ? shown : null));} else if (message.type === "notice" && typeof message.message === "string") {- notify({ kind: "error", message: message.message });+ notify({ kind: "error", message: serverErrorText(message, message.message) });}propsRef.current.onMessage?.(message);},diff --git a/src/lib/browser-stream-v1.test.ts b/src/lib/browser-stream-v1.test.tsindex 01ee727e01..cd98f90dde 100644--- a/src/lib/browser-stream-v1.test.ts+++ b/src/lib/browser-stream-v1.test.ts@@ -240,6 +240,20 @@ describe("the v1 live client", () => {expect(post.mock.calls.some(([body]) => body.type === "input_keyboard")).toBe(false);});+ it("preserves coded error fields and English while reconnecting an unresponsive browser", () => {+ vi.useFakeTimers();+ const { client, handlers, source } = open();+ const message = "The browser stopped responding, so it is being restarted. The live view reconnects by itself.";+ source.fail({ retryable: true, message, errorKey: "serverError.browser.restartingUnresponsive", errorParams: {} });+ expect(handlers.onMessage).toHaveBeenCalledExactlyOnceWith({ type: "notice", message, errorKey: "serverError.browser.restartingUnresponsive", errorParams: {} });+ expect(handlers.onGone).not.toHaveBeenCalled();+ vi.advanceTimersByTime(999);+ expect(FixtureEventSource.instances).toHaveLength(1);+ vi.advanceTimersByTime(1);+ expect(FixtureEventSource.instances).toHaveLength(2);+ client.stop();+ });+it("does not retry the server's terminal refusal, and shows its reason", () => {const { handlers, source } = open();source.fail({ retryable: false, message: "Too many browser views are open." });diff --git a/src/lib/browser-stream-v1.ts b/src/lib/browser-stream-v1.tsindex e7ee0120b3..11c71e4f19 100644--- a/src/lib/browser-stream-v1.ts+++ b/src/lib/browser-stream-v1.ts@@ -302,10 +302,10 @@ export function createLiveStreamClient(botId: string, events: PreviewStreamEventlet retryable = !(event instanceof MessageEvent);if (event instanceof MessageEvent) {try {- const data = JSON.parse(event.data) as { retryable?: unknown; message?: unknown; asleep?: unknown };+ const data = JSON.parse(event.data) as { retryable?: unknown; message?: unknown; asleep?: unknown; errorKey?: unknown; errorParams?: unknown };retryable = data.retryable === true;if (data.asleep === true) events.onMessage?.({ type: "asleep" });- else if (typeof data.message === "string") events.onMessage?.({ type: "notice", message: data.message });+ else if (typeof data.message === "string") events.onMessage?.({ type: "notice", message: data.message, ...(typeof data.errorKey === "string" ? { errorKey: data.errorKey, ...(data.errorParams !== undefined ? { errorParams: data.errorParams } : {}) } : {}) });} catch {}}dropped(live, retryable);diff --git a/src/lib/fixed-server-lines.test.ts b/src/lib/fixed-server-lines.test.tsindex 91966aa8dd..f02fefbfb6 100644--- a/src/lib/fixed-server-lines.test.ts+++ b/src/lib/fixed-server-lines.test.ts@@ -160,7 +160,7 @@ describe("fixed server words", () => {});describe("inbox reasons on the brief", () => {- it("preserves English and formats extracted amounts only when rendering pt-BR", () => {+ it("preserves English and formats extracted dates and amounts only when rendering pt-BR", () => {const picked = inboxWhy({ ask: "to revisar o pedido", deadline: "2026-10-30", amount: 1234.5 });expect(picked.why).toBe("Asks you to revisar o pedido, due 2026-10-30, about 1,234.5.");expect(picked.whyText?.params).toEqual({ ask: "revisar o pedido", deadline: "2026-10-30", amount: "1,234.5", amountValue: "1234.5" });@@ -168,7 +168,35 @@ describe("inbox reasons on the brief", () => {const payload: WidgetPayload = { v: 1, root: built.card };expect(localizedCard(payload, true)).toBe(payload);setLocale("pt-br");- expect(localizedCard(payload, true).root.children?.[1]?.children?.[1]?.value).toBe("Aguardando sua resposta · Pedido: revisar o pedido · prazo: 2026-10-30 · valor aproximado: 1.234,5.");+ expect(localizedCard(payload, true).root.children?.[1]?.children?.[1]?.value).toBe("Aguardando sua resposta · Pedido: revisar o pedido · prazo: 30 de out. de 2026 · valor aproximado: 1.234,5.");+ });++ it.each(["due", "askDue", "dueAmount", "askDueAmount", "waiting.due", "waiting.askDue", "waiting.dueAmount", "waiting.askDueAmount"])("formats an ISO deadline for %s without rewriting its params or its English", (shape) => {+ const params = { ask: "confirmar", deadline: "2026-10-30", amount: "1,200", amountValue: "1200" };+ const payload: WidgetPayload = { v: 1, root: { id: "deadline", type: "text", value: "English fallback", i18n: { value: { key: `brief.inbox.${shape}`, params } } } };+ expect(localizedCard(payload, true)).toBe(payload);+ setLocale("pt-br");+ expect(localizedCard(payload, true).root.value).toContain("30 de out. de 2026");+ expect(params.deadline).toBe("2026-10-30");+ expect(localizedCard(payload, false)).toBe(payload);+ });++ it.each(["amanhã", "October 30, 2026", "2026-13-30", "2026-02-30", "2026-10-30Tinvalid"])("keeps the free-form or invalid deadline %s as data", (deadline) => {+ const payload: WidgetPayload = { v: 1, root: { id: "deadline", type: "text", value: "English fallback", i18n: { value: { key: "brief.inbox.due", params: { deadline } } } } };+ setLocale("pt-br");+ expect(localizedCard(payload, true).root.value).toContain(deadline);+ });++ it("formats ISO timestamps in the renderer's time zone and date-only values without a day shift", () => {+ setLocale("pt-br");+ for (const deadline of ["2026-10-30", "2026-10-30T12:00:00Z"]) {+ const payload: WidgetPayload = { v: 1, root: { id: "deadline", type: "text", value: deadline, i18n: { value: { key: "brief.inbox.due", params: { deadline } } } } };+ const options: Intl.DateTimeFormatOptions = { dateStyle: "medium", ...(deadline.length === 10 ? { timeZone: "UTC" } : {}) };+ expect(localizedCard(payload, true).root.value).toContain(new Intl.DateTimeFormat("pt-BR", options).format(new Date(deadline)));+ setLocale("en");+ expect(localizedCard(payload, true)).toBe(payload);+ setLocale("pt-br");+ }});it.each([1, 2, 3, 4, 5, 6, 7])("keeps only string params for reason shape %s", (mask) => {diff --git a/src/lib/ready-bots.ts b/src/lib/ready-bots.tsindex 02af04c561..b7096423e9 100644--- a/src/lib/ready-bots.ts+++ b/src/lib/ready-bots.ts@@ -345,7 +345,7 @@ export function readyBotTemplate(defaults: NewBotDefaults, bot: ReadyBot): NewBoconst own = template.memory[path]?.trimEnd();template.memory[path] = own ? `${own}\n${text}` : text;}- template.routines = [...template.routines, ...(bot.routines ?? []).map((routine) => ({ ...routine, enabled: false }))];+ template.routines = [...template.routines, ...(bot.routines ?? []).map((routine) => ({ ...routine, ...(bot.id === "social" ? { name: t("readyBots.routine.socialWeekly") } : {}), enabled: false }))];return template;}diff --git a/src/lib/server-word-contracts.test.ts b/src/lib/server-word-contracts.test.tsnew file mode 100644index 0000000000..1f0130939b--- /dev/null+++ b/src/lib/server-word-contracts.test.ts@@ -0,0 +1,45 @@+import { afterEach, describe, expect, it } from "vitest";+import { en, type LocaleKey } from "@/locales";+import { activityText, noticeText, routineLineText } from "./activity-text";+import { setLocale, t } from "./i18n";+import { serverErrorText } from "./server-error";+import { USER_ERROR, userError, type UserErrorKey } from "../../server/user-errors";+import { CHAT_NOTICE, noticeLine, noticeTool, type ChatNoticeKey } from "../../server/chat-notices";+import { ROUTINE_LINE, codedLine, type RoutineLineKey } from "../../server/routine-lines";++const paramsFor = (template: string) => Object.fromEntries([...template.matchAll(/\{(\w+)\}/g)].map(([, name]) => [name!, `Fixture ${name}`]));+afterEach(() => setLocale("en"));++describe("fixed server words across transport and renderer", () => {+ it.each(Object.entries(USER_ERROR))("renders %s in pt-BR and keeps its English fallback", (key, template) => {+ const params = paramsFor(template);+ const body = userError(key as UserErrorKey, params);+ expect(body.error).toBe(template.replace(/\{(\w+)\}/g, (_, name: string) => params[name]!));+ expect(serverErrorText(body, body.error)).toBe(body.error);+ setLocale("pt-br");+ expect(serverErrorText(body, body.error)).toBe(t(key as LocaleKey, params));+ expect(en[key as LocaleKey]).toBe(template);+ expect(serverErrorText({ errorKey: "serverError.unknown" }, body.error)).toBe(body.error);+ });++ it.each(Object.entries(CHAT_NOTICE).filter(([key]) => !key.includes(".part.")))("renders line and tool %s using the same coded contract", (key, template) => {+ const params = paramsFor(template);+ const line = noticeLine(key as ChatNoticeKey, params);+ const tool = noticeTool(key as ChatNoticeKey, params, { ok: true });+ expect(noticeText(line.textCode, line.text, line.textParams)).toBe(line.text);+ expect(activityText(tool, tool.name)).toBe(tool.name);+ setLocale("pt-br");+ expect(noticeText(line.textCode, line.text, line.textParams)).toBe(t(key as LocaleKey, params));+ expect(activityText(tool, tool.name)).toBe(t(key as LocaleKey, params));+ expect(en[key as LocaleKey]).toBe(template);+ });++ it.each(Object.entries(ROUTINE_LINE).filter(([key]) => !key.includes(".part.")))("renders the routine line %s without changing stored params", (key, template) => {+ const params = paramsFor(template);+ const line = codedLine("attention", key as RoutineLineKey, params);+ expect(routineLineText(line.codes.attentionCode, line.text, line.codes.attentionParams)).toBe(line.text);+ setLocale("pt-br");+ expect(routineLineText(line.codes.attentionCode, line.text, line.codes.attentionParams)).toBe(t(key as LocaleKey, params));+ expect(en[key as LocaleKey]).toBe(template);+ });+});diff --git a/src/lib/widget-text.ts b/src/lib/widget-text.tsindex 049a30d8d9..2a95a92017 100644--- a/src/lib/widget-text.ts+++ b/src/lib/widget-text.ts@@ -34,6 +34,13 @@ function wordsOf(text: WidgetText): string {if (text.key.startsWith("brief.inbox.") && typeof params.amountValue === "string" && Number.isFinite(Number(params.amountValue))) {params.amount = new Intl.NumberFormat(intlLocale()).format(Number(params.amountValue));}+ if (text.key.startsWith("brief.inbox.") && typeof params.deadline === "string" && /^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(params.deadline)) {+ const date = new Date(params.deadline);+ const day = new Date(params.deadline.slice(0, 10));+ if (Number.isFinite(date.getTime()) && Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === params.deadline.slice(0, 10)) {+ params.deadline = new Intl.DateTimeFormat(intlLocale(), { dateStyle: "medium", ...(params.deadline.length === 10 ? { timeZone: "UTC" } : {}) }).format(date);+ }+ }const template = t(text.key as LocaleKey);const unfilled = [...template.matchAll(/\{(\w+)\}/g)].some(([, name]) => !Object.hasOwn(params, name!));if (unfilled) throw new Error(`card text ${text.key} lacks a param`);diff --git a/src/locales/en.json b/src/locales/en.jsonindex 9ba6a1e46e..9a8d11be13 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -8453,5 +8453,189 @@"shortcuts.toggle-sidebar": "Collapse or expand the sidebar","readyBots.bot.social.title": "Social media manager","readyBots.bot.social.description": "Plans your posts and adds them to Postiz as drafts or scheduled posts, ready for you to review.",- "readyBots.bot.social.try": "Plan next week's posts for LinkedIn and X"+ "readyBots.bot.social.try": "Plan next week's posts for LinkedIn and X",+ "native.cloud.otherGone": "That Cloud is no longer one of yours.",+ "native.cloud.otherNotReady": "{name} isn't ready to open yet.",+ "native.cloud.otherNoLongerYours": "{name} is no longer one of your Clouds.",+ "native.cloud.otherNotRunning": "{name} isn't running right now.",+ "native.cloud.invalidAdd": "Invalid Cloud to add.",+ "native.cloud.invalidOrganization": "Invalid organization to add.",+ "native.cloud.invalidColor": "Invalid Cloud color.",+ "native.cloud.invalidRemove": "Invalid Cloud to remove.",+ "native.cloud.ready.open": "Click to open it.",+ "native.cloud.ready.quotedTitle": "“{name}” is ready",+ "native.places.noLongerHere": "That place isn't here any more.",+ "native.places.cannotAdd": "That isn't something to add here.",+ "native.cloud.addSignIn": "Sign in to MausBot Cloud first.",+ "native.cloud.addPlanAndName": "Choose a plan and a name to continue.",+ "native.cloud.addOrganizationName": "Give the organization a name to continue.",+ "native.cloud.noNewCloud": "There is no new Cloud to open.",+ "native.lend.moveWaiting": "Lending to My Cloud waits until it is signed in and not paused.",+ "native.lend.moveNotStarted": "Lending to My Cloud did not start.",+ "native.boot.sharedFolderAdvice": " If OpenMausBot is not running on another computer or container that shares this folder, quit OpenMausBot, delete {path} and start again.",+ "native.lendTray.pause": "Pause",+ "native.lendTray.resume": "Resume",+ "native.lendTray.activity": "See activity",+ "native.files.newFromCloud": "new from My Cloud",+ "native.files.nameNotSupported": "This computer can't hold that name.",+ "native.files.gitProtected": "Files inside .git are never changed from My Cloud.",+ "native.files.changeDamaged": "The change was damaged on its way; it will be fetched again.",+ "native.places.chooseColor": "Choose one of the colors.",+ "native.places.noColor": "This place has no color to change.",+ "native.talk.listening": "Listening…",+ "native.talk.sending": "Sending to MausBot…",+ "native.talk.thinking": "MausBot is thinking…",+ "native.talk.needsYou": "MausBot needs you · Open chat",+ "native.talk.stillWorking": "Still working · Open chat",+ "native.talk.dismiss": "Dismiss",+ "native.talk.releaseToSend": "Let go to send",+ "native.talk.voiceBusy": "Voice is in use in MausBot",+ "native.talk.openMausBot": "Open MausBot to talk",+ "native.talk.starting": "MausBot is still starting. Try again in a moment.",+ "native.talk.setUpFirst": "Set up MausBot first, then try again.",+ "native.talk.movedToCloud": "MausBot lives on My Cloud now — talk to it there",+ "native.talk.permissions": "Talking needs Microphone + Speech Recognition access — System Settings → Privacy & Security.",+ "native.talk.dictationOff": "Turn on Dictation in System Settings → Keyboard, then try again.",+ "native.talk.unavailable": "Talking couldn't start. Try again.",+ "native.talk.failed": "MausBot couldn't take that · Open chat",+ "activity.tool.team.cancelWait": "Cancel wait",+ "activity.tool.team.deleteTrigger": "Delete trigger",+ "activity.tool.team.listWaits": "List waits",+ "activity.tool.team.waitUntil": "Wait until",+ "serverError.request.bodyTimeout": "The request took too long. Check the connection and try again.",+ "serverError.browser.restartingUnresponsive": "The browser stopped responding, so it is being restarted. The live view reconnects by itself.",+ "serverError.computer.desktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.",+ "serverError.computer.permissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it",+ "serverError.computer.notReadyDetail": "OpenMausBot can't use this computer yet — {reason}",+ "serverError.computer.notReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.",+ "chat.notice.copilotAccountRefused": "GitHub Copilot refused this request for the signed-in account. Check its Copilot plan and premium request allowance, then try again.",+ "chat.notice.acpQuietUsageLimit": "{name} reached a usage limit{said} and is waiting it out without replying, so this turn was stopped.",+ "chat.notice.acpQuietStuck": "{name} sent nothing for {quiet} with no tool running, no open request to its model and no CPU use, so the turn was stopped as stuck. Send the message again to retry.",+ "chat.notice.acpModelRequestFailed": "{name}'s model request failed: \"{message}\" {name} may retry or stop; no reply for {quiet} so far.",+ "chat.notice.acpModelFallback": "{displayName} no longer offers {wanted}, so this conversation uses {fallback}. Choose another model for this bot to stop seeing this.",+ "chat.notice.codexActionMayHaveRun": "{message} A tool action may have run. Check its effects before trying again.",+ "chat.notice.modelServerStoppedAnswering": "The model server at {host} stopped answering, so the reply was stopped.",+ "chat.notice.piModelNotConfirmed": "Pi did not confirm the selected model",+ "serverError.install.invalidDetails": "{name}'s install details are invalid. Nothing was downloaded.",+ "serverError.install.versionGone": "This version of {name} is no longer available to download. Update OpenMausBot, then try again.",+ "serverError.install.downloadLimited": "The download site is limiting downloads right now. Try again in a few minutes.",+ "serverError.install.siteNotAnswering": "{name}'s download site isn't answering right now. Try again later.",+ "serverError.install.downloadFailed": "{name} couldn't be downloaded. Check the internet connection and try again.",+ "serverError.install.downloadTooLarge": "The {name} download was larger than expected, so it was stopped. Nothing was installed.",+ "serverError.install.unofficialDownload": "The {name} download did not come from its official site, so it was stopped. Nothing was installed.",+ "serverError.install.redirects": "The {name} download kept redirecting, so it was stopped. Nothing was installed.",+ "serverError.install.safetyCheck": "The {name} download failed its safety check, so nothing was installed. Try again later.",+ "serverError.install.downloadTimeout": "The {name} download took too long and was stopped. Check the internet connection and try again.",+ "serverError.install.unsafeArchive": "The archive contains an unexpected or unsafe file. Nothing was installed.",+ "serverError.install.unsafeFile": "The {name} download holds an unexpected or unsafe file, so nothing was installed.",+ "serverError.install.notPlainFolder": "OpenMausBot's folder for {name} is not a plain folder ({path}), so nothing was changed. Move it away, then try again.",+ "serverError.install.unexpectedFolder": "OpenMausBot's folder for {name} holds something it did not put there ({path}), so nothing was changed. Move it away, then try again.",+ "serverError.install.diskSpace": "There is not enough free disk space to install {name}. Free up about {megabytes} MB, then try again.",+ "serverError.install.openElsewhere": "{name} is open in another window. Close it, then try again.",+ "serverError.install.cannotWrite": "OpenMausBot can't write to its folder for {name}. Check the folder's permissions, then try again.",+ "serverError.install.failed": "{name} couldn't be installed. Try again.",+ "serverError.install.noDownload": "{name} has no download for this computer.",+ "serverError.install.existingDoesNotStart": "{name} is installed, but it doesn't start on this computer ({failure}). Nothing was changed.",+ "serverError.install.programMissing": "The {name} download did not contain the program it should, so nothing was installed.",+ "serverError.install.notSigned": "The downloaded {name} is not signed by its maker, so nothing was installed.",+ "serverError.install.downloadDoesNotStart": "{name} was downloaded, but it doesn't start on this computer ({failure}). Nothing was installed.",+ "chat.notice.waitingApprovalElsewhere": "Waiting on your approval in @{name}",+ "chat.notice.waitingAnswerElsewhere": "Waiting on your answer in @{name}",+ "chat.notice.teammateNeedsInput": "{name} needs your input: {question}",+ "chat.notice.relayCouldNotContinue": "this conversation could not carry on — {error}",+ "secretCard.delivery.fileNamed": "{botName}'s commands can read it from a private file for 24 hours; it is never added to chat.",+ "secretCard.delivery.refNamed": "{botName} gets a one-use reference for OpenMausBot's own tools and never sees it.",+ "serverError.secret.missing": "no such credential request",+ "serverError.secret.settingsCard": "this card saves a key in Settings",+ "serverError.secret.savingFromPhone": "this secret is currently being saved from a phone",+ "serverError.secret.declined": "this request was declined",+ "serverError.secret.replaced": "this request was replaced by a newer one",+ "serverError.secret.taskStopped": "this request stopped with its task",+ "serverError.secret.alreadySaved": "this secret was already saved",+ "serverError.secret.valueSize": "Enter the secret: up to {bytes} bytes.",+ "serverError.secret.notKeptSafely": "The secret could not be kept safely. Nothing was saved.",+ "serverError.secret.unavailableLower": "this credential request is no longer available",+ "chat.notice.provideSecretSecurely": "Securely provide the {label} from OpenMausBot on your phone or computer. It is never added to chat.",+ "serverError.signIn.requestMissing": "no such sign-in request",+ "serverError.signIn.requestReplaced": "this sign-in request was superseded by a newer one",+ "serverError.signIn.answeredInChat": "this sign-in request was already answered in the chat",+ "serverError.signIn.alreadyDone": "this sign-in request was already marked done",+ "serverError.signIn.alreadyCancelled": "this sign-in request was already cancelled",+ "chat.notice.inboxNotPassed": "Not passed to {from}",+ "serverError.inbox.answerNotPassed": "That answer can't be passed back.",+ "serverError.room.nameOneLine": "room name must fit on one line",+ "serverError.computer.systemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work",+ "serverError.computer.aiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",+ "chat.notice.engineSignedOut": "{name} is signed out.",+ "serverError.wait.alreadyEnded": "This wait has already ended.",+ "chat.notice.failoverSignedInAgain": "{engine} is signed in again, so this conversation is back on {engine}.",+ "chat.notice.failoverSignedOut": "{from} is signed out, so {to} took over.",+ "serverError.botDefaults.nameLength": "name must be at most 100 characters",+ "serverError.botDefaults.sectionLength": "section must be at most 60 characters",+ "serverError.botDefaults.invalid": "These bot settings are not valid.",+ "serverError.postiz.addressHttps": "Enter your Postiz server's address, starting with https://.",+ "serverError.postiz.addressNoCredentials": "Leave any user name or password out of the Postiz address.",+ "serverError.postiz.addressNoQuery": "Enter the Postiz address without anything after ? or #.",+ "serverError.postiz.addressLocalHttp": "Use an https:// address. Plain http:// works only for a Postiz server on this computer.",+ "serverError.postiz.addressUseHttps": "Use your Postiz server's https:// address.",+ "serverError.postiz.addressContainsKey": "That address has a key in it. Enter the server address alone, and paste the key in its own box.",+ "serverError.postiz.mcpUpdating": "MCP servers are being updated. Try again in a moment.",+ "chat.notice.backupCardWaiting": "switched to {name}. Your request waits on a card above and continues on {name} once you act on it.",+ "chat.notice.backupRequestUnderWay": "switched to {name}. Your request is still under way here and continues on {name}.",+ "chat.notice.backupConversationBusy": "switched to {name}. This conversation is working, so your message was not sent again.",+ "chat.notice.backupQuestionWaiting": "switched to {name}. A teammate's question is waiting for your answer in this conversation, so your message was not sent again. Answer it, then send your message again.",+ "chat.notice.backupMessageMissing": "switched to {name}, but your message could not be found to send again. Send it again.",+ "chat.notice.backupContinuingLimit": "continuing on {name} after hitting the usage limit",+ "chat.notice.backupContinuingSignedOut": "continuing on {name} while {engine} is signed out",+ "chat.notice.backupCouldNotContinue": "could not continue on {name}: {error}",+ "serverError.setup.mausbotMissing": "no such MausBot",+ "serverError.setup.mausbotOwnerOnly": "only MausBot's own person can do this",+ "serverError.setup.noIntroToFollowUp": "this conversation has no intro to follow up",+ "serverError.inbox.missing": "There is no inbox here.",+ "serverError.inbox.lineMissing": "That line is not in your inbox.",+ "serverError.inbox.answerRequired": "This waits on your answer: answer it, or close it, where it asks.",+ "serverError.instance.settingsInvalid": "Supply a valid CLI path, account name, configuration directory, boolean tools setting or a reply wait of 1 to 60 minutes.",+ "serverError.instance.replyWaitUnsupported": "The reply wait is available for OpenAI-compatible servers only.",+ "serverError.mcp.personalHeadersShared": "Personal MCP header values cannot be saved in shared configuration. Save your key in your personal connection.",+ "serverError.mcp.testSignInFirst": "Sign in to the team to test your own connection.",+ "serverError.postiz.adminOnly": "Only the owner or an admin can manage the Postiz connection.",+ "serverError.postiz.keyAlone": "Paste the Postiz API key alone.",+ "serverError.postiz.addressAsText": "Send the Postiz address as text.",+ "serverError.secret.localService": "A local service cannot enter a secret. Enter it in OpenMausBot.",+ "serverError.secret.cloudOwnerOnly": "Only the owner of this Cloud can enter this secret.",+ "serverError.secret.conversationOwnerOnly": "Only the person this conversation belongs to can enter this secret.",+ "serverError.secret.credentialSavingFromPhone": "this credential is currently being saved from a phone",+ "serverError.secret.credentialDismissed": "this credential request was dismissed",+ "serverError.secret.credentialSuperseded": "this credential request was superseded by a newer one",+ "serverError.secret.notSavedYet": "{label} was not saved yet",+ "serverError.secret.notReadyToResume": "this credential request is not ready to resume",+ "serverError.secret.noLongerConfigured": "{label} is no longer configured",+ "serverError.department.moveChiefConflict": "A department can have only one Chief of Staff. Change the Chief before moving this bot.",+ "serverError.department.membershipChanged": "Department membership changed. Reopen the dialog and try again.",+ "serverError.mcp.addressAsText": "Send the MCP server address as text.",+ "serverError.mcp.addressChanged": "The MCP server address changed. Reload the server and try again.",+ "serverError.attachment.alreadyInMessage": "This file is already in a message, so it stays.",+ "routines.server.backupSignedOut": "Starting again on the backup AI: this bot's AI is signed out",+ "approval.applied.waitFollowUp": "Then {name} will: {followUp}",+ "chat.notice.waitDone.urlContains": "{label}: done. {url} now says “{text}”.",+ "chat.notice.waitDone.urlMissing": "{label}: done. {url} no longer says “{text}”.",+ "chat.notice.waitDone.fileExists": "{label}: done. {path} is there now.",+ "chat.notice.waitDone.fileMissing": "{label}: done. {path} is gone.",+ "chat.notice.waitDone.fileChanged": "{label}: done. {path} changed.",+ "chat.notice.waitDone.processRunning": "{label}: done. {process} is running.",+ "chat.notice.waitDone.processGone": "{label}: done. {process} stopped.",+ "chat.notice.waitDone.botIdle": "{label}: done. {botName} finished.",+ "chat.notice.waitBotGone": "Stopped waiting for {label}: {botName} no longer exists.",+ "chat.notice.waitExpiredOne": "Stopped waiting for {label} after {hours} hour.",+ "chat.notice.waitExpiredMany": "Stopped waiting for {label} after {hours} hours.",+ "mcp.personal.oneHeader": "Personal MCP connections support one header. Remove the extra headers before saving.",+ "readyBots.routine.socialWeekly": "Weekly post plan",+ "pair.sessionEnded": "Your session ended. Pair this device again to keep using it.",+ "chat.notice.computerDesktopOnly": "Only the OpenMausBot app on this computer can let a bot use it. Open the app here, or let the bot work in its own browser or on a cloud desktop instead.",+ "chat.notice.computerPermissionsThenRestart": "OpenMausBot can't use this computer yet — make sure OpenMausBot has the permissions it asks for, then restart it",+ "chat.notice.computerNotReadyDetail": "OpenMausBot can't use this computer yet — {reason}",+ "chat.notice.computerNotReadyMacPermission": "OpenMausBot can't use this computer yet — {reason}. Relaunch OpenMausBot after granting the missing macOS permission.",+ "chat.notice.computerSystemUnsupported": "bots can't use this computer on this system — choose another place for this bot to work",+ "chat.notice.computerAiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",+ "serverError.engine.signedOut": "{name} is signed out."}diff --git a/src/locales/everyday-words.test.ts b/src/locales/everyday-words.test.tsindex 8e26dd3d7d..453ee9d05e 100644--- a/src/locales/everyday-words.test.ts+++ b/src/locales/everyday-words.test.ts@@ -88,6 +88,7 @@ const ALLOWED: Record<string, string> = {"sidebar.update.howOtherRestart": "a server added from the app menu's Server menu: its update is for whoever runs it, not this app","cloudPhone.step1": "points at the app menu's Server menu, entry by entry","botAccess.tools.syntax": "the tool names people type, such as mcp:SERVER:NAME",+ "chat.notice.modelServerStoppedAnswering": "the person's model server at a named host, not the app's internal server",};const prefixes = Object.values(EVERYDAY_PREFIXES).flat();diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 8de469e5d1..cc349e82b5 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -8453,5 +8453,189 @@"shortcuts.toggle-sidebar": "Recolher ou expandir a barra lateral","readyBots.bot.social.title": "Gerente de redes sociais","readyBots.bot.social.description": "Planeja seus posts e os adiciona ao Postiz como rascunhos ou posts agendados para você revisar.",- "readyBots.bot.social.try": "Planejar os posts da próxima semana para o LinkedIn e o X"+ "readyBots.bot.social.try": "Planejar os posts da próxima semana para o LinkedIn e o X",+ "native.cloud.otherGone": "Esse Cloud não é mais seu.",+ "native.cloud.otherNotReady": "{name} ainda não está pronto para abrir.",+ "native.cloud.otherNoLongerYours": "{name} não é mais um dos seus Clouds.",+ "native.cloud.otherNotRunning": "{name} não está rodando agora.",+ "native.cloud.invalidAdd": "Cloud inválido para adicionar.",+ "native.cloud.invalidOrganization": "Organização inválida para adicionar.",+ "native.cloud.invalidColor": "Cor inválida para o Cloud.",+ "native.cloud.invalidRemove": "Cloud inválido para remover.",+ "native.cloud.ready.open": "Clique para abrir.",+ "native.cloud.ready.quotedTitle": "“{name}” já está disponível",+ "native.places.noLongerHere": "Esse local não está mais aqui.",+ "native.places.cannotAdd": "Isso não pode ser adicionado aqui.",+ "native.cloud.addSignIn": "Entre no MausBot Cloud primeiro.",+ "native.cloud.addPlanAndName": "Escolha um plano e um nome para continuar.",+ "native.cloud.addOrganizationName": "Dê um nome à organização para continuar.",+ "native.cloud.noNewCloud": "Não há um novo Cloud para abrir.",+ "native.lend.moveWaiting": "O compartilhamento com o Cloud fica em espera enquanto estiver sem login ou pausado.",+ "native.lend.moveNotStarted": "O compartilhamento com o Cloud não começou.",+ "native.boot.sharedFolderAdvice": " Se o OpenMausBot não estiver rodando em outro computador ou contêiner que compartilha esta pasta, encerre o OpenMausBot, exclua {path} e abra de novo.",+ "native.lendTray.pause": "Pausar",+ "native.lendTray.resume": "Retomar",+ "native.lendTray.activity": "Ver atividade",+ "native.files.newFromCloud": "novo do Cloud",+ "native.files.nameNotSupported": "Este computador não aceita esse nome.",+ "native.files.gitProtected": "Arquivos dentro de .git nunca são alterados pelo Cloud.",+ "native.files.changeDamaged": "A alteração foi danificada no caminho e será buscada de novo.",+ "native.places.chooseColor": "Escolha uma das cores.",+ "native.places.noColor": "Este local não tem uma cor para mudar.",+ "native.talk.listening": "Ouvindo…",+ "native.talk.sending": "Enviando para o MausBot…",+ "native.talk.thinking": "O MausBot está pensando…",+ "native.talk.needsYou": "O MausBot precisa de você · Abrir conversa",+ "native.talk.stillWorking": "Ainda trabalhando · Abrir conversa",+ "native.talk.dismiss": "Fechar",+ "native.talk.releaseToSend": "Soltar para enviar",+ "native.talk.voiceBusy": "A voz está em uso no MausBot",+ "native.talk.openMausBot": "Abra o MausBot para falar",+ "native.talk.starting": "O MausBot ainda está iniciando. Tente de novo em instantes.",+ "native.talk.setUpFirst": "Configure o MausBot primeiro e tente de novo.",+ "native.talk.movedToCloud": "O MausBot está no Cloud agora. Fale com ele por lá",+ "native.talk.permissions": "Para falar, é preciso permitir o acesso ao Microfone e ao Reconhecimento de Fala em Ajustes do Sistema → Privacidade e Segurança.",+ "native.talk.dictationOff": "Ligue o Ditado em Ajustes do Sistema → Teclado e tente de novo.",+ "native.talk.unavailable": "Não foi possível começar a conversa por voz. Tente de novo.",+ "native.talk.failed": "O MausBot não conseguiu receber seu pedido · Abrir conversa",+ "activity.tool.team.cancelWait": "Cancelar espera",+ "activity.tool.team.deleteTrigger": "Excluir automação",+ "activity.tool.team.listWaits": "Listar esperas",+ "activity.tool.team.waitUntil": "Esperar até",+ "serverError.request.bodyTimeout": "O pedido demorou demais. Confira a conexão e tente de novo.",+ "serverError.browser.restartingUnresponsive": "O navegador parou de responder e está sendo reiniciado. A visualização ao vivo se reconecta sozinha.",+ "serverError.computer.desktopOnly": "Só o app OpenMausBot neste computador pode permitir que um bot o use. Abra o app aqui ou deixe o bot trabalhar no próprio navegador ou em um desktop na nuvem.",+ "serverError.computer.permissionsThenRestart": "O OpenMausBot ainda não consegue usar este computador. Confira se o OpenMausBot tem as permissões que pede e reinicie o app.",+ "serverError.computer.notReadyDetail": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}",+ "serverError.computer.notReadyMacPermission": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}. Abra o OpenMausBot de novo depois de conceder a permissão do macOS que falta.",+ "chat.notice.copilotAccountRefused": "O GitHub Copilot recusou este pedido para a conta conectada. Confira o plano do Copilot e a franquia de pedidos premium e tente de novo.",+ "chat.notice.acpQuietUsageLimit": "{name} atingiu um limite de uso{said} e está esperando sem responder, então este turno foi interrompido.",+ "chat.notice.acpQuietStuck": "{name} não enviou nada por {quiet}, sem ferramenta em execução, pedido aberto ao modelo ou uso de CPU, então o turno foi interrompido por estar travado. Envie a mensagem de novo para tentar outra vez.",+ "chat.notice.acpModelRequestFailed": "O pedido de {name} ao modelo falhou: “{message}”. {name} pode tentar de novo ou parar. Ainda não há resposta após {quiet}.",+ "chat.notice.acpModelFallback": "{displayName} não oferece mais {wanted}, então esta conversa está usando {fallback}. Escolha outro modelo para este bot para não ver mais este aviso.",+ "chat.notice.codexActionMayHaveRun": "{message} Uma ação de ferramenta pode ter sido executada. Confira os efeitos antes de tentar de novo.",+ "chat.notice.modelServerStoppedAnswering": "O servidor de modelo em {host} parou de responder, então a resposta foi interrompida.",+ "chat.notice.piModelNotConfirmed": "O Pi não confirmou o modelo selecionado",+ "serverError.install.invalidDetails": "Os dados de instalação de {name} são inválidos. Nada foi baixado.",+ "serverError.install.versionGone": "Esta versão de {name} não está mais disponível para baixar. Atualize o OpenMausBot e tente de novo.",+ "serverError.install.downloadLimited": "O site está limitando os downloads agora. Tente de novo em alguns minutos.",+ "serverError.install.siteNotAnswering": "O site de download de {name} não está respondendo agora. Tente mais tarde.",+ "serverError.install.downloadFailed": "Não foi possível baixar {name}. Confira a conexão com a internet e tente de novo.",+ "serverError.install.downloadTooLarge": "O download de {name} era maior que o esperado e foi interrompido. Nada foi instalado.",+ "serverError.install.unofficialDownload": "O download de {name} não veio do site oficial e foi interrompido. Nada foi instalado.",+ "serverError.install.redirects": "O download de {name} continuou redirecionando e foi interrompido. Nada foi instalado.",+ "serverError.install.safetyCheck": "O download de {name} não passou na verificação de segurança, então nada foi instalado. Tente mais tarde.",+ "serverError.install.downloadTimeout": "O download de {name} demorou demais e foi interrompido. Confira a conexão com a internet e tente de novo.",+ "serverError.install.unsafeArchive": "O pacote contém um arquivo inesperado ou inseguro. Nada foi instalado.",+ "serverError.install.unsafeFile": "O download de {name} contém um arquivo inesperado ou inseguro, então nada foi instalado.",+ "serverError.install.notPlainFolder": "A pasta do OpenMausBot para {name} não é uma pasta comum ({path}), então nada foi alterado. Mova esse item para outro lugar e tente de novo.",+ "serverError.install.unexpectedFolder": "A pasta do OpenMausBot para {name} contém algo que o app não colocou lá ({path}), então nada foi alterado. Mova esse item para outro lugar e tente de novo.",+ "serverError.install.diskSpace": "Não há espaço livre suficiente no disco para instalar {name}. Libere cerca de {megabytes} MB e tente de novo.",+ "serverError.install.openElsewhere": "{name} está aberto em outra janela. Feche e tente de novo.",+ "serverError.install.cannotWrite": "O OpenMausBot não consegue gravar na pasta de {name}. Confira as permissões da pasta e tente de novo.",+ "serverError.install.failed": "Não foi possível instalar {name}. Tente de novo.",+ "serverError.install.noDownload": "{name} não tem um download para este computador.",+ "serverError.install.existingDoesNotStart": "{name} está instalado, mas não inicia neste computador ({failure}). Nada foi alterado.",+ "serverError.install.programMissing": "O download de {name} não continha o programa esperado, então nada foi instalado.",+ "serverError.install.notSigned": "O download de {name} não tem a assinatura de quem o criou, então nada foi instalado.",+ "serverError.install.downloadDoesNotStart": "{name} foi baixado, mas não inicia neste computador ({failure}). Nada foi instalado.",+ "chat.notice.waitingApprovalElsewhere": "Esperando sua aprovação em @{name}",+ "chat.notice.waitingAnswerElsewhere": "Esperando sua resposta em @{name}",+ "chat.notice.teammateNeedsInput": "{name} precisa da sua resposta: {question}",+ "chat.notice.relayCouldNotContinue": "Não foi possível continuar esta conversa. Motivo: {error}",+ "secretCard.delivery.fileNamed": "Os comandos de {botName} podem ler o conteúdo em um arquivo privado por 24 horas. Ele nunca é adicionado ao chat.",+ "secretCard.delivery.refNamed": "{botName} recebe uma referência de uso único para as próprias ferramentas do OpenMausBot e nunca vê o conteúdo.",+ "serverError.secret.missing": "Não há esse pedido de credencial",+ "serverError.secret.settingsCard": "Este cartão salva uma chave em Configurações",+ "serverError.secret.savingFromPhone": "Esta credencial está sendo salva por um celular",+ "serverError.secret.declined": "Este pedido foi recusado",+ "serverError.secret.replaced": "Este pedido foi substituído por um mais recente",+ "serverError.secret.taskStopped": "Este pedido foi interrompido junto com a tarefa",+ "serverError.secret.alreadySaved": "Esta credencial já foi salva",+ "serverError.secret.valueSize": "Digite a credencial: até {bytes} bytes.",+ "serverError.secret.notKeptSafely": "Não foi possível guardar a credencial com segurança. Nada foi salvo.",+ "serverError.secret.unavailableLower": "Este pedido de credencial não está mais disponível",+ "chat.notice.provideSecretSecurely": "Forneça {label} com segurança pelo OpenMausBot no celular ou no computador. O conteúdo nunca é adicionado ao chat.",+ "serverError.signIn.requestMissing": "Não há esse pedido de login",+ "serverError.signIn.requestReplaced": "Este pedido de login foi substituído por um mais recente",+ "serverError.signIn.answeredInChat": "Este pedido de login já foi respondido na conversa",+ "serverError.signIn.alreadyDone": "Este pedido de login já foi marcado como concluído",+ "serverError.signIn.alreadyCancelled": "Este pedido de login já foi cancelado",+ "chat.notice.inboxNotPassed": "Não foi repassado para {from}",+ "serverError.inbox.answerNotPassed": "Não é possível repassar essa resposta.",+ "serverError.room.nameOneLine": "O nome do chat em grupo precisa caber em uma linha",+ "serverError.computer.systemUnsupported": "Os bots não podem usar este computador neste sistema. Escolha outro local de trabalho para este bot",+ "serverError.computer.aiUnsupported": "A IA deste bot não pode usar este computador. Escolha outra IA ou outro local de trabalho para este bot",+ "chat.notice.engineSignedOut": "{name} está sem login.",+ "serverError.wait.alreadyEnded": "Esta espera já terminou.",+ "chat.notice.failoverSignedInAgain": "{engine} está com o login ativo de novo, então esta conversa voltou para {engine}.",+ "chat.notice.failoverSignedOut": "{from} está sem login, então {to} assumiu.",+ "serverError.botDefaults.nameLength": "O nome precisa ter no máximo 100 caracteres",+ "serverError.botDefaults.sectionLength": "O nome da equipe precisa ter no máximo 60 caracteres",+ "serverError.botDefaults.invalid": "Estas configurações do bot são inválidas.",+ "serverError.postiz.addressHttps": "Digite o endereço do seu servidor Postiz, começando com https://.",+ "serverError.postiz.addressNoCredentials": "Não inclua nome de usuário nem senha no endereço do Postiz.",+ "serverError.postiz.addressNoQuery": "Digite o endereço do Postiz sem nada depois de ? ou #.",+ "serverError.postiz.addressLocalHttp": "Use um endereço https://. Um endereço http:// só funciona para um servidor Postiz neste computador.",+ "serverError.postiz.addressUseHttps": "Use o endereço https:// do seu servidor Postiz.",+ "serverError.postiz.addressContainsKey": "Esse endereço contém uma chave. Digite só o endereço do servidor e cole a chave no campo dela.",+ "serverError.postiz.mcpUpdating": "Os servidores MCP estão sendo atualizados. Tente de novo em instantes.",+ "chat.notice.backupCardWaiting": "Mudou para {name}. Seu pedido espera uma ação sua em um cartão acima e continua em {name} depois disso.",+ "chat.notice.backupRequestUnderWay": "Mudou para {name}. Seu pedido ainda está em andamento aqui e continua em {name}.",+ "chat.notice.backupConversationBusy": "Mudou para {name}. Esta conversa está em andamento, então sua mensagem não foi enviada de novo.",+ "chat.notice.backupQuestionWaiting": "Mudou para {name}. Uma pergunta de um colega espera sua resposta nesta conversa, então sua mensagem não foi enviada de novo. Responda à pergunta e envie sua mensagem de novo.",+ "chat.notice.backupMessageMissing": "Mudou para {name}, mas não foi possível encontrar sua mensagem para enviar de novo. Envie a mensagem de novo.",+ "chat.notice.backupContinuingLimit": "Continuando em {name} depois de atingir o limite de uso",+ "chat.notice.backupContinuingSignedOut": "Continuando em {name} enquanto {engine} está sem login",+ "chat.notice.backupCouldNotContinue": "Não foi possível continuar em {name}: {error}",+ "serverError.setup.mausbotMissing": "Não há esse MausBot",+ "serverError.setup.mausbotOwnerOnly": "Só a pessoa dona deste MausBot pode fazer isso",+ "serverError.setup.noIntroToFollowUp": "Esta conversa não tem uma apresentação para continuar",+ "serverError.inbox.missing": "Não há uma caixa de entrada aqui.",+ "serverError.inbox.lineMissing": "Essa mensagem não está na sua caixa de entrada.",+ "serverError.inbox.answerRequired": "Isso espera sua resposta. Responda ou feche o pedido onde ele aparece.",+ "serverError.instance.settingsInvalid": "Informe um caminho válido para a CLI, nome de conta, pasta de configuração, opção booleana de ferramentas ou tempo de espera pela resposta de 1 a 60 minutos.",+ "serverError.instance.replyWaitUnsupported": "O tempo de espera pela resposta só está disponível para servidores compatíveis com OpenAI.",+ "serverError.mcp.personalHeadersShared": "Valores de cabeçalhos MCP pessoais não podem ser salvos na configuração compartilhada. Salve sua chave na conexão pessoal.",+ "serverError.mcp.testSignInFirst": "Entre na equipe para testar sua conexão pessoal.",+ "serverError.postiz.adminOnly": "Só o proprietário ou um administrador pode gerenciar a conexão com o Postiz.",+ "serverError.postiz.keyAlone": "Cole só a chave de API do Postiz.",+ "serverError.postiz.addressAsText": "Envie o endereço do Postiz como texto.",+ "serverError.secret.localService": "Um serviço local não pode inserir uma credencial. Insira pelo OpenMausBot.",+ "serverError.secret.cloudOwnerOnly": "Só o proprietário deste Cloud pode inserir esta credencial.",+ "serverError.secret.conversationOwnerOnly": "Só a pessoa dona desta conversa pode inserir esta credencial.",+ "serverError.secret.credentialSavingFromPhone": "Esta credencial está sendo salva por um celular",+ "serverError.secret.credentialDismissed": "Este pedido de credencial foi dispensado",+ "serverError.secret.credentialSuperseded": "Este pedido de credencial foi substituído por um mais recente",+ "serverError.secret.notSavedYet": "Ainda falta salvar: {label}",+ "serverError.secret.notReadyToResume": "Este pedido de credencial ainda não está pronto para continuar",+ "serverError.secret.noLongerConfigured": "Não há mais configuração de {label}",+ "serverError.department.moveChiefConflict": "Uma equipe só pode ter um chefe de gabinete. Troque o chefe antes de mover este bot.",+ "serverError.department.membershipChanged": "A composição da equipe mudou. Abra o diálogo de novo e tente outra vez.",+ "serverError.mcp.addressAsText": "Envie o endereço do servidor MCP como texto.",+ "serverError.mcp.addressChanged": "O endereço do servidor MCP mudou. Recarregue o servidor e tente de novo.",+ "serverError.attachment.alreadyInMessage": "Este arquivo já está em uma mensagem, então ele será mantido.",+ "routines.server.backupSignedOut": "Começando de novo na IA reserva: a IA deste bot está sem login",+ "approval.applied.waitFollowUp": "Próxima ação de {name}: {followUp}",+ "chat.notice.waitDone.urlContains": "Espera concluída: {label}. {url} agora contém “{text}”.",+ "chat.notice.waitDone.urlMissing": "Espera concluída: {label}. {url} não contém mais “{text}”.",+ "chat.notice.waitDone.fileExists": "Espera concluída: {label}. {path} já está disponível.",+ "chat.notice.waitDone.fileMissing": "Espera concluída: {label}. {path} não existe mais.",+ "chat.notice.waitDone.fileChanged": "Espera concluída: {label}. {path} mudou.",+ "chat.notice.waitDone.processRunning": "Espera concluída: {label}. {process} está em execução.",+ "chat.notice.waitDone.processGone": "Espera concluída: {label}. {process} parou.",+ "chat.notice.waitDone.botIdle": "Espera concluída: {label}. {botName} terminou.",+ "chat.notice.waitBotGone": "A espera por {label} foi encerrada: {botName} não existe mais.",+ "chat.notice.waitExpiredOne": "A espera por {label} foi encerrada após {hours} h.",+ "chat.notice.waitExpiredMany": "A espera por {label} foi encerrada após {hours} h.",+ "mcp.personal.oneHeader": "Conexões MCP pessoais aceitam um cabeçalho. Remova os cabeçalhos extras antes de salvar.",+ "readyBots.routine.socialWeekly": "Plano semanal de publicações",+ "pair.sessionEnded": "Sua sessão terminou. Pareie este dispositivo de novo para continuar usando.",+ "chat.notice.computerDesktopOnly": "Só o app OpenMausBot neste computador pode permitir que um bot o use. Abra o app aqui ou deixe o bot trabalhar no próprio navegador ou em um desktop na nuvem.",+ "chat.notice.computerPermissionsThenRestart": "O OpenMausBot ainda não consegue usar este computador. Confira se o OpenMausBot tem as permissões que pede e reinicie o app.",+ "chat.notice.computerNotReadyDetail": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}",+ "chat.notice.computerNotReadyMacPermission": "O OpenMausBot ainda não consegue usar este computador. Motivo: {reason}. Abra o OpenMausBot de novo depois de conceder a permissão do macOS que falta.",+ "chat.notice.computerSystemUnsupported": "Os bots não podem usar este computador neste sistema. Escolha outro local de trabalho para este bot",+ "chat.notice.computerAiUnsupported": "A IA deste bot não pode usar este computador. Escolha outra IA ou outro local de trabalho para este bot",+ "serverError.engine.signedOut": "{name} está sem login."}diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex e23f105e0e..bc6286135b 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -27745,7 +27745,191 @@"shortcuts.toggle-sidebar": "2183a13051ac6a0e0c896d816651c152fc79b344fbb3f888b36066b66a44d23d","readyBots.bot.social.title": "54a270fc36c200c7af59e3cc96b6ff8287c1367eae6685d236a34c7728a08200","readyBots.bot.social.description": "3e240a2e1502ae75e71bc63e0eb547202788f608d3470e49262305e69be9a1a7",- "readyBots.bot.social.try": "cdcf2b01b855c12d8ffe3be8df1be3ae3476f1f4d1c98b8a9842c126effeb034"+ "readyBots.bot.social.try": "cdcf2b01b855c12d8ffe3be8df1be3ae3476f1f4d1c98b8a9842c126effeb034",+ "native.cloud.otherGone": "3aee5eff525d9ea434638e7a76c956f577614b42f85108e4f2d0eb0da7d8864e",+ "native.cloud.otherNotReady": "ef07acd2bdee22a89fc371b4d76aa6f5830c98429544909e1d0baedca44ef747",+ "native.cloud.otherNoLongerYours": "eca2b21b347dc8febf108f0e38f20fd7100f5514298ac23e1a8384f74abb7eca",+ "native.cloud.otherNotRunning": "0007b3882c68ae457c9d5cd8142dcbe9f815a087fa2bb4ec3910aaa7068393c3",+ "native.cloud.invalidAdd": "f94d1fddd9578235465f44f171ea7c61d97f7bb611f2e4bb7c81d1223e879a05",+ "native.cloud.invalidOrganization": "7523286be651f69e7b763861d30a0eaf0bfae1515a2fbbd63f2141e6168cacf3",+ "native.cloud.invalidColor": "6b2d2f44c5b1fb814c53cefa2555d39815ac796bcd043c10b7f49205e476afb7",+ "native.cloud.invalidRemove": "56ac9d821966bfa57310164cfcff0e67a8a782d1301ccd378d96e8c295202815",+ "native.cloud.ready.open": "17b8945ce5adc61a78d560ace5a9ec120d9952f35b49a1473bccf28eb9815a16",+ "native.cloud.ready.quotedTitle": "b1562b98b491d6aaa6cb0fa20b9095daef54db6ad77f29837d81b3a4137482a8",+ "native.places.noLongerHere": "6547d7a9861ce1d9e502d7d09c6b2ff979659e9f39130328b0b0afbd964fb1c8",+ "native.places.cannotAdd": "f7ed598ede7bd95d48710b80409a0d1ddb092e596b79e263140bd933becd6268",+ "native.cloud.addSignIn": "291b302c6c1ad13583189ce080734ed18dd207cdbc81ddb08092cbb41d122fdb",+ "native.cloud.addPlanAndName": "f335c523935932f6c35ae70d3993b35f6cc0ab9b3b4e19419b8c8bcade040efb",+ "native.cloud.addOrganizationName": "d999655bc46aadd9240d6663bd7a800ac28233881e93253339e7104acdafb09e",+ "native.cloud.noNewCloud": "a1b0f61edd741f6653aae331672a064320aa56ed9b4ccaa490cd53e5ff0dff03",+ "native.lend.moveWaiting": "5adf927872d95bb91417a4a9820a72552545bc389a87e7543e91c97e99609edc",+ "native.lend.moveNotStarted": "83c7a1bc1a8185025e4062e9fd1d1922205f521612de08101ef8ce57cfb255a4",+ "native.boot.sharedFolderAdvice": "038b2585e8c3a09e2925e0a7297bbd4af83f2d41ffc57e5774340b27c3a27139",+ "native.lendTray.pause": "858e4ba7a29fd38b630ed73a79e2738333b3fc6778fafa90252f5556c1262fdc",+ "native.lendTray.resume": "d640c7421da066618a39daf4266da5f61f66a9b1afcd626481b831a17064965d",+ "native.lendTray.activity": "f2d246986894911f4898ba092a95b43633b610c4db249c92eec075efca0286c3",+ "native.files.newFromCloud": "6b2f81bc8f55366f6e53c9b58178f99f9ec229a091d1951957fcb0c09ba33c3b",+ "native.files.nameNotSupported": "1f42a46831173b8569181b3f68920f196177c8f8c2b479aa4a4776ac6ffc1776",+ "native.files.gitProtected": "4064faa75094fd53ed08917f88e501578fa4b4dba8a61d7cb98281896330de01",+ "native.files.changeDamaged": "7d5fb7e3b39fdf4cb29e51b8870a36d9ff5214c7ad842cfb361b2385d91c558d",+ "native.places.chooseColor": "ada22202102566ffa68186a7bcf9b1f1fef694bfebf9023f647c5354a35519f7",+ "native.places.noColor": "406eafe9028264ceeeca5d944a418b58f1f79579a3d7e1d42afbe9f5cb1a13a8",+ "native.talk.listening": "bbb4106e814467bd2f2db8fa8076072c471009f3a3d73d19b2e64c44c1ff3ad8",+ "native.talk.sending": "b85bc916033e3fa10bfd59fa1c3637b3118545726b4476d587c734239b361620",+ "native.talk.thinking": "f15724c848c24f739353058a73d3b8994c3e6185dbc0f7c3837293ae3be79562",+ "native.talk.needsYou": "af31be696ddd059e455911305c04447de13d66e3eeb365e02c8633dca266d225",+ "native.talk.stillWorking": "6fa8b166634a7d5f7d644ef342f5f88f66822f29da3e69c3b28b4373715be047",+ "native.talk.dismiss": "48845bff334a50a59aaecf499f28a7a24c3b4b891b8b18a9f1169ad8e8a6b261",+ "native.talk.releaseToSend": "ab9cc6e5aee4cb5bf581789a92d74020c9c792a33aa0dfbf7e36d590b6111d79",+ "native.talk.voiceBusy": "2fc7906942d646c9e40d6c542cdea6f58ffae001bbc1fea3b36be36bee23dedf",+ "native.talk.openMausBot": "c9f2a827faea94bb7bed966850dcf94d451853d9dcd5c8d2e6059c4c10b9d85b",+ "native.talk.starting": "02297904f4875eff2de696a6091d7e1fe098c3f701662ed32bcbe826d014167d",+ "native.talk.setUpFirst": "582cc7411f245557eb4947f07b0654163f5181907db0375a9a1ae3a9df3e2203",+ "native.talk.movedToCloud": "0fc36d16f55cb89364b8acc9d0d2358499d25b2143e0e3f3cc05fc2295a3d53a",+ "native.talk.permissions": "04a0129782b55a3e8d7ba229672282b525f992d888ed8c58629e8d6358d94615",+ "native.talk.dictationOff": "2e0de2e869a1c228340493de6ff03fa3f01f122a908f3bbb2a43632cf89b6aeb",+ "native.talk.unavailable": "7ec3696ce28870c7608f70952a03b9e2979649362f3c3000fa04eedcfdfdfe1e",+ "native.talk.failed": "f40e31315faa765a7f8b9bb93674cc84316ac5140754fa7c77e593a5ec56eead",+ "activity.tool.team.cancelWait": "4b647d2c844fa10e2db03d6a6da75b29266333eb91c6929e24ea9c7c762c7b21",+ "activity.tool.team.deleteTrigger": "8043e69a8dd617aca1d0cab8209449387f49d1be02a08bd51a0c9443f69bd98a",+ "activity.tool.team.listWaits": "aee24d220c25b4c64b50cf58f165de841a264e838b9394a41cb2d2aa0857885a",+ "activity.tool.team.waitUntil": "a5ac4a5834512d773549fcab99c8b8baeac5c642510121c20d53183479958930",+ "serverError.request.bodyTimeout": "933920bb30e72e04be6e5fe5b9f7b34de94f039d8cb37a5e3ea9ab09de1c8523",+ "serverError.browser.restartingUnresponsive": "4f6c64627776dc2322b2ac45a39ffae4c9f160175a1df973806ea9f7cf13bb45",+ "serverError.computer.desktopOnly": "d988ce68614e8abc7c8a3f127a09ad00f44254dc732a40b8bbd925036412ea45",+ "serverError.computer.permissionsThenRestart": "29ea1210fc84f84e15e26dff95c448731bbdd60ecc358428cdebb9594d16b6ab",+ "serverError.computer.notReadyDetail": "a79f9a0ceb7124aeba6dca7ee05432c50f1c2b1f7bd88ddd7be1bfed5ca7a3e4",+ "serverError.computer.notReadyMacPermission": "5c574832e65034fc6ea339fb9e79eb1dfba1235a9cd46bf9196de5a73f6a8efc",+ "chat.notice.copilotAccountRefused": "5cfc3375ffaf9625d03b8428c82d449dfa27213b8850dedf99d642ed117f10c0",+ "chat.notice.acpQuietUsageLimit": "08860c3487e61b71d31512e4dae658d3728cbf909b59f77b6d4f346516d2dc80",+ "chat.notice.acpQuietStuck": "60ddaad225a745f3f8084c339c41f8dae45795bd8743ed511846c83bb7694bab",+ "chat.notice.acpModelRequestFailed": "52b4d4b41e9c2bb6d0a84f10b1f8032fbc414bcc5f2cfb42270a14de60d4c3b6",+ "chat.notice.acpModelFallback": "561bf92c14b4e6a8d14f78d43cd2530436eb8f93ed7997b3e6644e1ba45ef717",+ "chat.notice.codexActionMayHaveRun": "fc804b3df742479b6287ae1173eb0feb80fc4d41c4612f95a6f5f69e74b63338",+ "chat.notice.modelServerStoppedAnswering": "704052ab0b1e358f6c7703329286ec3a3a0f03df1d0af71735f6e56207966d88",+ "chat.notice.piModelNotConfirmed": "7cae104f9c836f120d4485e571e12dd0744938058f5a1709933378fb23b731d8",+ "serverError.install.invalidDetails": "43d41c1d32721b95fb994706ec6a8deaafcf273e29934569142e0493ee971508",+ "serverError.install.versionGone": "592d4c71ebbd8bb6539812bb37b044ed7073154bfe24cb96226e8ec5a51d50d1",+ "serverError.install.downloadLimited": "51e6202e0e86fad735c8f0e8b2d29edff870b87e52009517ddf3d8cfef203025",+ "serverError.install.siteNotAnswering": "91ef23ddc9a60e36b2136f1cf2cd193bde76deedadd22e933c2e91b575205313",+ "serverError.install.downloadFailed": "dd0acb13ece899e92fff7f030a314aad972fdb22e6f4932ddfddd1fa4407c1ce",+ "serverError.install.downloadTooLarge": "9bb181b21085710bce64787bde9a3029132594415beb792b1e29cddd4a4329db",+ "serverError.install.unofficialDownload": "354c649f96c868fa72dab812425d6858d8092090fdef5d4393350b7b356da8fe",+ "serverError.install.redirects": "2adbf350dfb78a94f3d1ec162474e4fc51d6bc4162444638cbbd0429c0c61304",+ "serverError.install.safetyCheck": "8a9adc2afd8202f099af396b1a3a94d748364439799a6e0ca50a8630e0ea176f",+ "serverError.install.downloadTimeout": "1b94e9f0b8b13a375832409066d3c5dcb700d5d2e135c66ec9ca5d623c1b7fed",+ "serverError.install.unsafeArchive": "b27ff0ce572005799c2b529b07d4535b158d6175d0954cacf0819884ca03e413",+ "serverError.install.unsafeFile": "87a745f16d827628f91c627ddf6cbb72b82aa27e4ccda7270d946d62da254439",+ "serverError.install.notPlainFolder": "73191f997723dfabbd28a9231a84a16fcbe02c2f21578db9e0c300255f5c42e2",+ "serverError.install.unexpectedFolder": "ae490a8e3d7d2bdb92e550e44a63a66f9f02b2bde7c186b54fd60ce6b07f7dd7",+ "serverError.install.diskSpace": "89e08adfc6b96e45c22cdad88222f0ccfa543186fd275f95de12bce7c32dd5dc",+ "serverError.install.openElsewhere": "0ac4d2f5c2aa28f44d5cf4e1753375cae37e0064ead9cb84129980ba15d1bf46",+ "serverError.install.cannotWrite": "b4e663a1561c894dc98918985119fd07cb0d61110e1141a7bdb0395bbcc051c2",+ "serverError.install.failed": "d661c42d1cf5df37328ba368ce4996f88929c4ddd22b6e3f4423212faae2f963",+ "serverError.install.noDownload": "fd48558bf917815a84dbbd81223344fa8b99eb184ef20f16d9f1e388e5b5fed5",+ "serverError.install.existingDoesNotStart": "55b34bc3f6515752a7647c0297f83432b6cc2b643ace152d9ab3f7831f425054",+ "serverError.install.programMissing": "880e10682a696736ec866d8e19e29ee971dc0db594ba9a1440c8164a6de2c632",+ "serverError.install.notSigned": "cdd644c044007407c2ff77de61f286f6cdd9480d4e10579c89b4f28aa0d81783",+ "serverError.install.downloadDoesNotStart": "ad9deed0f0b930378216a2f85217f4f92afdf883b4e97f1fcf81eb72a55b40b6",+ "chat.notice.waitingApprovalElsewhere": "d4bbfe845476d7e8fcea058998607657987988fe26a1a4cd42df1055c74e1100",+ "chat.notice.waitingAnswerElsewhere": "77b590c7a4b351a8b74fcfc915e398eb081b7151ae9f7a4592bc5717425af94b",+ "chat.notice.teammateNeedsInput": "fa955b3cdcc23fe91c57178f8a33bc3b29d70bb2c6bbe2605695699060935756",+ "chat.notice.relayCouldNotContinue": "b6486cd4a898b74d774f7f698b856d56ed4426eee7bdd53411d2711be57e7238",+ "secretCard.delivery.fileNamed": "ef644ac49d3207da1c751da6144c554d455f64a6421f80b62cb1b9251740144a",+ "secretCard.delivery.refNamed": "1ecb68e606e37fac10385e6f33fd3bed3089891f2eab42bbf64b3d42c7af02fd",+ "serverError.secret.missing": "7d2490ff84af3a76ff9826347a959f80ccfee07a6e79bc1fa830e8d260bed269",+ "serverError.secret.settingsCard": "81e4e9edbeddb73b50c5f93199f14aea5973e801c968427fac1c385badc34a8d",+ "serverError.secret.savingFromPhone": "8a0fddb4b589e7f5db8287391d1b005775f9868853433e0d180fa09648f12b34",+ "serverError.secret.declined": "496769a1efcf1c10387f9248b68beb398d3cdedcb3338c2e0e196c144c3b7e2a",+ "serverError.secret.replaced": "8cfef101076aed8ab1583a5f96ee04adba92597bd54b24c3e98706519e4a20da",+ "serverError.secret.taskStopped": "3898e2ba195c8a2b3f9788fe341ea010129b993e69e7fd027ee5c5a6cf327b6a",+ "serverError.secret.alreadySaved": "6765766bc1e38dd3f4fd0c8b499f8b9256921d96fe1fb5992e203f8c384e859a",+ "serverError.secret.valueSize": "793d6a00feb3a1d14b14edf013161f5ff37fa9a2bd5dbbd6eb11d0982e0e3b12",+ "serverError.secret.notKeptSafely": "dc94387203c19d6ecd1854a822a46bd44b1d284134eca1898189bc46bfe97c1f",+ "serverError.secret.unavailableLower": "479322a099b38e281096cdb65b57591166e9b5475491b785fc3a187895d8b31d",+ "chat.notice.provideSecretSecurely": "87b473dfb41b8d9dfb8abaa0369195c03e28e0d6c761aafbe5c01986b6647bce",+ "serverError.signIn.requestMissing": "fd3ea695173a37e52da15d352965fdd3f491c13c913e2a8e89b0af78782b6111",+ "serverError.signIn.requestReplaced": "a9460648cf12071df0b5e7a605426354aa7e42ef4113ff37b39a37bef8c71a4d",+ "serverError.signIn.answeredInChat": "f16cf67072fcef21f81dd709e5ca5267df35f8c8e9b8614fdd0cfe45fd9f2d29",+ "serverError.signIn.alreadyDone": "237a0ffeebff813696e479790ac02a09ab85ee3d31dce3202f8c143b7d240322",+ "serverError.signIn.alreadyCancelled": "22c77f1cf1cff95324ea4cfe64576f3d48d90d0a3a9fc118f1519b247de7c174",+ "chat.notice.inboxNotPassed": "d26e1d09a34bc6a668ec93c8800a76d75962c9c09ff5de1533937b57a1e9945b",+ "serverError.inbox.answerNotPassed": "8fd91a3389bb500d98099d74f82a26b812773782ceb782ef1c35f3ab0eca3652",+ "serverError.room.nameOneLine": "c33de47a5d29729066950525807f39c5a3edd8466fa12f38071f50e2ad9f7f85",+ "serverError.computer.systemUnsupported": "08530a5e4f50a588d4bb0fe0de3806ba3593936a8ca739f0a092f7eee1ea563a",+ "serverError.computer.aiUnsupported": "6d9ae505ea50b010118c9b8dec93541889b39923edae9b4e5f06103ef9964f22",+ "chat.notice.engineSignedOut": "289d1731e8149d5d12d30df14deeb90f2cfd057a66fba105c0fcc6f6ef4e5a13",+ "serverError.wait.alreadyEnded": "be86b8a7a633810f0c30cbcaaefc5d2c752676503a408a309becb7deff463a2c",+ "chat.notice.failoverSignedInAgain": "f7ad07121dd657d29d8243d3d6026e32c97b33b513b79460fef44c43652860bd",+ "chat.notice.failoverSignedOut": "7bd97e3b465c2f6459a6df3c1509ff41dab29cb2f992a5e90aea48aeb676c40e",+ "serverError.botDefaults.nameLength": "99f0e0c98f56cc5679a5b10113f6d30ef44c35a44d9117e3e354dad1dfcdc9a7",+ "serverError.botDefaults.sectionLength": "cc502025433f0b1ca3c902b927eb55ebb8faae9c38fd24655d8e358b78610885",+ "serverError.botDefaults.invalid": "94ffcd279707a297db3074d3d01937ab6a825aaab505dc2fc3be8affcc1170dd",+ "serverError.postiz.addressHttps": "ff8bb2acb0f76b9ce1da758d19de80a8b67db10e742a5867f64aa474c1088095",+ "serverError.postiz.addressNoCredentials": "acb3c443aaa91f87d4802fdfe5c869d33123c957dc404d4bcfde9a6fb443f8a5",+ "serverError.postiz.addressNoQuery": "436c427990be5a00caed97248ba5fc8c102e393fcd7b7f94b1e0d822332fe771",+ "serverError.postiz.addressLocalHttp": "469ed26a0cafe7af098897f4b02109c74a4b477373ad90cf6de03fc5e6f3e723",+ "serverError.postiz.addressUseHttps": "1c2d68fddb84f435a3a2e8ec731b67956f049571239f3a37845c81cd7093da3d",+ "serverError.postiz.addressContainsKey": "b5694d4923d223cb8547cc824d75762266795e77db2cdb13ecb59d3afd825573",+ "serverError.postiz.mcpUpdating": "8a987de23f1d061adeb18d29c3aa090e908f45335bd6d692209f13dd47850d31",+ "chat.notice.backupCardWaiting": "029265428ed97a61eb238bc8b04fd914486677fabf8557ba32b87251c59258bd",+ "chat.notice.backupRequestUnderWay": "6ce7145a7d8cb57f3b40c61940c731a20380ebfc05f4f52b912f734d675fa19a",+ "chat.notice.backupConversationBusy": "75d9854dac2ac287e682aef0af82afd25c1e4000370e54b41df672a4690ce40f",+ "chat.notice.backupQuestionWaiting": "f74d1708f3e29ad2ebada94650d973f38a7e956a0bbc39b183d9630741c28ed0",+ "chat.notice.backupMessageMissing": "4f435d35fc7b63f78920e7fe4e3724068c4c45e20c85ab2210a05a4251607739",+ "chat.notice.backupContinuingLimit": "563bc3e55dffac4c75c9ca9bebc33eb97b911ca509e257862b30fec230567237",+ "chat.notice.backupContinuingSignedOut": "68e8637a0c3340a1b68fc49b986f395386f2d22cb5de8b3328a4b9eae62c5314",+ "chat.notice.backupCouldNotContinue": "5ba38f5ed11f7520c8f33ddaf2a13e9ee79856f651e05596a5e09c92bcec4561",+ "serverError.setup.mausbotMissing": "c1ed7e1f9bfa032a7187a32b20546d9874f16a51ffc41a8e22c15c5d0b45bf32",+ "serverError.setup.mausbotOwnerOnly": "58540ecc388da24ce3b3fac3a78eeb15a0a0fcd79fa3f6310d742f64eae34f20",+ "serverError.setup.noIntroToFollowUp": "1294039a362f2d25ea41a6a84ffbaee28858047467696b61edfbf276081d5456",+ "serverError.inbox.missing": "5a19cd6834bd01f49f0b73e6c3725693cf6cd34c41f6cebc2511d18d921af6f4",+ "serverError.inbox.lineMissing": "8b9a435e44331a3f88d8f39edc7b0343adc951fdddd6435986ba8543837e2841",+ "serverError.inbox.answerRequired": "3208e39812f356fe7bb492db1d8f2b7f6cce30f008d27eda5504e3192efb0241",+ "serverError.instance.settingsInvalid": "cd92791f3873d519aba66f64f5246bd23a620ed31e856f2eabe8555839f8e8c8",+ "serverError.instance.replyWaitUnsupported": "7f6042041614fd1e764460dc834dd0cee36b00435aac1208bafe93b094225176",+ "serverError.mcp.personalHeadersShared": "8d7232075cb7dcfc5fbe2b1b9e7f02ace4651a0c890005c13a11310e40b9a41f",+ "serverError.mcp.testSignInFirst": "4ff258b9dcf4d9f90786103ced0a0aad1bf543402b042c6c32813a8b98466b9f",+ "serverError.postiz.adminOnly": "da2309636710bad3845b0bfd0d3b7324be7e982665658e87a9d53ff1418a8084",+ "serverError.postiz.keyAlone": "56bddb2850bc4b10d5cc6fa7b670d600b865e25147d979bd1139b9dc531a8b66",+ "serverError.postiz.addressAsText": "2cc8897a77c2f95a126bb7e51fa950228dff7816698fae23c42926f4c95aaad4",+ "serverError.secret.localService": "4b0162592d4aef17a38eab6974cde8180273d06bfb64f343ebae4c0569ff2292",+ "serverError.secret.cloudOwnerOnly": "a04a646a0e5f96294bfc7af3520e890a1aace6143e5d76fb2b1a07bada79c7ea",+ "serverError.secret.conversationOwnerOnly": "4c5d037f35f691678cfbb51d33faf81b4d1cbaae7b9da5a58799365defa96863",+ "serverError.secret.credentialSavingFromPhone": "f8cec438bdc2963e45e827ac469d8ab66272c89f5f25bf2fcac298517b495628",+ "serverError.secret.credentialDismissed": "222dedbd142a8e1f56782d690f98e27e44cf1bbf0f5edc9847c2c65c5d6c5bde",+ "serverError.secret.credentialSuperseded": "065b58646192af9feb2cc9f84bade1a7ef7aa8fb62778ec5eac776e86da757e3",+ "serverError.secret.notSavedYet": "ca8ff7b83e2f8d5c170cfd044ae14decd3e7e9cdf98b46b9f59b026286ca925b",+ "serverError.secret.notReadyToResume": "e1ae4313e92ee73ba2e96fd18b9f5889c1143419381e8cd6a5866d9a3447b709",+ "serverError.secret.noLongerConfigured": "42879245ea0fe524513d5a319bd3bbd4ca5dc3d0fbeb6dc539e67580d4eea279",+ "serverError.department.moveChiefConflict": "bd41be90ba01536e69a664ae6b65978f1201ba359154c95b45015fbae0aac712",+ "serverError.department.membershipChanged": "a6c5739d66acaca35972d066c85bef876ada566980fda5efb69f60442382ddb1",+ "serverError.mcp.addressAsText": "7e5e3b6b9e21bf533c57e554da92174fd2dfb9e3b1abaeb64db47214aaaac802",+ "serverError.mcp.addressChanged": "90ca243defa15b0bc3114db5cad30a358b212d7612156231c59d761c92194a49",+ "serverError.attachment.alreadyInMessage": "fd6c2f486d0d7176b20781f254de59f379fb9e8bf56787a1488ecfb41753588e",+ "routines.server.backupSignedOut": "8d8df3bbeceb9f4d1cd2d020ff23f1d843a4df56e991b5f1d0de49a12655d520",+ "approval.applied.waitFollowUp": "f0c405115240f936ec37a3db3302bba91ea3048c8bc35bb2ba5b00791e1708c5",+ "chat.notice.waitDone.urlContains": "b3e80997f44f97e967d6e8908a0865476f12cb5dbbcf1077600c1771fbad42c9",+ "chat.notice.waitDone.urlMissing": "dc37c1191523d15d182235789a57d3904128c83c37f8096e3bc3d4a10e938d07",+ "chat.notice.waitDone.fileExists": "74ef3747ac009fd1c17c89fb51afb8ba4afc0f12c7403f57cb6e8ff1b9b0adcb",+ "chat.notice.waitDone.fileMissing": "2caeb41b7b234455001214145f9e2a60914d88f069aa3a5f2c85ee3dbd403995",+ "chat.notice.waitDone.fileChanged": "57147fcc39cd51e5d8191da50dcfcc7b48ac4c9af0b6625118ebd14bacbaad71",+ "chat.notice.waitDone.processRunning": "ab6f3b15e926d616c756d23a8db786506b25e4ec31fd5af70f3bc6410044e061",+ "chat.notice.waitDone.processGone": "db08c34ff74b3c34cdffe5369ec0cdc9b8fe0993c92449661e0f144528f059fe",+ "chat.notice.waitDone.botIdle": "69707b959f72f4968c648e441d32c6b9d5ea5bbb4c79673103041a6e3d1e894e",+ "chat.notice.waitBotGone": "d305a79d72567a6da95594adb07e30a2466b750e4571ed5e82f8b904a9118680",+ "chat.notice.waitExpiredOne": "ed6212ac521edf75a56386ebaaf6e8b3e122a1670c0bf176e60f0a38a8552486",+ "chat.notice.waitExpiredMany": "9344b8169076d8279b539596b3da3a1bab779dcce73a7a5120883ed74bd8c31c",+ "mcp.personal.oneHeader": "4504094076186e6b4c5e0c051f45cfbbd2f7f312bb8e9b736f111b71e3b3a1f3",+ "readyBots.routine.socialWeekly": "319894bfa62b6f9d469aaef044f29fb4710de649e5159c9dad0238917b0c5247",+ "pair.sessionEnded": "33cb1e58930b6dfc59533a854ebbd7fd0de2606fb5d60b2750d9c828ac910064",+ "chat.notice.computerDesktopOnly": "d988ce68614e8abc7c8a3f127a09ad00f44254dc732a40b8bbd925036412ea45",+ "chat.notice.computerPermissionsThenRestart": "29ea1210fc84f84e15e26dff95c448731bbdd60ecc358428cdebb9594d16b6ab",+ "chat.notice.computerNotReadyDetail": "a79f9a0ceb7124aeba6dca7ee05432c50f1c2b1f7bd88ddd7be1bfed5ca7a3e4",+ "chat.notice.computerNotReadyMacPermission": "5c574832e65034fc6ea339fb9e79eb1dfba1235a9cd46bf9196de5a73f6a8efc",+ "chat.notice.computerSystemUnsupported": "08530a5e4f50a588d4bb0fe0de3806ba3593936a8ca739f0a092f7eee1ea563a",+ "chat.notice.computerAiUnsupported": "6d9ae505ea50b010118c9b8dec93541889b39923edae9b4e5f06103ef9964f22",+ "serverError.engine.signedOut": "289d1731e8149d5d12d30df14deeb90f2cfd057a66fba105c0fcc6f6ef4e5a13"},"zh": {"highlevel.unavailable": "87b8ac7f7610e6dd69f520bc59058fd92f307b9f4bcf804075f25d08bcaa7533",diff --git a/src/main.tsx b/src/main.tsxindex 6f5edad18f..2dda0a1b31 100644--- a/src/main.tsx+++ b/src/main.tsx@@ -14,7 +14,7 @@ import { settleAdvancedModeDefault } from "./lib/interface-mode";import { BrowserSignInPage } from "./pair/BrowserSignInPage";import { PairPage } from "./pair/PairPage";import { HomeScreen, SignedOutAtHome } from "./components/HomeScreen";-import { endedBeforeReload, forgetEndedSession, SESSION_ENDED_REASON } from "./lib/session-ended";+import { endedBeforeReload, forgetEndedSession } from "./lib/session-ended";import "./styles.css";// Before first paint; settleAdvancedModeDefault must run before applySkin writes omb-skin.@@ -43,7 +43,7 @@ async function chooseRoot(): Promise<React.ReactNode> {}const session = await readSessionState();if (session.kind === "unauthenticated") {- const pair = <PairPage initialCode={null} reason={endedBeforeReload() ? SESSION_ENDED_REASON : session.error} />;+ const pair = <PairPage initialCode={null} reason={endedBeforeReload() ? t("pair.sessionEnded") : session.error} />;return home ? <SignedOutAtHome bridge={home} fallback={pair} /> : pair;}forgetEndedSession();