Skip to content

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

Server lines in the person's language: the way in, a guard, and bug report lines (#3931)

Milind Soni97ee8c73197e
diff --git a/scripts/bundle-server.mjs b/scripts/bundle-server.mjs
index 7f5785d049..854a12446e 100644
--- a/scripts/bundle-server.mjs
+++ b/scripts/bundle-server.mjs
@@ -2,9 +2,10 @@
// packaged app ships no node_modules. Entry points keep their exact relative
// paths under dist-server, where the server locates each proxy by path.
import { build } from "esbuild";
-import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
+import { serverLocalePlugin } from "./server-locale-plugin.mjs";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const server = join(root, "server");
@@ -73,7 +74,7 @@ await build({
// Written after tsc, replacing its output for these entry points.
allowOverwrite: true,
logLevel: "info",
- plugins: [yamlEsmPlugin],
+ plugins: [yamlEsmPlugin, serverLocalePlugin],
banner: NODE_REQUIRE,
});
@@ -88,6 +89,7 @@ await build({
outfile: join(root, "dist-server", "mcp-server.js"),
allowOverwrite: true,
logLevel: "info",
+ plugins: [serverLocalePlugin],
});
// `openmausbot serve --tunnel` spawns the connector guardian as its own
@@ -129,6 +131,7 @@ if (existsSync(join(root, "enterprise", "server", "index.ts"))) {
outfile: join(root, "dist-server", "enterprise", "server", "index.js"),
allowOverwrite: true,
logLevel: "info",
+ plugins: [serverLocalePlugin],
});
copyFileSync(join(root, "enterprise", "LICENSE"), join(root, "dist-server", "enterprise", "LICENSE"));
}
@@ -159,3 +162,7 @@ await build({ entryPoints: [piMcpExtSrc], outfile: piMcpExtDest, bundle: true,
// package.json, and the server reports this one (server/environment.ts).
const { version } = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
writeFileSync(join(root, "dist-server", "package.json"), `${JSON.stringify({ type: "module", version })}\n`);
+
+// tsc copies the language packs server/server-lines.ts imports (13 MB) beside its own output. The bundles above carry
+// the server's keys, so nothing reads the copies.
+rmSync(join(root, "dist-server", "src", "locales"), { recursive: true, force: true });
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index 68218bdb41..ebbea18e03 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -38,9 +38,17 @@ export const AREA_CHECKS = {
* shards, as vitest filters. Locale tests: every test that reads a translation
* other than English (the renderer's files take about nine minutes in one
* process), with the Electron node tests, which compare their own copy of some
- * strings with every catalog. Docs tests: every test that reads the docs. */
+ * strings with every catalog, and the server's tests of its lines in other
+ * languages (they load server/server-line-packs.ts). Docs tests: every test that
+ * reads the docs. */
export const VITEST_SUBSETS = {
- "locale-tests": { part: "locale tests", files: ["src/", "scripts/generate-locale.test.mjs", "scripts/testing/key-readback.e2e.test.ts"], shards: 2, nodeTests: true },
+ "locale-tests": {
+ part: "locale tests",
+ files: ["src/", "scripts/generate-locale.test.mjs", "scripts/testing/key-readback.e2e.test.ts", "scripts/server-locale-plugin.test.ts",
+ "server/server-lines.test.ts", "server/host/devs-reports.test.ts"],
+ shards: 2,
+ nodeTests: true,
+ },
"docs-tests": {
part: "docs tests",
files: ["scripts/testing/analytics-docs.test.ts", "server/model-providers-docs.test.ts", "src/locales/vocabulary.test.ts"],
@@ -51,7 +59,9 @@ export const VITEST_SUBSETS = {
/** Renderer files that also run outside the renderer: the server imports
* them, or the macOS app-frame smoke bundles them. ci-scope.test.ts holds this
- * equal to the import graph. */
+ * equal to the import graph. The language packs are left out, though the
+ * server reads their "server." lines: a change to English runs every Linux test,
+ * and one to another language runs every test that reads it (the locale tests). */
export const SRC_OUTSIDE_RENDERER = [
"src/components/app/app-frame-host.ts",
"src/lib/citations.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index e0fa45fee1..48e1967532 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -170,9 +170,10 @@ describe("CI outputs", () => {
it("runs the locale tests in their own shards, with the Electron node tests, when no full Linux run covers them", () => {
const out = ciOutputs(selectCiScope(["src/locales/de.json"]), PR);
expect(out.jobs).toEqual(["vitest"]);
+ expect(VITEST_SUBSETS["locale-tests"].files).toEqual(expect.arrayContaining(["src/", "scripts/generate-locale.test.mjs", "scripts/testing/key-readback.e2e.test.ts"]));
expect(out.vitest_matrix.include).toEqual([1, 2].map((shard) => ({
os: "ubuntu-latest", part: `locale tests ${shard}/2`, shard, shards: 2,
- files: "src/ scripts/generate-locale.test.mjs scripts/testing/key-readback.e2e.test.ts", e2e: "all", node_tests: shard === 1,
+ files: VITEST_SUBSETS["locale-tests"].files.join(" "), e2e: "all", node_tests: shard === 1,
})));
expect(ciOutputs(selectCiScope(["src/locales/de.json", "src/App.tsx"]), PR).vitest_matrix).toEqual(vitestMatrix(["ubuntu-latest"]));
});
@@ -385,7 +386,9 @@ describe("the repository's import graph", () => {
.flatMap((directory) => codeFiles(join(ROOT, directory)))
.filter((file) => !TEST_FILE.test(relative(ROOT, file).split("\\").join("/")));
expect(runtime.length).toBeGreaterThan(500);
- const loaded = importClosure([...runtime, join(ROOT, "src/components/app/app-frame-host.ts")]).filter((file) => file.startsWith("src/"));
+ // The language packs the server reads its lines from stay locale changes (SRC_OUTSIDE_RENDERER says why).
+ const loaded = importClosure([...runtime, join(ROOT, "src/components/app/app-frame-host.ts")])
+ .filter((file) => file.startsWith("src/") && !/^src\/locales\/[^/]+\.json$/.test(file));
expect(loaded.sort()).toEqual([...SRC_OUTSIDE_RENDERER].sort());
});
diff --git a/scripts/server-locale-plugin.mjs b/scripts/server-locale-plugin.mjs
new file mode 100644
index 0000000000..13e1ea70f1
--- /dev/null
+++ b/scripts/server-locale-plugin.mjs
@@ -0,0 +1,21 @@
+// The app's language packs (src/locales/*.json) hold every screen's words, about 13 MB. The server reads only the lines
+// it writes itself, the "server." keys (server/server-lines.ts), so the server's bundles carry only those.
+import { readFileSync } from "node:fs";
+
+export const SERVER_KEY_PREFIX = "server.";
+const PACK = /[\\/]src[\\/]locales[\\/][a-z0-9-]+\.json$/;
+
+/** The pack with only the server's own keys. */
+export function serverLinesOnly(pack) {
+ return Object.fromEntries(Object.entries(pack).filter(([key]) => key.startsWith(SERVER_KEY_PREFIX)));
+}
+
+export const serverLocalePlugin = {
+ name: "server-locale",
+ setup(build) {
+ build.onLoad({ filter: PACK }, (args) => ({
+ contents: JSON.stringify(serverLinesOnly(JSON.parse(readFileSync(args.path, "utf8")))),
+ loader: "json",
+ }));
+ },
+};
diff --git a/scripts/server-locale-plugin.test.ts b/scripts/server-locale-plugin.test.ts
new file mode 100644
index 0000000000..70b9386d35
--- /dev/null
+++ b/scripts/server-locale-plugin.test.ts
@@ -0,0 +1,23 @@
+import { fileURLToPath } from "node:url";
+
+import { build } from "esbuild";
+import { describe, expect, it } from "vitest";
+
+import { serverLinesOnly, serverLocalePlugin } from "./server-locale-plugin.mjs";
+
+const SERVER_LINES = fileURLToPath(new URL("../server/server-line-packs.ts", import.meta.url));
+
+describe("the server's bundle of the language packs", () => {
+ it("keeps only the lines the server writes", () => {
+ expect(serverLinesOnly({ "server.reports.sent": "Sent", "chat.turnStopped": "Stopped", "serverish.key": "x" })).toEqual({ "server.reports.sent": "Sent" });
+ });
+
+ it("carries every language's server lines and none of the app's screens", async () => {
+ const bundled = await build({ entryPoints: [SERVER_LINES], bundle: true, write: false, platform: "node", format: "esm", plugins: [serverLocalePlugin], logLevel: "silent" });
+ const code = bundled.outputFiles[0]!.text;
+ expect(code).toContain("An das MausBot-Team gesendet");
+ expect(code).toContain("Sent to the MausBot team");
+ expect(code).not.toContain("notice.openFailed");
+ expect(code.length).toBeLessThan(1_000_000);
+ });
+});
diff --git a/server/host/devs-reports.test.ts b/server/host/devs-reports.test.ts
index a94bb80251..8a1024cdf2 100644
--- a/server/host/devs-reports.test.ts
+++ b/server/host/devs-reports.test.ts
@@ -3,6 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
+import "../server-line-packs.ts";
import type { DevsReportPayload } from "../devs-report.ts";
import type { SendOutcome } from "../devs-report-send.ts";
import { personKey } from "../person-key.ts";
@@ -17,7 +18,7 @@ const SCOUT = { id: "scout", name: "Scout", threadId: "scout-main", modelSelecti
const ROVER = { id: "rover", name: "Rover", threadId: "rover-main", modelSelection: { instanceId: "codex", model: "gpt-5.5", effort: "high" } };
function fixture(options: { dataDir?: string; outcomes?: SendOutcome[]; sessions?: PublicSession[]; ownerKey?: string | null; team?: boolean;
- profileEmail?: string; automated?: boolean } = {}) {
+ profileEmail?: string; automated?: boolean; lineLanguage?: DevsReportsDeps["lineLanguage"] } = {}) {
const dataDir = options.dataDir ?? mkdtempSync(join(tmpdir(), "omb-devs-reports-"));
if (!options.dataDir) dirs.push(dataDir);
const listeners = new Set<(change: StoreChange) => void>();
@@ -48,7 +49,8 @@ function fixture(options: { dataDir?: string; outcomes?: SendOutcome[]; sessions
working: (threadId) => busy.has(threadId), automated: () => options.automated === true,
engine: (instanceId) => ({ name: instanceId === "claude" ? "Claude Code" : "Codex", snapshot: { state: "available", authenticated: true } }),
appsReady: () => false, sessions: () => options.sessions ?? [], ownerKey: options.ownerKey ?? null, team: options.team === true,
- profileEmail: () => options.profileEmail, language: () => "en", recentLog: () => ["2026-10-27T08:59:00.000Z warn engine probe slow"],
+ profileEmail: () => options.profileEmail, language: () => "en", ...(options.lineLanguage ? { lineLanguage: options.lineLanguage } : {}),
+ recentLog: () => ["2026-10-27T08:59:00.000Z warn engine probe slow"],
send: async (payload) => { sent.push(payload); return outcomes.shift() ?? { ok: true, id: `report-${sent.length}` }; },
now: () => clock, timer: false,
};
@@ -179,6 +181,44 @@ describe("a message that tags @devs", () => {
});
});
+describe("what the person is told, in their language", () => {
+ const german = (person?: string) => (person === "p-ada" ? "de" : undefined);
+ const ada = { sender: { name: "Ada", id: "p-ada" } };
+
+ it("the line the bot passes on is German, and so is the system line when the bot does not pass it on", async () => {
+ const fx = fixture({ profileEmail: "[email protected]", lineLanguage: german });
+ fx.person("scout-main", "@devs die Bilder laden nicht", ada);
+ fx.busy.add("scout-main");
+ fx.reports.note("scout-main", true);
+ const answer = await fx.call("scout", "scout-main", { went_wrong: "Bilder laden nicht" });
+ const line = "An das MausBot-Team gesendet (Bericht report-1). Milind und Omkar bekommen ihn per E-Mail und antworten dir an [email protected].";
+ expect(answer.body.text).toBe(`Sent. Tell the person this line in your reply, word for word: "${line}"`);
+ fx.bot("scout-main", "Ich schaue mir das an.", { turnId: "t1", turnSucceeded: true });
+ fx.busy.delete("scout-main");
+ await fx.settle();
+ expect(fx.notices("scout-main")).toEqual([`notice: ${line}`]);
+ fx.stop();
+ });
+
+ it("a report that waits is explained in German, not twice when the bot passed it on, and its later send is told in German", async () => {
+ const fx = fixture({ outcomes: [{ ok: false, retry: true, why: "offline" }], lineLanguage: german });
+ fx.person("scout-main", "@devs offline", ada);
+ fx.busy.add("scout-main");
+ fx.reports.note("scout-main", true);
+ const answer = await fx.call("scout", "scout-main", { went_wrong: "offline" });
+ const waiting = "Noch nicht gesendet: der Server des MausBot-Teams war nicht erreichbar. Der Bericht ist gespeichert und wird so bald wie möglich von selbst gesendet, du musst ihn also nicht noch einmal senden.";
+ expect(answer.body.text).toBe(`Not sent. Tell the person this line in your reply, word for word: "${waiting}"`);
+ fx.bot("scout-main", waiting, { turnId: "t1", turnSucceeded: true });
+ fx.busy.delete("scout-main");
+ await fx.settle();
+ expect(fx.notices("scout-main")).toEqual([]);
+ fx.advance(RETRY_MS[0]);
+ await fx.settle();
+ expect(fx.notices("scout-main")).toEqual(["notice: An das MausBot-Team gesendet (Bericht report-2), nachdem ein früherer Versuch nicht geklappt hat. Milind und Omkar bekommen ihn per E-Mail."]);
+ fx.stop();
+ });
+});
+
describe("a report that cannot go yet", () => {
it("is saved, the person is told, and it goes on its own later", async () => {
const fx = fixture({ outcomes: [{ ok: false, retry: true, why: "offline" }, { ok: false, retry: true, why: "limited", retryAfterMs: 20 * 60_000 }] });
diff --git a/server/host/devs-reports.ts b/server/host/devs-reports.ts
index eefdfb4227..95dc784e57 100644
--- a/server/host/devs-reports.ts
+++ b/server/host/devs-reports.ts
@@ -21,6 +21,7 @@ import type { json as sendJson } from "../harness/http.ts";
import { personKey } from "../person-key.ts";
import type { RecentLog } from "../recent-log.ts";
import { PASS } from "../routes/table.ts";
+import { serverLine, type LineLanguage } from "../server-lines.ts";
import type { PublicSession } from "../sessions.ts";
import type { BotRecord, Message, Store, StoreChange } from "../store.ts";
import { clip } from "./text-clip.ts";
@@ -45,7 +46,9 @@ const waitingSchema = z.object({ messageId: id, threadId: id, at: z.number(), te
sender: z.object({ name: z.string().max(200), id: z.string().max(200).optional() }).optional() });
const payloadSchema = z.object({ installId: z.string(), source: z.literal("bot"), description: z.string(), appVersion: z.string(), platform: z.string(),
diagnostics: z.string(), contactEmail: z.string().optional(), contact: z.string().optional() });
-const queuedSchema = z.object({ messageId: id, threadId: id, payload: payloadSchema, firstAt: z.number(), attempts: z.number().int().min(0), nextAt: z.number() });
+const queuedSchema = z.object({ messageId: id, threadId: id, payload: payloadSchema, firstAt: z.number(), attempts: z.number().int().min(0), nextAt: z.number(),
+ /** Who wrote @devs, so a later try's line reads in their language. */
+ person: z.string().max(200).optional() });
const fileSchema = z.object({ version: z.literal(1), waiting: z.array(waitingSchema).max(MAX_WAITING), outbox: z.array(queuedSchema).max(MAX_OUTBOX) });
const bodySchema = z.object({
went_wrong: z.string().trim().min(1).max(2_000), you_saw: z.string().trim().max(3_000).optional(), steps: z.string().trim().max(2_000).optional(),
@@ -77,6 +80,8 @@ export interface DevsReportsDeps {
team: boolean;
profileEmail(): string | undefined;
language(): string | undefined;
+ /** The language a line for this person is written in; absent, the one set on this server. */
+ lineLanguage?: LineLanguage;
recentLog: RecentLog;
send(payload: DevsReportPayload): Promise<SendOutcome>;
now?: () => number;
@@ -94,19 +99,23 @@ export interface DevsReportContext {
readBody: () => Promise<unknown>;
}
-export const sentLine = (reportId: string, contact?: string) =>
- `Sent to the MausBot team (report ${reportId}). Milind and Omkar get it by email${contact ? ` and will reply to ${contact}` : ""}.`;
-const laterLine = (reportId: string, contact?: string) =>
- `Sent to the MausBot team (report ${reportId}) after an earlier try did not go through. Milind and Omkar get it by email${contact ? ` and will reply to ${contact}` : ""}.`;
-function notYetLine(outcome: Extract<SendOutcome, { retry: true }>): string {
+// What the person is told, in their language (server/server-lines.ts). The bot passes it on word for word.
+export const sentLine = (reportId: string, contact?: string, language?: string) => contact
+ ? serverLine(language, "server.reports.sentReply", { report: reportId, contact }) : serverLine(language, "server.reports.sent", { report: reportId });
+const laterLine = (reportId: string, contact: string | undefined, language: string | undefined) => contact
+ ? serverLine(language, "server.reports.sentLaterReply", { report: reportId, contact }) : serverLine(language, "server.reports.sentLater", { report: reportId });
+function notYetLine(outcome: Extract<SendOutcome, { retry: true }>, language: string | undefined): string {
const minutes = outcome.retryAfterMs ? Math.max(1, Math.ceil(outcome.retryAfterMs / 60_000)) : 0;
- const why = outcome.why === "limited" ? "the MausBot team takes only a few reports an hour from each app"
- : outcome.why === "offline" ? "the MausBot team's server could not be reached" : "the MausBot team's server could not take it right now";
- return `Not sent yet: ${why}. The report is saved and goes on its own${minutes ? ` in about ${minutes} minute${minutes === 1 ? "" : "s"}` : " as soon as it can"}, so there is no need to send it again.`;
+ const why = serverLine(language, outcome.why === "limited" ? "server.reports.why.limited" : outcome.why === "offline" ? "server.reports.why.offline" : "server.reports.why.busy");
+ const when = minutes ? serverLine(language, minutes === 1 ? "server.reports.when.minute" : "server.reports.when.minutes", { count: minutes })
+ : serverLine(language, "server.reports.when.soon");
+ return serverLine(language, "server.reports.notYet", { why, when });
}
-const refusedLine = (detail: string) => `The MausBot team's server refused this bug report, so nothing was sent: ${detail.replace(/[.\s]+$/, "")}.`;
-const fullLine = `Not sent: ${MAX_OUTBOX} bug reports are already waiting to go to the MausBot team. Type @devs again once they have gone.`;
-const droppedLine = "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.";
+const refusedLine = (detail: string, language: string | undefined) => serverLine(language, "server.reports.refused", { detail: detail.replace(/[.\s]+$/, "") });
+const fullLine = (language: string | undefined) => serverLine(language, "server.reports.full", { count: MAX_OUTBOX });
+const droppedLine = (language: string | undefined) => serverLine(language, "server.reports.dropped");
+/** A failure line names MausBot in every language: a bot reply that does has passed it on. */
+const FAILED_MARKER = "MausBot";
/** Rides on the turn that answers a @devs message. */
const TURN_NOTE = "\n\n[From OpenMausBot, not the person: this message tags @devs, so it is a bug report for the MausBot team, OpenMausBot's developers. Call report_bug once, first: what the person says went wrong; what you saw yourself in this conversation (errors, failed tools, stuck steps), or that you saw nothing unusual; and steps to reproduce. Leave out passwords, keys, tokens and file contents; OpenMausBot adds the app's own diagnostics. Then tell the person, word for word, the line report_bug returns, and help with the problem if you can.]";
@@ -177,6 +186,7 @@ export function createDevsReports(deps: DevsReportsDeps) {
};
const botNames = () => store.bots.map((bot) => bot.name);
const secrets = () => environmentSecrets();
+ const languageFor = (person: string | undefined) => (deps.lineLanguage ? deps.lineLanguage(person) : deps.language());
function contactFor(sender: ResolvedSender | undefined): string | undefined {
const person = sender?.id;
@@ -228,16 +238,17 @@ export function createDevsReports(deps: DevsReportsDeps) {
}
/** The words for the person after one attempt; a report worth trying again joins the outbox. */
- function settle(entry: { messageId: string; threadId: string }, payload: DevsReportPayload, outcome: SendOutcome, contact?: string): Told {
+ function settle(entry: Pick<Waiting, "messageId" | "threadId" | "sender">, payload: DevsReportPayload, outcome: SendOutcome, contact?: string): Told {
+ const person = entry.sender?.id, language = languageFor(person);
if (outcome.ok) {
lastSent.set(entry.threadId, { reportId: outcome.id, at: now() });
- return { ok: true, line: sentLine(outcome.id, contact), marker: outcome.id };
+ return { ok: true, line: sentLine(outcome.id, contact, language), marker: outcome.id };
}
- if (!outcome.retry) return { ok: false, line: refusedLine(outcome.detail), marker: "MausBot team" };
- if (outbox.length >= MAX_OUTBOX) return { ok: false, line: fullLine, marker: "MausBot team" };
+ if (!outcome.retry) return { ok: false, line: refusedLine(outcome.detail, language), marker: FAILED_MARKER };
+ if (outbox.length >= MAX_OUTBOX) return { ok: false, line: fullLine(language), marker: FAILED_MARKER };
outbox.push({ messageId: entry.messageId, threadId: entry.threadId, payload, firstAt: now(), attempts: 1,
- nextAt: now() + (outcome.retryAfterMs ?? RETRY_MS[0]) });
- return { ok: false, line: notYetLine(outcome), marker: "MausBot team" };
+ nextAt: now() + (outcome.retryAfterMs ?? RETRY_MS[0]), ...(person ? { person } : {}) });
+ return { ok: false, line: notYetLine(outcome, language), marker: FAILED_MARKER };
}
function deliver(entry: Waiting, author: Author): Promise<Told> {
@@ -269,17 +280,17 @@ export function createDevsReports(deps: DevsReportsDeps) {
async function retry(queued: Queued): Promise<void> {
retrying.add(queued);
const outcome = await deps.send(queued.payload).catch((): SendOutcome => ({ ok: false, retry: true, why: "offline" })).finally(() => retrying.delete(queued));
- const contact = queued.payload.contactEmail ?? queued.payload.contact;
+ const contact = queued.payload.contactEmail ?? queued.payload.contact, language = languageFor(queued.person);
if (outcome.ok) {
outbox = outbox.filter((one) => one !== queued);
lastSent.set(queued.threadId, { reportId: outcome.id, at: now() });
- notice(queued.threadId, { ok: true, line: laterLine(outcome.id, contact), marker: outcome.id });
+ notice(queued.threadId, { ok: true, line: laterLine(outcome.id, contact, language), marker: outcome.id });
} else if (!outcome.retry) {
outbox = outbox.filter((one) => one !== queued);
- notice(queued.threadId, { ok: false, line: refusedLine(outcome.detail), marker: "" });
+ notice(queued.threadId, { ok: false, line: refusedLine(outcome.detail, language), marker: "" });
} else if (now() - queued.firstAt > KEPT_MS) {
outbox = outbox.filter((one) => one !== queued);
- notice(queued.threadId, { ok: false, line: droppedLine, marker: "" });
+ notice(queued.threadId, { ok: false, line: droppedLine(language), marker: "" });
} else {
queued.attempts += 1;
queued.nextAt = now() + (outcome.retryAfterMs ?? RETRY_MS[Math.min(queued.attempts - 1, RETRY_MS.length - 1)]!);
@@ -330,7 +341,7 @@ export function createDevsReports(deps: DevsReportsDeps) {
if (!tagsDevs(line.text, botNames())) return;
seen.add(line.id);
if (seen.size > 1_000) seen.delete(seen.values().next().value!);
- if (waiting.length >= MAX_WAITING) return notice(threadId, { ok: false, line: fullLine, marker: "" });
+ if (waiting.length >= MAX_WAITING) return notice(threadId, { ok: false, line: fullLine(languageFor(line.sender?.id)), marker: "" });
const redact = (text: string) => clip(redactReportText(text, secrets()), 3_000);
waiting.push({ messageId: line.id, threadId, at: line.at, text: redact(line.text), words: redact(withoutDevsTags(line.text, botNames())),
...(line.sender ? { sender: { name: line.sender.name, ...(line.sender.id ? { id: line.sender.id } : {}) } } : {}) });
diff --git a/server/host/person-languages.test.ts b/server/host/person-languages.test.ts
new file mode 100644
index 0000000000..e192b58706
--- /dev/null
+++ b/server/host/person-languages.test.ts
@@ -0,0 +1,69 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createPersonLanguages, PERSON_LANGUAGES_FILE } from "./person-languages.ts";
+
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+function fixture(configured?: string, dataDir = mkdtempSync(join(tmpdir(), "omb-person-languages-"))) {
+ dirs.push(dataDir);
+ let clock = 1_000;
+ const languages = createPersonLanguages({ dataDir, configured: () => configured, now: () => clock });
+ return { languages, dataDir, tick: () => { clock += 1_000; } };
+}
+
+describe("the language a line for a person is written in", () => {
+ it("is the one their app shows, else the place's: the one set here, else the one most people's apps show", () => {
+ const { languages, tick } = fixture();
+ expect(languages.forLine()).toBeUndefined();
+ languages.heard("ada", "de");
+ tick();
+ languages.heard("ben", "en");
+ tick();
+ languages.heard("cy", "de");
+ expect(languages.forLine("ben")).toBe("en");
+ expect(languages.forLine("ada")).toBe("de");
+ expect(languages.forLine("someone-new")).toBe("de");
+ expect(languages.forLine()).toBe("de");
+ const set = fixture("fr");
+ set.languages.heard("ada", "de");
+ expect(set.languages.forLine("ada")).toBe("de");
+ expect(set.languages.forLine()).toBe("fr");
+ });
+
+ it("breaks a tie with the language heard last, and follows a person who changes theirs", () => {
+ const { languages, tick } = fixture();
+ languages.heard("ada", "de");
+ tick();
+ languages.heard("ben", "es");
+ expect(languages.forLine()).toBe("es");
+ tick();
+ languages.heard("ada", "de");
+ expect(languages.forLine()).toBe("de");
+ languages.heard("ada", "pt-BR");
+ expect(languages.forLine("ada")).toBe("pt-br");
+ });
+
+ it("keeps what it heard across a restart, and ignores what is not a language tag", () => {
+ const first = fixture();
+ first.languages.heard("ada", "de");
+ first.languages.heard("ben", "<script>");
+ first.languages.heard("", "fr");
+ const again = fixture(undefined, first.dataDir);
+ expect(again.languages.forLine("ada")).toBe("de");
+ expect(again.languages.forLine("ben")).toBe("de");
+ expect(Object.keys(JSON.parse(readFileSync(join(first.dataDir, PERSON_LANGUAGES_FILE), "utf8")).people)).toEqual(["ada"]);
+ });
+
+ it("starts fresh from a file it cannot read", () => {
+ const dataDir = mkdtempSync(join(tmpdir(), "omb-person-languages-"));
+ writeFileSync(join(dataDir, PERSON_LANGUAGES_FILE), "{ not json");
+ const { languages } = fixture("it", dataDir);
+ expect(languages.forLine("ada")).toBe("it");
+ languages.heard("ada", "de");
+ expect(languages.forLine("ada")).toBe("de");
+ });
+});
diff --git a/server/host/person-languages.ts b/server/host/person-languages.ts
new file mode 100644
index 0000000000..fe19b20672
--- /dev/null
+++ b/server/host/person-languages.ts
@@ -0,0 +1,81 @@
+// The language each person's app shows, from its presence pings (src/hooks/use-presence.ts), so the lines the server
+// writes for a person read in it (server/server-lines.ts). The app keeps a person's language pick on their own computer,
+// so this is the only way the server learns it. Kept on disk: a routine's line at night, with no app open, still knows.
+// A line for nobody in particular reads in the place's language: the one set on this server or by the team's Admin,
+// else the one most people's apps here show.
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { z } from "zod";
+
+import { writeFileAtomic } from "../atomic.ts";
+import type { LineLanguage } from "../server-lines.ts";
+
+export const PERSON_LANGUAGES_FILE = "person-languages.json";
+/** Pings from this computer's own app carry no session; they are kept under this key. */
+export const THIS_COMPUTER = "this-computer";
+const MAX_PEOPLE = 500;
+const TAG = /^[a-z]{2,3}(?:-[a-z0-9]{2,8}){0,3}$/;
+const fileSchema = z.object({
+ version: z.literal(1),
+ people: z.record(z.string().min(1).max(200), z.object({ language: z.string().regex(TAG), at: z.number() })),
+});
+
+export interface PersonLanguagesDeps {
+ dataDir: string;
+ /** The language set on this server, else the team's default from the Admin. */
+ configured(): string | undefined;
+ now?: () => number;
+}
+
+export function createPersonLanguages(deps: PersonLanguagesDeps) {
+ const file = join(deps.dataDir, PERSON_LANGUAGES_FILE);
+ const now = deps.now ?? Date.now;
+ const people = new Map<string, { language: string; at: number }>();
+ try {
+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));
+ if (parsed.success) for (const [person, heard] of Object.entries(parsed.data.people)) people.set(person, heard);
+ else console.warn(`person languages: ${file} is not a languages file; starting fresh`);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`person languages: ${file} is unreadable; starting fresh`);
+ }
+
+ const save = () => {
+ try {
+ writeFileAtomic(file, `${JSON.stringify({ version: 1, people: Object.fromEntries(people) })}\n`, { mode: 0o600 });
+ } catch (error) {
+ console.warn(`person languages: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ };
+
+ /** The language most people's apps here show; on a tie, the one heard most lately. */
+ const usual = (): string | undefined => {
+ const counts = new Map<string, { people: number; at: number }>();
+ for (const { language, at } of people.values()) {
+ const count = counts.get(language);
+ counts.set(language, { people: (count?.people ?? 0) + 1, at: Math.max(count?.at ?? 0, at) });
+ }
+ return [...counts].sort(([, a], [, b]) => b.people - a.people || b.at - a.at)[0]?.[0];
+ };
+
+ const forLine: LineLanguage = (person) => (person ? people.get(person)?.language : undefined) ?? deps.configured() ?? usual();
+
+ return {
+ /** A presence ping from this person's app: the language it shows. Written down only when it changes. */
+ heard(person: string, language: string): void {
+ const tag = language.trim().toLowerCase();
+ if (!person || !TAG.test(tag)) return;
+ const known = people.get(person);
+ if (known?.language === tag) {
+ known.at = now();
+ return;
+ }
+ people.delete(person);
+ people.set(person, { language: tag, at: now() });
+ if (people.size > MAX_PEOPLE) people.delete(people.keys().next().value!);
+ save();
+ },
+ forLine,
+ };
+}
+
+export type PersonLanguages = ReturnType<typeof createPersonLanguages>;
diff --git a/server/index.ts b/server/index.ts
index 96bbdd6636..c830edea76 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -44,7 +44,7 @@ import { escapeAttribute } from "../src/lib/composer-attachments.ts";
import { isPendingSignInRequest, normalizeSignInSite, signInFallbackText, signInOutcome, signInResumePrompt } from "../shared/sign-in-request.ts";
import { createRoomTurnLevels } from "./room-turn-level.ts";
-import { createSignInSettle } from "./host/sign-in-settle.ts";
+import { createSignInSettle } from "./host/sign-in-settle.ts"; import { createPersonLanguages, THIS_COMPUTER } from "./host/person-languages.ts"; import "./server-line-packs.ts";
import { RoomMemberLock } from "./room-member-lock.ts";
import { approvalHeldNote, approvalHeldReason, approvalModeForOrigin, autoVerdict, deliverFullAccessApproval, undeliveredApprovalTool } from "./auto-approve.ts"; import { readsOwnFiles } from "./own-file-reads.ts";
import { bindSafetyFloor, denyAtSafetyFloor, heldAtSafetyFloor, safetyFloorOn } from "./safety-floor-gate.ts";
@@ -685,7 +685,7 @@ const CLOUD_ENV: NodeJS.ProcessEnv = { ...process.env, ...CLOUD_SECRETS };
const CLOUD_HOME = cloudHomeConfiguration(CLOUD_ENV);
const CLOUD_TEAM = CLOUD_HOME?.team ?? null, CLOUD_PERSONAL = CLOUD_HOME !== null && CLOUD_TEAM === null, TEAM_LABEL = CLOUD_TEAM ? { label: CLOUD_TEAM.name } : {};
/** The language set on this server, else (on a Team Cloud) the team's default from the Admin. */
-const appLanguage = (): string | undefined => cfg.language ?? CLOUD_TEAM?.language;
+const appLanguage = (): string | undefined => cfg.language ?? CLOUD_TEAM?.language; const personLanguages = createPersonLanguages({ dataDir: DATA_DIR, configured: appLanguage });
if (CLOUD_HOME) repairMovedWorkspacePaths(DATA_DIR);
if (CLOUD_PERSONAL) sessions.requireAdmin(CLOUD_PERSONAL_REFUSAL);
const lendingEnabled = () => sharedComputersEnabled(cfg) || CLOUD_HOME !== null;
@@ -2873,7 +2873,7 @@ const { stopThreadForPerson, stopOnTypedCommand, noteTeammatesLeftRunning } = cr
store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,
stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),
}); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });
-const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage });
+const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
@@ -12367,7 +12367,7 @@ ROUTES.push(createBotMemoryRoutes({
}));
const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin") ? { person: actorKey(auth), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
-ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: teamMessages.arrived } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),
+ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: teamMessages.arrived } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));
ROUTES.push(createRoomHoldRoutes({
group: (id) => store.group(id),
diff --git a/server/routes/presence.test.ts b/server/routes/presence.test.ts
index cb018a0c0e..9a438931b1 100644
--- a/server/routes/presence.test.ts
+++ b/server/routes/presence.test.ts
@@ -3,14 +3,15 @@ import { describe, expect, it, vi } from "vitest";
import type { RequestAuth } from "../request-auth.ts";
import { createPresenceRoutes } from "./presence.ts";
-function call(auth: RequestAuth, body: unknown, active = vi.fn(async () => ({ returned: true }))) {
+function call(auth: RequestAuth, body: unknown, active = vi.fn(async () => ({ returned: true })), team = false) {
const answers: Array<[number, unknown]> = [];
- const route = createPresenceRoutes({ isOwner: (who) => who.scopes.includes("admin"), active });
+ const heard = vi.fn((_auth: RequestAuth, _language: string) => {});
+ const route = createPresenceRoutes({ isOwner: (who) => who.scopes.includes("admin"), active, heard, ...(team ? { member: () => ({ returned: false }) } : {}) });
const done = route({
req: {} as never, res: {} as never, url: new URL("http://x/api/presence/active"), path: "/api/presence/active", method: "POST", auth,
json: ((_res: unknown, status: number, value: unknown) => { answers.push([status, value]); }) as never, readBody: (async () => body) as never,
});
- return { done, answers, active };
+ return { done, answers, active, heard };
}
describe("POST /api/presence/active", () => {
@@ -25,9 +26,22 @@ describe("POST /api/presence/active", () => {
});
it("answers a guest without recording anything", async () => {
- const guest = call({ kind: "loopback", scopes: ["client"], trust: "service" }, { source: "desktop" });
+ const guest = call({ kind: "loopback", scopes: ["client"], trust: "service" }, { source: "desktop", language: "fr" });
await guest.done;
expect(guest.active).not.toHaveBeenCalled();
+ expect(guest.heard).not.toHaveBeenCalled();
expect(guest.answers).toEqual([[200, { ok: true, returned: false }]]);
});
+
+ it("hears the language the owner's app shows, and on a Team Cloud each member's, for the lines written for them", async () => {
+ const owner = call({ kind: "loopback", scopes: ["admin", "client"] }, { language: "de-DE" });
+ await owner.done;
+ expect(owner.heard).toHaveBeenCalledWith(expect.objectContaining({ kind: "loopback" }), "de-de");
+ const member = call({ kind: "loopback", scopes: ["client"] }, { language: "es" }, undefined, true);
+ await member.done;
+ expect(member.heard).toHaveBeenCalledWith(expect.anything(), "es");
+ const none = call({ kind: "loopback", scopes: ["admin", "client"] }, { language: "not a tag" });
+ await none.done;
+ expect(none.heard).not.toHaveBeenCalled();
+ });
});
diff --git a/server/routes/presence.ts b/server/routes/presence.ts
index 546fe67cb8..323c303cf6 100644
--- a/server/routes/presence.ts
+++ b/server/routes/presence.ts
@@ -8,6 +8,9 @@ export interface PresenceRouteDeps {
active(source: "desktop" | "phone", timeZone?: string, language?: string): Promise<PresenceAnswer>;
/** A Team Cloud: every member's arrival counts, for their own brief, in the language their app shows. */
member?(auth: RequestAuth, language?: string): PresenceAnswer;
+ /** The language the app of a ping that counts shows (the owner's, or a member's), for the lines the server writes for
+ * that person (host/person-languages.ts). */
+ heard?(auth: RequestAuth, language: string): void;
}
const IANA_ZONE = /^(?:UTC|[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)+)$/;
@@ -22,6 +25,7 @@ export function createPresenceRoutes(deps: PresenceRouteDeps): RouteHandler {
const source = given.source === "phone" ? "phone" : "desktop";
const timeZone = typeof given.timeZone === "string" && given.timeZone.length <= 128 && IANA_ZONE.test(given.timeZone) ? validZone(given.timeZone) : undefined;
const language = typeof given.language === "string" && LANGUAGE_TAG.test(given.language) ? given.language.toLowerCase() : undefined;
+ if (language && (deps.member || deps.isOwner(auth))) deps.heard?.(auth, language);
if (deps.member) return json(res, 200, { ok: true, ...deps.member(auth, language) });
// A guest's activation is not the person's: answered, never recorded.
if (!deps.isOwner(auth)) return json(res, 200, { ok: true, returned: false });
diff --git a/server/server-line-packs.ts b/server/server-line-packs.ts
new file mode 100644
index 0000000000..4afb67b6e3
--- /dev/null
+++ b/server/server-line-packs.ts
@@ -0,0 +1,21 @@
+// Every other language's server lines, from the app's packs (server-lines.ts reads English). The server loads this when
+// it starts (server/index.ts), and so does a test that checks a line in another language; before that, a line reads in
+// English. Only tests that load this read a translation, so only they run with the locale tests (scripts/ci-scope.mjs).
+import de from "../src/locales/de.json" with { type: "json" };
+import es from "../src/locales/es.json" with { type: "json" };
+import fr from "../src/locales/fr.json" with { type: "json" };
+import hi from "../src/locales/hi.json" with { type: "json" };
+import it from "../src/locales/it.json" with { type: "json" };
+import ja from "../src/locales/ja.json" with { type: "json" };
+import ko from "../src/locales/ko.json" with { type: "json" };
+import pl from "../src/locales/pl.json" with { type: "json" };
+import ptBr from "../src/locales/pt-br.json" with { type: "json" };
+import ru from "../src/locales/ru.json" with { type: "json" };
+import tr from "../src/locales/tr.json" with { type: "json" };
+import uk from "../src/locales/uk.json" with { type: "json" };
+import vi from "../src/locales/vi.json" with { type: "json" };
+import zhTw from "../src/locales/zh-tw.json" with { type: "json" };
+import zh from "../src/locales/zh.json" with { type: "json" };
+import { addServerLinePacks } from "./server-lines.ts";
+
+addServerLinePacks({ de, es, fr, hi, it, ja, ko, pl, "pt-br": ptBr, ru, tr, uk, vi, zh, "zh-tw": zhTw });
diff --git a/server/server-lines.test.ts b/server/server-lines.test.ts
new file mode 100644
index 0000000000..fe9c4a141b
--- /dev/null
+++ b/server/server-lines.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+
+import "./server-line-packs.ts";
+import { serverLine } from "./server-lines.ts";
+
+describe("serverLine", () => {
+ it("writes the line in the language given, with its values filled in", () => {
+ expect(serverLine("de", "server.reports.sent", { report: "r-1" })).toBe("An das MausBot-Team gesendet (Bericht r-1). Milind und Omkar bekommen ihn per E-Mail.");
+ expect(serverLine(undefined, "server.reports.sent", { report: "r-1" })).toBe("Sent to the MausBot team (report r-1). Milind and Omkar get it by email.");
+ expect(serverLine("en", "server.reports.when.minutes", { count: 5 })).toBe("in about 5 minutes");
+ });
+
+ it("reads a regional tag as its language, and a language it has no words for as English", () => {
+ expect(serverLine("de-AT", "server.reports.when.soon")).toBe("so bald wie möglich");
+ expect(serverLine("pt", "server.reports.when.soon")).toBe(serverLine("pt-br", "server.reports.when.soon"));
+ expect(serverLine("zh-Hant", "server.reports.when.soon")).toBe(serverLine("zh-tw", "server.reports.when.soon"));
+ expect(serverLine("nl", "server.reports.when.soon")).toBe("as soon as it can");
+ });
+
+ it("leaves a {name} it was given no value for as it is", () => {
+ expect(serverLine("en", "server.reports.refused", {})).toBe("The MausBot team's server refused this bug report, so nothing was sent: {detail}.");
+ });
+});
diff --git a/server/server-lines.ts b/server/server-lines.ts
new file mode 100644
index 0000000000..f1b1e1eb4e
--- /dev/null
+++ b/server/server-lines.ts
@@ -0,0 +1,29 @@
+// The lines the server writes for a person to read (a bot's line, a status row, a card, a notification) come from the
+// app's language packs, under "server.", in the language of the person they are for (host/person-languages.ts). This
+// module reads English; server-line-packs.ts adds every other language when the server starts. The packaged server
+// bundles only the "server." keys (scripts/server-locale-plugin.mjs). Text only a model reads stays English and never
+// comes from here. A guard beside the packs (server-lines.test.ts) fails on an English line written straight into one.
+import en from "../src/locales/en.json" with { type: "json" };
+import { byLanguage } from "./language.ts";
+
+export type ServerLineKey = Extract<keyof typeof en, `server.${string}`>;
+type Pack = Partial<Record<string, string>>;
+
+const ENGLISH: Pack = en;
+const packs: { en: Pack } & Record<string, Pack> = { en: ENGLISH };
+
+/** The other languages' packs, by code ("de", "pt-br", "zh-tw"); server-line-packs.ts adds them once, at start. */
+export function addServerLinePacks(more: Readonly<Record<string, Pack>>): void {
+ Object.assign(packs, more, { en: ENGLISH });
+}
+
+/** The line in `language` (a language tag; undefined reads as English), with each `{name}` filled from `params`. A key
+ * the language has no words for yet reads in English, as the app's own screens do. */
+export function serverLine(language: string | undefined, key: ServerLineKey, params?: Readonly<Record<string, string | number>>): string {
+ const template = byLanguage(packs, language)[key] ?? ENGLISH[key] ?? key;
+ return params ? template.replace(/\{(\w+)\}/g, (match, name: string) => (Object.hasOwn(params, name) ? String(params[name]) : match)) : template;
+}
+
+/** The language a line for this person is written in: their app's, else the place's (host/person-languages.ts).
+ * Undefined reads as English. */
+export type LineLanguage = (person?: string) => string | undefined;
diff --git a/src/locales/de.json b/src/locales/de.json
index b4069921cc..f3e2febd72 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -37,6 +37,20 @@
"notice.dismiss": "Dauerhaft ausblenden",
"notice.notNow": "Jetzt nicht",
"notice.openFailed": "Dein Browser konnte nicht geöffnet werden. Bitte versuche es erneut.",
+ "server.reports.sent": "An das MausBot-Team gesendet (Bericht {report}). Milind und Omkar bekommen ihn per E-Mail.",
+ "server.reports.sentReply": "An das MausBot-Team gesendet (Bericht {report}). Milind und Omkar bekommen ihn per E-Mail und antworten dir an {contact}.",
+ "server.reports.sentLater": "An das MausBot-Team gesendet (Bericht {report}), nachdem ein früherer Versuch nicht geklappt hat. Milind und Omkar bekommen ihn per E-Mail.",
+ "server.reports.sentLaterReply": "An das MausBot-Team gesendet (Bericht {report}), nachdem ein früherer Versuch nicht geklappt hat. Milind und Omkar bekommen ihn per E-Mail und antworten dir an {contact}.",
+ "server.reports.notYet": "Noch nicht gesendet: {why}. Der Bericht ist gespeichert und wird {when} von selbst gesendet, du musst ihn also nicht noch einmal senden.",
+ "server.reports.why.limited": "das MausBot-Team nimmt von jeder App nur wenige Berichte pro Stunde an",
+ "server.reports.why.offline": "der Server des MausBot-Teams war nicht erreichbar",
+ "server.reports.why.busy": "der Server des MausBot-Teams konnte ihn gerade nicht annehmen",
+ "server.reports.when.minute": "in etwa {count} Minute",
+ "server.reports.when.minutes": "in etwa {count} Minuten",
+ "server.reports.when.soon": "so bald wie möglich",
+ "server.reports.refused": "Der Server des MausBot-Teams hat diesen Fehlerbericht abgelehnt, daher wurde nichts gesendet: {detail}.",
+ "server.reports.full": "Nicht gesendet: {count} Fehlerberichte warten schon darauf, an das MausBot-Team zu gehen. Schreib noch einmal @devs, sobald sie gesendet sind.",
+ "server.reports.dropped": "Ein Fehlerbericht aus dieser Unterhaltung konnte das MausBot-Team eine Woche lang nicht erreichen und wurde deshalb verworfen. Schreib noch einmal @devs, um einen neuen zu senden.",
"star.title": "Gefällt dir {app}?",
"star.body": "Ein Stern auf GitHub hilft mehr Menschen, es zu finden.",
"star.button": "Stern auf GitHub geben",
diff --git a/src/locales/en.json b/src/locales/en.json
index 8957dbd1ae..2e35c03038 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -134,6 +134,20 @@
"notice.dismiss": "Dismiss for good",
"notice.notNow": "Not now",
"notice.openFailed": "Could not open your browser. Please try again.",
+ "server.reports.sent": "Sent to the MausBot team (report {report}). Milind and Omkar get it by email.",
+ "server.reports.sentReply": "Sent to the MausBot team (report {report}). Milind and Omkar get it by email and will reply to {contact}.",
+ "server.reports.sentLater": "Sent to the MausBot team (report {report}) after an earlier try did not go through. Milind and Omkar get it by email.",
+ "server.reports.sentLaterReply": "Sent to the MausBot team (report {report}) after an earlier try did not go through. Milind and Omkar get it by email and will reply to {contact}.",
+ "server.reports.notYet": "Not sent yet: {why}. The report is saved and goes on its own {when}, so there is no need to send it again.",
+ "server.reports.why.limited": "the MausBot team takes only a few reports an hour from each app",
+ "server.reports.why.offline": "the MausBot team's server could not be reached",
+ "server.reports.why.busy": "the MausBot team's server could not take it right now",
+ "server.reports.when.minute": "in about {count} minute",
+ "server.reports.when.minutes": "in about {count} minutes",
+ "server.reports.when.soon": "as soon as it can",
+ "server.reports.refused": "The MausBot team's server refused this bug report, so nothing was sent: {detail}.",
+ "server.reports.full": "Not sent: {count} bug reports are already waiting to go to the MausBot team. Type @devs again once they have gone.",
+ "server.reports.dropped": "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.",
"star.title": "Enjoying {app}?",
"star.body": "A star on GitHub helps more people find it.",
"star.button": "Star on GitHub",
diff --git a/src/locales/es.json b/src/locales/es.json
index 537d06594c..a0bc64ce9b 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -84,6 +84,20 @@
"notice.dismiss": "Descartar para siempre",
"notice.notNow": "Ahora no",
"notice.openFailed": "No se pudo abrir tu navegador. Inténtalo de nuevo.",
+ "server.reports.sent": "Enviado al equipo de MausBot (informe {report}). Milind y Omkar lo reciben por correo electrónico.",
+ "server.reports.sentReply": "Enviado al equipo de MausBot (informe {report}). Milind y Omkar lo reciben por correo electrónico y responderán a {contact}.",
+ "server.reports.sentLater": "Enviado al equipo de MausBot (informe {report}) después de que un intento anterior no saliera. Milind y Omkar lo reciben por correo electrónico.",
+ "server.reports.sentLaterReply": "Enviado al equipo de MausBot (informe {report}) después de que un intento anterior no saliera. Milind y Omkar lo reciben por correo electrónico y responderán a {contact}.",
+ "server.reports.notYet": "Aún no se ha enviado: {why}. El informe está guardado y se enviará solo {when}, así que no hace falta enviarlo de nuevo.",
+ "server.reports.why.limited": "el equipo de MausBot solo acepta unos pocos informes por hora de cada app",
+ "server.reports.why.offline": "no se pudo conectar con el servidor del equipo de MausBot",
+ "server.reports.why.busy": "el servidor del equipo de MausBot no pudo recibirlo ahora mismo",
+ "server.reports.when.minute": "en aproximadamente {count} minuto",
+ "server.reports.when.minutes": "en aproximadamente {count} minutos",
+ "server.reports.when.soon": "en cuanto pueda",
+ "server.reports.refused": "El servidor del equipo de MausBot rechazó este informe de error, así que no se envió nada: {detail}.",
+ "server.reports.full": "No enviado: ya hay {count} informes de error esperando para ir al equipo de MausBot. Vuelve a escribir @devs cuando se hayan enviado.",
+ "server.reports.dropped": "Un informe de error de esta conversación no pudo llegar al equipo de MausBot durante una semana, así que se descartó. Vuelve a escribir @devs para enviar uno nuevo.",
"star.title": "¿Te gusta {app}?",
"star.body": "Una estrella en GitHub ayuda a que más personas lo encuentren.",
"star.button": "Dar una estrella en GitHub",
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 6ba0989275..650a7340ca 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -37,6 +37,20 @@
"notice.dismiss": "Masquer définitivement",
"notice.notNow": "Pas maintenant",
"notice.openFailed": "Impossible d'ouvrir votre navigateur. Veuillez réessayer.",
+ "server.reports.sent": "Envoyé à l'équipe MausBot (rapport {report}). Milind et Omkar le reçoivent par e-mail.",
+ "server.reports.sentReply": "Envoyé à l'équipe MausBot (rapport {report}). Milind et Omkar le reçoivent par e-mail et répondront à {contact}.",
+ "server.reports.sentLater": "Envoyé à l'équipe MausBot (rapport {report}) après l'échec d'une tentative précédente. Milind et Omkar le reçoivent par e-mail.",
+ "server.reports.sentLaterReply": "Envoyé à l'équipe MausBot (rapport {report}) après l'échec d'une tentative précédente. Milind et Omkar le reçoivent par e-mail et répondront à {contact}.",
+ "server.reports.notYet": "Pas encore envoyé : {why}. Le rapport est enregistré et partira tout seul {when}, inutile donc de l'envoyer à nouveau.",
+ "server.reports.why.limited": "l'équipe MausBot n'accepte que quelques rapports par heure de chaque application",
+ "server.reports.why.offline": "le serveur de l'équipe MausBot était injoignable",
+ "server.reports.why.busy": "le serveur de l'équipe MausBot n'a pas pu le prendre pour le moment",
+ "server.reports.when.minute": "dans environ {count} minute",
+ "server.reports.when.minutes": "dans environ {count} minutes",
+ "server.reports.when.soon": "dès que possible",
+ "server.reports.refused": "Le serveur de l'équipe MausBot a refusé ce rapport de bug, rien n'a donc été envoyé : {detail}.",
+ "server.reports.full": "Non envoyé : {count} rapports de bug attendent déjà d'être envoyés à l'équipe MausBot. Écrivez de nouveau @devs une fois qu'ils sont partis.",
+ "server.reports.dropped": "Un rapport de bug de cette conversation n'a pas pu atteindre l'équipe MausBot pendant une semaine, il a donc été abandonné. Écrivez de nouveau @devs pour en envoyer un nouveau.",
"star.title": "Vous aimez {app} ?",
"star.body": "Une étoile sur GitHub aide plus de gens à le découvrir.",
"star.button": "Mettre une étoile sur GitHub",
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 03a93e0e80..c8e8bbbe05 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -37,6 +37,20 @@
"notice.dismiss": "हमेशा के लिए हटाएँ",
"notice.notNow": "अभी नहीं",
"notice.openFailed": "आपका ब्राउज़र नहीं खुल सका। कृपया फिर से कोशिश करें।",
+ "server.reports.sent": "MausBot टीम को भेज दिया गया (रिपोर्ट {report})। Milind और Omkar को यह ईमेल से मिलेगी।",
+ "server.reports.sentReply": "MausBot टीम को भेज दिया गया (रिपोर्ट {report})। Milind और Omkar को यह ईमेल से मिलेगी और वे {contact} पर जवाब देंगे।",
+ "server.reports.sentLater": "पिछली कोशिश सफल न होने के बाद MausBot टीम को भेज दिया गया (रिपोर्ट {report})। Milind और Omkar को यह ईमेल से मिलेगी।",
+ "server.reports.sentLaterReply": "पिछली कोशिश सफल न होने के बाद MausBot टीम को भेज दिया गया (रिपोर्ट {report})। Milind और Omkar को यह ईमेल से मिलेगी और वे {contact} पर जवाब देंगे।",
+ "server.reports.notYet": "अभी नहीं भेजी गई: {why}। रिपोर्ट सहेज ली गई है और {when} अपने-आप चली जाएगी, इसलिए इसे दोबारा भेजने की ज़रूरत नहीं है।",
+ "server.reports.why.limited": "MausBot टीम हर ऐप से एक घंटे में कुछ ही रिपोर्ट लेती है",
+ "server.reports.why.offline": "MausBot टीम के सर्वर तक नहीं पहुँचा जा सका",
+ "server.reports.why.busy": "MausBot टीम का सर्वर अभी इसे नहीं ले सका",
+ "server.reports.when.minute": "लगभग {count} मिनट में",
+ "server.reports.when.minutes": "लगभग {count} मिनट में",
+ "server.reports.when.soon": "जितनी जल्दी हो सके",
+ "server.reports.refused": "MausBot टीम के सर्वर ने यह बग रिपोर्ट अस्वीकार कर दी, इसलिए कुछ नहीं भेजा गया: {detail}।",
+ "server.reports.full": "नहीं भेजी गई: {count} बग रिपोर्ट पहले से MausBot टीम को भेजे जाने का इंतज़ार कर रही हैं। उनके चले जाने के बाद फिर से @devs लिखें।",
+ "server.reports.dropped": "इस बातचीत की एक बग रिपोर्ट एक हफ़्ते तक MausBot टीम तक नहीं पहुँच सकी, इसलिए उसे हटा दिया गया। नई रिपोर्ट भेजने के लिए फिर से @devs लिखें।",
"star.title": "{app} पसंद आ रहा है?",
"star.body": "GitHub पर एक स्टार से ज़्यादा लोग इसे ढूँढ पाते हैं।",
"star.button": "GitHub पर स्टार दें",
diff --git a/src/locales/it.json b/src/locales/it.json
index 2b6a4edddd..3d97065bcf 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -89,6 +89,20 @@
"notice.dismiss": "Non mostrare più",
"notice.notNow": "Non ora",
"notice.openFailed": "Non riesco ad aprire il browser. Riprova.",
+ "server.reports.sent": "Inviata al team di MausBot (segnalazione {report}). Milind e Omkar la ricevono via email.",
+ "server.reports.sentReply": "Inviata al team di MausBot (segnalazione {report}). Milind e Omkar la ricevono via email e risponderanno a {contact}.",
+ "server.reports.sentLater": "Inviata al team di MausBot (segnalazione {report}) dopo che un tentativo precedente non era andato a buon fine. Milind e Omkar la ricevono via email.",
+ "server.reports.sentLaterReply": "Inviata al team di MausBot (segnalazione {report}) dopo che un tentativo precedente non era andato a buon fine. Milind e Omkar la ricevono via email e risponderanno a {contact}.",
+ "server.reports.notYet": "Non ancora inviata: {why}. La segnalazione è salvata e partirà da sola {when}, quindi non serve inviarla di nuovo.",
+ "server.reports.why.limited": "il team di MausBot accetta solo poche segnalazioni all'ora da ogni app",
+ "server.reports.why.offline": "non è stato possibile raggiungere il server del team di MausBot",
+ "server.reports.why.busy": "il server del team di MausBot non ha potuto riceverla in questo momento",
+ "server.reports.when.minute": "tra circa {count} minuto",
+ "server.reports.when.minutes": "tra circa {count} minuti",
+ "server.reports.when.soon": "appena possibile",
+ "server.reports.refused": "Il server del team di MausBot ha rifiutato questa segnalazione di bug, quindi non è stato inviato nulla: {detail}.",
+ "server.reports.full": "Non inviata: ci sono già {count} segnalazioni di bug in attesa di essere inviate al team di MausBot. Scrivi di nuovo @devs quando saranno partite.",
+ "server.reports.dropped": "Una segnalazione di bug di questa conversazione non è riuscita a raggiungere il team di MausBot per una settimana, quindi è stata scartata. Scrivi di nuovo @devs per inviarne una nuova.",
"star.title": "Ti piace {app}?",
"star.body": "Una stella su GitHub aiuta più persone a trovarlo.",
"star.button": "Stella su GitHub",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index 36751c1852..0ae6793ec6 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -91,6 +91,20 @@
"notice.dismiss": "今後表示しない",
"notice.notNow": "今はしない",
"notice.openFailed": "ブラウザーを開けませんでした。もう一度お試しください。",
+ "server.reports.sent": "MausBot チームに送信しました(レポート {report})。Milind と Omkar がメールで受け取ります。",
+ "server.reports.sentReply": "MausBot チームに送信しました(レポート {report})。Milind と Omkar がメールで受け取り、{contact} に返信します。",
+ "server.reports.sentLater": "前回の送信がうまくいかなかったため、改めて MausBot チームに送信しました(レポート {report})。Milind と Omkar がメールで受け取ります。",
+ "server.reports.sentLaterReply": "前回の送信がうまくいかなかったため、改めて MausBot チームに送信しました(レポート {report})。Milind と Omkar がメールで受け取り、{contact} に返信します。",
+ "server.reports.notYet": "まだ送信していません:{why}。レポートは保存されていて、{when}自動で送信されるので、もう一度送る必要はありません。",
+ "server.reports.why.limited": "MausBot チームが各アプリから受け付けるレポートは 1 時間に数件までです",
+ "server.reports.why.offline": "MausBot チームのサーバーに接続できませんでした",
+ "server.reports.why.busy": "MausBot チームのサーバーが今は受け付けられませんでした",
+ "server.reports.when.minute": "約 {count} 分後に",
+ "server.reports.when.minutes": "約 {count} 分後に",
+ "server.reports.when.soon": "送れるようになり次第",
+ "server.reports.refused": "MausBot チームのサーバーがこのバグレポートを拒否したため、何も送信されていません:{detail}。",
+ "server.reports.full": "送信していません:MausBot チームへの送信を待っているバグレポートがすでに {count} 件あります。それらが送信されてから、もう一度 @devs と入力してください。",
+ "server.reports.dropped": "この会話のバグレポートは 1 週間 MausBot チームに届かなかったため、破棄されました。新しく送るには、もう一度 @devs と入力してください。",
"star.title": "{app} を気に入っていただけましたか?",
"star.body": "GitHub でスターを付けていただくと、より多くの人に見つけてもらえます。",
"star.button": "GitHub でスターを付ける",
diff --git a/src/locales/ko.json b/src/locales/ko.json
index 993d30ec28..e787edb5d5 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -134,6 +134,20 @@
"notice.dismiss": "다시 보지 않기",
"notice.notNow": "나중에",
"notice.openFailed": "브라우저를 열지 못했어요. 다시 시도하세요.",
+ "server.reports.sent": "MausBot 팀에 보냈어요(리포트 {report}). Milind 님과 Omkar 님이 이메일로 받아요.",
+ "server.reports.sentReply": "MausBot 팀에 보냈어요(리포트 {report}). Milind 님과 Omkar 님이 이메일로 받고 {contact}(으)로 답장할 거예요.",
+ "server.reports.sentLater": "이전 시도가 실패해서 다시 MausBot 팀에 보냈어요(리포트 {report}). Milind 님과 Omkar 님이 이메일로 받아요.",
+ "server.reports.sentLaterReply": "이전 시도가 실패해서 다시 MausBot 팀에 보냈어요(리포트 {report}). Milind 님과 Omkar 님이 이메일로 받고 {contact}(으)로 답장할 거예요.",
+ "server.reports.notYet": "아직 보내지 못했어요: {why}. 리포트는 저장되어 있고 {when} 자동으로 전송되니 다시 보낼 필요는 없어요.",
+ "server.reports.why.limited": "MausBot 팀은 앱마다 한 시간에 몇 건의 리포트만 받아요",
+ "server.reports.why.offline": "MausBot 팀 서버에 연결할 수 없었어요",
+ "server.reports.why.busy": "MausBot 팀 서버가 지금은 받을 수 없었어요",
+ "server.reports.when.minute": "약 {count}분 후에",
+ "server.reports.when.minutes": "약 {count}분 후에",
+ "server.reports.when.soon": "가능해지는 대로",
+ "server.reports.refused": "MausBot 팀 서버가 이 버그 리포트를 거절해서 아무것도 보내지 않았어요: {detail}.",
+ "server.reports.full": "보내지 않았어요: MausBot 팀으로 보내길 기다리는 버그 리포트가 이미 {count}건 있어요. 전송이 끝난 뒤 다시 @devs를 입력하세요.",
+ "server.reports.dropped": "이 대화의 버그 리포트가 일주일 동안 MausBot 팀에 전달되지 못해 삭제됐어요. 새로 보내려면 다시 @devs를 입력하세요.",
"star.title": "{app}이 마음에 드세요?",
"star.body": "GitHub에 별을 눌러 주시면 더 많은 사람이 찾을 수 있어요.",
"star.button": "GitHub에서 별 주기",
diff --git a/src/locales/pl.json b/src/locales/pl.json
index c53c63993f..f1b36374ad 100644
--- a/src/locales/pl.json
+++ b/src/locales/pl.json
@@ -91,6 +91,20 @@
"notice.dismiss": "Odrzuć na zawsze",
"notice.notNow": "Nie teraz",
"notice.openFailed": "Nie udało się otworzyć przeglądarki. Spróbuj ponownie.",
+ "server.reports.sent": "Wysłano do zespołu MausBot (zgłoszenie {report}). Milind i Omkar dostaną je e-mailem.",
+ "server.reports.sentReply": "Wysłano do zespołu MausBot (zgłoszenie {report}). Milind i Omkar dostaną je e-mailem i odpowiedzą na adres {contact}.",
+ "server.reports.sentLater": "Wysłano do zespołu MausBot (zgłoszenie {report}) po nieudanej wcześniejszej próbie. Milind i Omkar dostaną je e-mailem.",
+ "server.reports.sentLaterReply": "Wysłano do zespołu MausBot (zgłoszenie {report}) po nieudanej wcześniejszej próbie. Milind i Omkar dostaną je e-mailem i odpowiedzą na adres {contact}.",
+ "server.reports.notYet": "Jeszcze nie wysłano: {why}. Zgłoszenie jest zapisane i wyśle się samo {when}, więc nie trzeba wysyłać go ponownie.",
+ "server.reports.why.limited": "zespół MausBot przyjmuje tylko kilka zgłoszeń na godzinę z każdej aplikacji",
+ "server.reports.why.offline": "nie udało się połączyć z serwerem zespołu MausBot",
+ "server.reports.why.busy": "serwer zespołu MausBot nie mógł go teraz przyjąć",
+ "server.reports.when.minute": "za około {count} minutę",
+ "server.reports.when.minutes": "za około {count} min",
+ "server.reports.when.soon": "gdy tylko będzie to możliwe",
+ "server.reports.refused": "Serwer zespołu MausBot odrzucił to zgłoszenie błędu, więc nic nie zostało wysłane: {detail}.",
+ "server.reports.full": "Nie wysłano: {count} zgłoszeń błędów czeka już na wysłanie do zespołu MausBot. Wpisz ponownie @devs, gdy zostaną wysłane.",
+ "server.reports.dropped": "Zgłoszenie błędu z tej rozmowy przez tydzień nie mogło dotrzeć do zespołu MausBot, więc zostało odrzucone. Wpisz ponownie @devs, aby wysłać nowe.",
"star.title": "Podoba ci się {app}?",
"star.body": "Gwiazdka na GitHubie pomaga większej liczbie osób go znaleźć.",
"star.button": "Dodaj gwiazdkę na GitHubie",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 1324ba6c90..4ba8d5d022 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -83,6 +83,20 @@
"notice.dismiss": "Dispensar para sempre",
"notice.notNow": "Agora não",
"notice.openFailed": "Não foi possível abrir seu navegador. Tente novamente.",
+ "server.reports.sent": "Enviado para a equipe do MausBot (relatório {report}). Milind e Omkar recebem por e-mail.",
+ "server.reports.sentReply": "Enviado para a equipe do MausBot (relatório {report}). Milind e Omkar recebem por e-mail e vão responder para {contact}.",
+ "server.reports.sentLater": "Enviado para a equipe do MausBot (relatório {report}) depois que uma tentativa anterior não deu certo. Milind e Omkar recebem por e-mail.",
+ "server.reports.sentLaterReply": "Enviado para a equipe do MausBot (relatório {report}) depois que uma tentativa anterior não deu certo. Milind e Omkar recebem por e-mail e vão responder para {contact}.",
+ "server.reports.notYet": "Ainda não enviado: {why}. O relatório está salvo e será enviado sozinho {when}, então não é preciso enviá-lo de novo.",
+ "server.reports.why.limited": "a equipe do MausBot aceita só alguns relatórios por hora de cada app",
+ "server.reports.why.offline": "não foi possível acessar o servidor da equipe do MausBot",
+ "server.reports.why.busy": "o servidor da equipe do MausBot não conseguiu recebê-lo agora",
+ "server.reports.when.minute": "em cerca de {count} minuto",
+ "server.reports.when.minutes": "em cerca de {count} minutos",
+ "server.reports.when.soon": "assim que possível",
+ "server.reports.refused": "O servidor da equipe do MausBot recusou este relatório de bug, então nada foi enviado: {detail}.",
+ "server.reports.full": "Não enviado: {count} relatórios de bug já estão esperando para ir para a equipe do MausBot. Digite @devs de novo quando eles tiverem sido enviados.",
+ "server.reports.dropped": "Um relatório de bug desta conversa não conseguiu chegar à equipe do MausBot durante uma semana, então foi descartado. Digite @devs de novo para enviar um novo.",
"star.title": "Está gostando do {app}?",
"star.body": "Uma estrela no GitHub ajuda mais pessoas a encontrá-lo.",
"star.button": "Dar uma estrela no GitHub",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 21f33345e9..64eda37d13 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -91,6 +91,20 @@
"notice.dismiss": "Больше не показывать",
"notice.notNow": "Не сейчас",
"notice.openFailed": "Не удалось открыть браузер. Повторите попытку.",
+ "server.reports.sent": "Отправлено команде MausBot (отчёт {report}). Milind и Omkar получат его по электронной почте.",
+ "server.reports.sentReply": "Отправлено команде MausBot (отчёт {report}). Milind и Omkar получат его по электронной почте и ответят на {contact}.",
+ "server.reports.sentLater": "Отправлено команде MausBot (отчёт {report}) после неудачной предыдущей попытки. Milind и Omkar получат его по электронной почте.",
+ "server.reports.sentLaterReply": "Отправлено команде MausBot (отчёт {report}) после неудачной предыдущей попытки. Milind и Omkar получат его по электронной почте и ответят на {contact}.",
+ "server.reports.notYet": "Пока не отправлено: {why}. Отчёт сохранён и отправится сам {when}, так что отправлять его ещё раз не нужно.",
+ "server.reports.why.limited": "команда MausBot принимает лишь несколько отчётов в час от каждого приложения",
+ "server.reports.why.offline": "не удалось связаться с сервером команды MausBot",
+ "server.reports.why.busy": "сервер команды MausBot сейчас не смог его принять",
+ "server.reports.when.minute": "примерно через {count} минуту",
+ "server.reports.when.minutes": "примерно через {count} мин",
+ "server.reports.when.soon": "как только появится возможность",
+ "server.reports.refused": "Сервер команды MausBot отклонил этот отчёт об ошибке, поэтому ничего не отправлено: {detail}.",
+ "server.reports.full": "Не отправлено: уже {count} отчётов об ошибках ждут отправки команде MausBot. Напишите @devs ещё раз, когда они уйдут.",
+ "server.reports.dropped": "Отчёт об ошибке из этого разговора неделю не мог дойти до команды MausBot, поэтому он удалён. Напишите @devs ещё раз, чтобы отправить новый.",
"star.title": "Нравится {app}?",
"star.body": "Звезда на GitHub поможет большему числу людей его найти.",
"star.button": "Поставить звезду на GitHub",
diff --git a/src/locales/server-lines.test.ts b/src/locales/server-lines.test.ts
new file mode 100644
index 0000000000..dee87cdb3a
--- /dev/null
+++ b/src/locales/server-lines.test.ts
@@ -0,0 +1,697 @@
+// The lines the server writes for a person to read come from the language packs (the "server." keys, through
+// serverLine in server/server-lines.ts), in the language of the person they are for. This guard reads the server's
+// code and fails on an English line written straight into one. It starts where a line is made: a bot line's text
+// (an object with role "bot"), a status row's name (its tool's name), a card (card, connector, signIn, secret,
+// routineRun, goalRun), a notification's title and body, a line's text patched in later, and what is handed to a
+// notice(...) callback. From there it follows what flows in: literals, templates, conditionals, a const, what a helper
+// returns (in the same file or a file it imports) and what a same-file helper is called with.
+// Text only a model reads, an id or a tool's name is no line: ALLOWED says why. PENDING holds the lines written before
+// this guard, by area. It only shrinks: an area's pull request moves its lines into the packs and deletes them here.
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { dirname, join, relative, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+import { describe, expect, it } from "vitest";
+
+import de from "./de.json";
+import en from "./en.json";
+
+const ROOT = fileURLToPath(new URL("../../", import.meta.url));
+const SCANNED = ["server", "shared"];
+const SKIPPED_DIRS = new Set(["node_modules", "testing", "dist", "resources"]);
+const isSource = (name: string) => name.endsWith(".ts") && !/\.test\.|\.d\.ts$/.test(name);
+
+/** Words, not an id or a tool's name: two words of letters with a space between. */
+const english = (text: string) => /[A-Za-z]{2,}[,.:;!?'’)]*\s+[(“"]?[A-Za-z]{2,}/.test(text);
+/** In an object a line is made from, the properties a person reads. */
+const SHOWN = new Set(["text", "line", "title", "question", "label", "detail", "note", "body", "summary", "hint", "prompt",
+ "description", "subtitle", "message", "reason", "button", "placeholder", "caption"]);
+const CARDS = new Set(["card", "connector", "signIn", "secret", "routineRun", "goalRun"]);
+/** Helpers whose result is their first argument's words, shortened or cleaned. */
+const PASS_THROUGH = new Set(["summarize", "clip", "oneLine", "truncate", "redactSecretsInText", "String"]);
+/** String methods whose result keeps the words of what they are called on. */
+const KEEPS_WORDS = new Set(["join", "trim", "trimEnd", "trimStart", "slice", "replace", "replaceAll", "concat", "toString"]);
+
+/** `sink`: where the line is made, as "status row at server/x.ts:12". */
+export interface Finding { file: string; line: number; text: string; sink: string }
+
+type FunctionLike = ts.FunctionDeclaration | ts.ArrowFunction | ts.FunctionExpression | ts.MethodDeclaration;
+interface Source {
+ sf: ts.SourceFile;
+ decls: Map<string, ts.FunctionDeclaration | ts.VariableDeclaration>;
+ imports: Map<string, { file: string; name: string }>;
+ calls?: Map<string, ts.CallExpression[]>;
+}
+
+const nameOf = (node: ts.PropertyName | ts.Identifier) => node.getText().replace(/^["']|["']$/g, "");
+const isFunction = (node: ts.Node | undefined): node is FunctionLike => Boolean(node)
+ && (ts.isFunctionDeclaration(node!) || ts.isArrowFunction(node!) || ts.isFunctionExpression(node!) || ts.isMethodDeclaration(node!));
+
+/** The English lines that reach a person in `paths`. `read` gives a file's text, or null when there is none. */
+export function findServerLines(paths: readonly string[], read: (path: string) => string | null, root: string): Finding[] {
+ const sources = new Map<string, Source | null>();
+ const findings = new Map<string, Finding>();
+
+ function load(path: string): Source | null {
+ if (sources.has(path)) return sources.get(path)!;
+ const text = read(path);
+ if (text === null) {
+ sources.set(path, null);
+ return null;
+ }
+ const sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
+ // The file's own top-level names: what another file can import. Names inside a function are found from the use.
+ const decls = new Map<string, ts.FunctionDeclaration | ts.VariableDeclaration>();
+ for (const statement of sf.statements) {
+ if (ts.isFunctionDeclaration(statement) && statement.name) decls.set(statement.name.text, statement);
+ else if (ts.isVariableStatement(statement)) {
+ for (const one of statement.declarationList.declarations) if (ts.isIdentifier(one.name) && one.initializer) decls.set(one.name.text, one);
+ }
+ }
+ const imports = new Map<string, { file: string; name: string }>();
+ for (const statement of sf.statements) {
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
+ const bindings = statement.importClause?.namedBindings, specifier = statement.moduleSpecifier.text;
+ if (!bindings || !ts.isNamedImports(bindings) || !specifier.startsWith(".") || !specifier.endsWith(".ts")) continue;
+ const file = resolve(dirname(path), specifier);
+ for (const element of bindings.elements) imports.set(element.name.text, { file, name: (element.propertyName ?? element.name).text });
+ }
+ const source = { sf, decls, imports };
+ sources.set(path, source);
+ return source;
+ }
+
+ function report(source: Source, node: ts.Node, text: string, sink: string): void {
+ const line = source.sf.getLineAndCharacterOfPosition(node.getStart(source.sf)).line + 1;
+ const file = relative(root, source.sf.fileName).split("\\").join("/");
+ findings.set(`${file}:${line}:${text}`, { file, line, text, sink });
+ }
+
+ function callsTo(source: Source, name: string): ts.CallExpression[] {
+ if (!source.calls) {
+ const calls = new Map<string, ts.CallExpression[]>();
+ const visit = (node: ts.Node) => {
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) calls.set(node.expression.text, [...(calls.get(node.expression.text) ?? []), node]);
+ ts.forEachChild(node, visit);
+ };
+ visit(source.sf);
+ source.calls = calls;
+ }
+ return source.calls.get(name) ?? [];
+ }
+
+ /** The function `name` is a parameter of, at the use, and its position. */
+ function parameterOf(node: ts.Node, name: string): { fn: FunctionLike; index: number } | null {
+ for (let at: ts.Node | undefined = node.parent; at; at = at.parent) {
+ if (!isFunction(at)) continue;
+ const index = at.parameters.findIndex((parameter) => ts.isIdentifier(parameter.name) && parameter.name.text === name);
+ if (index >= 0) return { fn: at, index };
+ }
+ return null;
+ }
+
+ function functionName(fn: FunctionLike): string | null {
+ if (ts.isFunctionDeclaration(fn)) return fn.name?.text ?? null;
+ return ts.isVariableDeclaration(fn.parent) && ts.isIdentifier(fn.parent.name) ? fn.parent.name.text : null;
+ }
+
+ /** The calls to a named function within the block it is declared in. */
+ function callsOf(source: Source, fn: FunctionLike): ts.CallExpression[] {
+ const name = functionName(fn);
+ if (!name) return [];
+ let scope: ts.Node | undefined = ts.isFunctionDeclaration(fn) ? fn.parent : fn.parent.parent;
+ while (scope && !ts.isBlock(scope) && !ts.isSourceFile(scope) && !ts.isModuleBlock(scope)) scope = scope.parent;
+ return callsTo(source, name).filter((call) => !scope || (call.pos >= scope.pos && call.end <= scope.end));
+ }
+
+ function returnsOf(fn: FunctionLike): ts.Expression[] {
+ if (ts.isArrowFunction(fn) && !ts.isBlock(fn.body)) return [fn.body];
+ const found: ts.Expression[] = [];
+ const visit = (node: ts.Node) => {
+ if (node !== fn && isFunction(node)) return;
+ if (ts.isReturnStatement(node) && node.expression) found.push(node.expression);
+ ts.forEachChild(node, visit);
+ };
+ if (fn.body) visit(fn.body);
+ return found;
+ }
+
+ /** The nearest declaration of `name` in scope at the use, else the file's. */
+ function declarationOf(source: Source, node: ts.Node, name: string): ts.FunctionDeclaration | ts.VariableDeclaration | null {
+ for (let at: ts.Node | undefined = node.parent; at; at = at.parent) {
+ if (!ts.isBlock(at) && !ts.isSourceFile(at) && !ts.isModuleBlock(at)) continue;
+ for (const statement of at.statements) {
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === name) return statement;
+ if (!ts.isVariableStatement(statement)) continue;
+ const found = statement.declarationList.declarations.find((one) => ts.isIdentifier(one.name) && one.name.text === name && one.initializer);
+ if (found) return found;
+ }
+ }
+ return source.decls.get(name) ?? null;
+ }
+
+ /** What `name` names at `node`: a declaration here, else the one it is imported from. */
+ function resolveName(source: Source, node: ts.Node, name: string): { source: Source; decl: ts.FunctionDeclaration | ts.VariableDeclaration } | null {
+ const local = declarationOf(source, node, name);
+ if (local) return { source, decl: local };
+ const imported = source.imports.get(name);
+ const target = imported ? load(imported.file) : null;
+ const decl = imported && target ? target.decls.get(imported.name) : undefined;
+ return target && decl ? { source: target, decl } : null;
+ }
+
+ const functionOf = (decl: ts.FunctionDeclaration | ts.VariableDeclaration): FunctionLike | null =>
+ ts.isFunctionDeclaration(decl) ? decl : isFunction(decl.initializer) ? decl.initializer : null;
+
+ function trace(source: Source, expr: ts.Node | undefined, sink: string, seen: Set<string>, depth = 0): void {
+ if (!expr || depth > 14) return;
+ const key = `${source.sf.fileName}:${expr.pos}:${expr.end}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ const next = (node: ts.Node | undefined, from: Source = source) => trace(from, node, sink, seen, depth + 1);
+ if (ts.isStringLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) {
+ if (english(expr.text)) report(source, expr, expr.text, sink);
+ } else if (ts.isTemplateExpression(expr)) {
+ const words = [expr.head.text, ...expr.templateSpans.map((span) => span.literal.text)].join(" … ");
+ if (english(words)) report(source, expr, words, sink);
+ for (const span of expr.templateSpans) next(span.expression);
+ } else if (ts.isParenthesizedExpression(expr) || ts.isAsExpression(expr) || ts.isNonNullExpression(expr) || ts.isSatisfiesExpression(expr)
+ || ts.isTypeAssertionExpression(expr) || ts.isAwaitExpression(expr)) {
+ next(expr.expression);
+ } else if (ts.isConditionalExpression(expr)) {
+ next(expr.whenTrue);
+ next(expr.whenFalse);
+ } else if (ts.isBinaryExpression(expr)) {
+ const kind = expr.operatorToken.kind;
+ if (kind === ts.SyntaxKind.PlusToken || kind === ts.SyntaxKind.BarBarToken || kind === ts.SyntaxKind.QuestionQuestionToken
+ || kind === ts.SyntaxKind.AmpersandAmpersandToken) {
+ next(expr.left);
+ next(expr.right);
+ }
+ } else if (ts.isArrayLiteralExpression(expr)) {
+ for (const element of expr.elements) next(element);
+ } else if (ts.isSpreadElement(expr)) {
+ next(expr.expression);
+ } else if (ts.isIdentifier(expr)) {
+ const parameter = parameterOf(expr, expr.text);
+ if (parameter) {
+ for (const call of callsOf(source, parameter.fn)) next(call.arguments[parameter.index]);
+ return;
+ }
+ const named = resolveName(source, expr, expr.text);
+ if (named && ts.isVariableDeclaration(named.decl) && !isFunction(named.decl.initializer)) next(named.decl.initializer, named.source);
+ } else if (ts.isCallExpression(expr)) {
+ const callee = expr.expression;
+ if (ts.isPropertyAccessExpression(callee) && KEEPS_WORDS.has(callee.name.text)) {
+ next(callee.expression);
+ } else if (ts.isPropertyAccessExpression(callee) && callee.name.text === "map") {
+ const mapper = expr.arguments[0];
+ if (isFunction(mapper)) for (const result of returnsOf(mapper)) next(result);
+ } else if (ts.isIdentifier(callee) && callee.text === "serverLine") {
+ // The words the line's {names} are filled with.
+ const params = expr.arguments[2];
+ if (params && ts.isObjectLiteralExpression(params)) {
+ for (const one of params.properties) {
+ if (ts.isPropertyAssignment(one)) next(one.initializer);
+ else if (ts.isShorthandPropertyAssignment(one)) next(one.name);
+ else if (ts.isSpreadAssignment(one)) next(one.expression);
+ }
+ } else next(params);
+ } else if (ts.isIdentifier(callee) && PASS_THROUGH.has(callee.text)) {
+ next(expr.arguments[0]);
+ } else if (ts.isIdentifier(callee)) {
+ const named = resolveName(source, expr, callee.text);
+ const fn = named ? functionOf(named.decl) : null;
+ if (named && fn) for (const result of returnsOf(fn)) next(result, named.source);
+ }
+ } else if (ts.isObjectLiteralExpression(expr)) {
+ for (const property of expr.properties) {
+ if (ts.isPropertyAssignment(property) && SHOWN.has(nameOf(property.name))) next(property.initializer);
+ else if (ts.isShorthandPropertyAssignment(property) && SHOWN.has(property.name.text)) next(property.name);
+ else if (ts.isSpreadAssignment(property)) next(property.expression);
+ }
+ } else if (ts.isPropertyAccessExpression(expr)) {
+ for (const object of objectsOf(source, expr.expression, new Set(), 0)) {
+ const property = object.node.properties.find((one) => (ts.isPropertyAssignment(one) || ts.isShorthandPropertyAssignment(one))
+ && nameOf(one.name) === expr.name.text);
+ if (property) next(ts.isPropertyAssignment(property) ? property.initializer : property.name, object.source);
+ }
+ }
+ }
+
+ /** The object literals an expression can be. */
+ function objectsOf(source: Source, expr: ts.Node | undefined, seen: Set<string>, depth: number): Array<{ source: Source; node: ts.ObjectLiteralExpression }> {
+ if (!expr || depth > 10) return [];
+ const key = `${source.sf.fileName}:${expr.pos}:${expr.end}`;
+ if (seen.has(key)) return [];
+ seen.add(key);
+ const next = (node: ts.Node | undefined, from: Source = source) => objectsOf(from, node, seen, depth + 1);
+ if (ts.isObjectLiteralExpression(expr)) return [{ source, node: expr }];
+ if (ts.isParenthesizedExpression(expr) || ts.isAsExpression(expr) || ts.isNonNullExpression(expr) || ts.isSatisfiesExpression(expr)
+ || ts.isAwaitExpression(expr)) return next(expr.expression);
+ if (ts.isConditionalExpression(expr)) return [...next(expr.whenTrue), ...next(expr.whenFalse)];
+ if (ts.isBinaryExpression(expr)) return [...next(expr.left), ...next(expr.right)];
+ if (ts.isIdentifier(expr)) {
+ const parameter = parameterOf(expr, expr.text);
+ if (parameter) return callsOf(source, parameter.fn).flatMap((call) => next(call.arguments[parameter.index]));
+ const named = resolveName(source, expr, expr.text);
+ return named && ts.isVariableDeclaration(named.decl) ? next(named.decl.initializer, named.source) : [];
+ }
+ if (ts.isCallExpression(expr) && ts.isIdentifier(expr.expression)) {
+ const named = resolveName(source, expr, expr.expression.text);
+ const fn = named ? functionOf(named.decl) : null;
+ return named && fn ? returnsOf(fn).flatMap((result) => next(result, named.source)) : [];
+ }
+ return [];
+ }
+
+ const property = (object: ts.ObjectLiteralExpression, name: string) => object.properties.find((one): one is ts.PropertyAssignment | ts.ShorthandPropertyAssignment =>
+ (ts.isPropertyAssignment(one) || ts.isShorthandPropertyAssignment(one)) && nameOf(one.name) === name);
+ const valueOf = (one: ts.PropertyAssignment | ts.ShorthandPropertyAssignment) => (ts.isPropertyAssignment(one) ? one.initializer : one.name);
+
+ for (const path of paths) {
+ const source = load(path);
+ if (!source) continue;
+ const at = (node: ts.Node, what: string) =>
+ `${what} at ${relative(root, source.sf.fileName).split("\\").join("/")}:${source.sf.getLineAndCharacterOfPosition(node.getStart(source.sf)).line + 1}`;
+ const visit = (node: ts.Node) => {
+ if (ts.isObjectLiteralExpression(node)) {
+ const role = property(node, "role");
+ if (role && ts.isPropertyAssignment(role) && ts.isStringLiteral(role.initializer) && role.initializer.text === "bot") {
+ for (const one of node.properties) {
+ if (!ts.isPropertyAssignment(one) && !ts.isShorthandPropertyAssignment(one)) continue;
+ const name = nameOf(one.name);
+ if (name === "text") trace(source, valueOf(one), at(node, "line"), new Set());
+ else if (CARDS.has(name)) trace(source, valueOf(one), at(node, `card ${name}`), new Set());
+ else if (name === "tool") {
+ for (const tool of objectsOf(source, valueOf(one), new Set(), 0)) {
+ const toolName = property(tool.node, "name");
+ if (toolName) trace(tool.source, valueOf(toolName), at(node, "status row"), new Set());
+ }
+ }
+ }
+ }
+ const title = property(node, "title"), body = property(node, "body");
+ if (property(node, "botId") && title && body) {
+ trace(source, valueOf(title), at(node, "notification"), new Set());
+ trace(source, valueOf(body), at(node, "notification"), new Set());
+ }
+ } else if (ts.isCallExpression(node)) {
+ const callee = node.expression;
+ const called = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : "";
+ if (called === "patchMessage" && node.arguments[2] && ts.isObjectLiteralExpression(node.arguments[2])) {
+ const text = property(node.arguments[2], "text");
+ if (text) trace(source, valueOf(text), at(node, "line"), new Set());
+ } else if (called === "notice") {
+ for (const argument of node.arguments) trace(source, argument, at(node, "notice"), new Set());
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(source.sf);
+ }
+ return [...findings.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
+}
+
+function* sources(dir: string): Generator<string> {
+ for (const name of readdirSync(dir)) {
+ if (SKIPPED_DIRS.has(name)) continue;
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) yield* sources(path);
+ else if (isSource(name)) yield path;
+ }
+}
+
+const readTree = (path: string) => (existsSync(path) ? readFileSync(path, "utf8") : null);
+
+/** English on purpose: what reaches a line here is not words a person reads in it. */
+const ALLOWED: ReadonlyArray<{ file: string; snippet: string; why: string }> = [
+ { file: "server/host/helper-suggestion.ts", snippet: "Want me to sort your email for free?", why: "the app draws this suggestion in its own words (setupSuggestion)" },
+ { file: "shared/client-cancel.ts", snippet: "You stopped this.", why: "a stopped turn's marker: the app says it in the reader's language (chat.turnStopped)" },
+];
+
+/** Lines written before this guard, by area: a file and the line's words (" … " where a value goes). Only shrinks. */
+const PENDING: Readonly<Record<string, ReadonlyArray<readonly [file: string, snippet: string]>>> = {
+ "runs and routines": [
+ ["server/app-trigger-requests.ts", "When an email arrives in Gmail …"],
+ ["server/app-trigger-requests.ts", "When “ … ” happens in … …"],
+ ["server/app-trigger-requests.ts", "(it checks every 15 minutes)"],
+ ["server/app-trigger-requests.ts", "reviews the event"],
+ ["server/automation-reports.ts", "Recovered: … finished OK at …"],
+ ["server/automation-reports.ts", "This run didn't finish: …"],
+ ["server/automation-reports.ts", "This run didn't finish."],
+ ["server/incidents.ts", "in the room \" … \""],
+ ["server/incidents.ts", "in its thread # …"],
+ ["server/incidents.ts", "in its main conversation"],
+ ["server/incidents.ts", "… 's run … stopped after showing no activity …"],
+ ["server/incidents.ts", "… 's run … could not start …"],
+ ["server/incidents.ts", "… 's scheduled routine … failed …"],
+ ["server/routine-requests.ts", "Each time … 's usage limit resets"],
+ ["server/routine-requests.ts", "When … 's usage limit resets"],
+ ["server/routine-requests.ts", "Every … minutes, cadence starting at confirmation; first run is the"],
+ ["server/routine-requests.ts", "Every … minutes, starting one interval after confirmation"],
+ ["server/routine-requests.ts", "Every … minutes, anchored at … …"],
+ ["server/routine-requests.ts", "each run starts a fresh session with the previous run's report"],
+ ["server/routine-requests.ts", "each run starts a fresh session"],
+ ["server/routine-requests.ts", "Will run at matching calendar times, … ; … ."],
+ ["server/routine-requests.ts", "Will run once; that run starts a fresh session."],
+ ["server/routine-requests.ts", "Will run a minute after each time that usage limit resets, in this con"],
+ ["server/routine-requests.ts", "Will run once, a minute after that usage limit resets, and continue in"],
+ ["server/routine-requests.ts", "Will run every … minutes when its day, time, and end restrictions al"],
+ ["server/routine-requests.ts", "about once a day"],
+ ["server/routine-requests.ts", "Will run … ; … ."],
+ ["server/routine-requests.ts", "every day"],
+ ["server/routine-requests.ts", "one day a week"],
+ ["server/routine-requests.ts", "Bot’s current model on its cloud desktop"],
+ ["server/routine-requests.ts", "Bot’s current model, where it usually works"],
+ ["server/routine-requests.ts", "None — this routine remains paused"],
+ ["server/routine-requests.ts", "Next allowed time after confirmation ( … )"],
+ ["server/routine-requests.ts", "One interval after confirmation"],
+ ["server/routine-requests.ts", "None — this routine will be paused"],
+ ["server/routine-requests.ts", "None — this routine will be deleted"],
+ ["server/routine-requests.ts", "When that limit resets (the time is not known yet)"],
+ ["server/routine-requests.ts", "For: @ … — each run uses that bot's AI and permissions"],
+ ["server/routine-requests.ts", "Next run: …"],
+ ["server/routine-requests.ts", "Runs on: …"],
+ ["server/routine-requests.ts", "Run limit: …"],
+ ["server/routine-requests.ts", "No limit"],
+ ["server/routine-requests.ts", "Carries the previous run's report into the next run"],
+ ["server/routine-requests.ts", "Each run starts fresh"],
+ ["server/routine-requests.ts", "While busy: …"],
+ ["server/routine-requests.ts", "Queue one scheduled run; skip further occurrences until it starts"],
+ ["server/routine-requests.ts", "Skip overlapping scheduled occurrences"],
+ ["server/routine-requests.ts", "On startup: …"],
+ ["server/routine-requests.ts", "Also runs once each time OpenMausBot starts"],
+ ["server/routine-requests.ts", "Runs only on its schedule"],
+ ["server/routine-run-card.ts", "needs your input"],
+ ["server/routine-run-card.ts", "was blocked"],
+ ["server/routine-run-card.ts", "reached its limit"],
+ ["server/routine-run-card.ts", "was stopped"],
+ ["server/routine-run-card.ts", "needs your attention"],
+ ["server/routine-run-card.ts", "was cancelled"],
+ ["server/routine-run-card.ts", "was missed"],
+ ["server/routine-run-card.ts", "deferred: target busy"],
+ ["server/webhook-requests.ts", "When another app sends something … , … …"],
+ ["server/webhook-requests.ts", "does what it is asked"],
+ ["shared/plain-time-zone.ts", "every day"],
+ ],
+ "connect prompts and sign-ins": [
+ ["server/automation-reports.ts", "I need you to sign in to … …"],
+ ["server/automation-reports.ts", "I need you to connect … ."],
+ ["server/automation-reports.ts", "I need your … ."],
+ ["server/connector-card-text.ts", "this app"],
+ ["server/connector-card-text.ts", "Connect … as “ … ” to continue."],
+ ["server/connector-card-text.ts", "Connect … to continue."],
+ ["server/host/secret-cards.ts", "… 's commands can read it from a private file for 24 hours; it is neve"],
+ ["server/host/secret-cards.ts", "… gets a one-use reference for OpenMausBot's own tools and never sees"],
+ ["server/host/secret-cards.ts", "Securely provide the … from OpenMausBot on your phone or computer. I"],
+ ["server/host/secret-cards.ts", "… … can use it but never read it back."],
+ ["server/index.ts", "Connect … as “ … ” so the bot can continue"],
+ ["server/index.ts", "Connect … so the bot can continue"],
+ ["shared/sign-in-request.ts", "… needs you to sign in to … . Open this conversation in OpenMausBot"],
+ ],
+ "rooms and teammates": [
+ ["server/escalations.ts", "in the room \" … \""],
+ ["server/escalations.ts", "in its thread # …"],
+ ["server/escalations.ts", "in its main conversation"],
+ ["server/escalations.ts", "… 's work … is parked at a gate: … ."],
+ ["server/host/delegated-level.ts", "… — delegated by … , … a Chief of Staff on …"],
+ ["server/host/goal-cards.ts", "… is coordinating this goal."],
+ ["server/host/goal-cards.ts", "Goal in progress: …"],
+ ["server/host/goal-cards.ts", "needs your input"],
+ ["server/host/goal-cards.ts", "reached its limit"],
+ ["server/host/handoff-sent.ts", "this room"],
+ ["server/host/handoff-sent.ts", "Sent to … directly: it isn't in … ."],
+ ["server/host/handoff-sent.ts", "Sent to … …"],
+ ["server/host/person-inbox.ts", "… 's assistant answered"],
+ ["server/host/team-messages.ts", "Not passed to …"],
+ ["server/index.ts", "Send failed — …"],
+ ["server/index.ts", "Result withheld: …"],
+ ["server/index.ts", "delegated work"],
+ ["server/index.ts", "Resumed with a question from …"],
+ ["server/index.ts", "Resumed with … results"],
+ ["server/index.ts", "… is finishing another conversation — will reply here when free"],
+ ["server/index.ts", "… is no longer available — skipped this round"],
+ ["server/index.ts", "… stayed busy in another conversation for … minute … — skipped thi"],
+ ["server/index.ts", "Answer passed to the waiting work"],
+ ["server/index.ts", "… is busy in another conversation — skipped this round"],
+ ["server/index.ts", "… 's settings changed while starting — skipped this round"],
+ ["server/index.ts", "… 's computer provider is being updated — skipped this round"],
+ ["server/index.ts", "… 's cloud computer is being changed — skipped this round"],
+ ["server/index.ts", "… became busy in another conversation — skipped this round"],
+ ["server/index.ts", "… isn't in this room, so that mention didn't reach them — add them to"],
+ ["server/index.ts", "… is archived and can't respond — restore it or mention an active roo"],
+ ["server/index.ts", "… is still stopping — this message was not dispatched"],
+ ["server/index.ts", "A room member"],
+ ["server/index.ts", "Posted in …"],
+ ["server/index.ts", "Opened thread # …"],
+ ["server/peer-approval.ts", "@ … wants to … …"],
+ ["server/recall-disclosure.ts", "… recalled … message … from its private chat with you"],
+ ["server/recall-disclosure.ts", "… 's recent-work brief covers … private chat … with you"],
+ ["server/room-context.ts", "compacted … 's context ( … % full): fresh session with the room's rec"],
+ ["server/room-context.ts", "… 's context was … % full: compacted to a fresh session with the room"],
+ ["server/room-holds.ts", "… is held (stopped by you) — @mention it or say resume"],
+ ["server/room-reply.ts", "… finished without a summary — asking for a short result"],
+ ["server/room-reply.ts", "… finished without a summary"],
+ ["server/room-turn-timeout.ts", "… 's room turn made no progress for … … and was stopped"],
+ ["server/routes/internal-threads.ts", "Closed by @ …"],
+ ["server/store.ts", "needs your input"],
+ ["server/store.ts", "reached its turn limit"],
+ ["server/waiting-on-person.ts", "Queued for @ … behind your … in “ … ”"],
+ ],
+ "notifications": [
+ ["server/host/person-inbox.ts", "… · your assistant answered"],
+ ["server/notify.ts", "… needs approval"],
+ ["server/notify.ts", "… needs you to sign in to …"],
+ ["server/notify.ts", "… 's routine failed"],
+ ["server/notify.ts", "… 's routine is waiting"],
+ ["server/notify.ts", "… resumed with results"],
+ ["server/notify.ts", "… mentioned you"],
+ ["server/notify.ts", "… 's wait is over"],
+ ],
+ "AI engines and limits": [
+ ["server/cloud-credit-moves.ts", "notice: … is connected, so this conversation uses it now instead of"],
+ ["server/computer-engine-removal.ts", "The Computer choice in the model list was removed."],
+ ["server/computer-engine-removal.ts", "This conversation now uses … ."],
+ ["server/computer-engine-removal.ts", "… now uses … ; this conversation keeps its own model."],
+ ["server/computer-engine-removal.ts", "… now uses … ."],
+ ["server/computer-engine-removal.ts", "… can't use a desktop, so"],
+ ["server/computer-engine-removal.ts", "… still works on its cloud desktop."],
+ ["server/computer-engine-removal.ts", "It still works on … 's cloud desktop."],
+ ["server/computer-engine-removal.ts", "… no longer works on its"],
+ ["server/computer-engine-removal.ts", "it no longer works on … 's"],
+ ["server/computer-engine-removal.ts", "cloud desktop. To use it again, choose a model that can use a desktop."],
+ ["server/computer-engine-removal.ts", "… … can't reply on … while its Works on is Cloud desktop."],
+ ["server/computer-engine-removal.ts", "Choose a model that can use a desktop, or set Works on to Auto."],
+ ["server/computer-engine-removal.ts", "… … can't reply here while this conversation is pinned to its cloud"],
+ ["server/computer-engine-removal.ts", "Choose a model that can use a desktop, or clear this conversation's pl"],
+ ["server/computer-engine-removal.ts", "… 's permissions are now Ask, but this conversation's stay as they wer"],
+ ["server/computer-engine-removal.ts", "Its permissions are now Ask."],
+ ["server/drivers/acp/cursor.ts", "Cursor offers … rather than … in this session, so this conversatio"],
+ ["server/drivers/acp/cursor.ts", "Cursor did not accept … in this session, so it runs … ."],
+ ["server/drivers/acp/cursor.ts", "its default model"],
+ ["server/drivers/acp/cursor.ts", "Choose another model for this bot to stop seeing this."],
+ ["server/drivers/codex-unsupported-calls.ts", "Codex could not run … … (\"unsupported call\"): the AI provider sent"],
+ ["server/drivers/codex-unsupported-calls.ts", "the tool"],
+ ["server/drivers/codex-unsupported-calls.ts", "the tools"],
+ ["server/drivers/codex-unsupported-calls.ts", "the call back without the tool's app name, so it never reached the too"],
+ ["server/index.ts", "notice: This thread's model ( … ) isn't available, so it now uses … '"],
+ ["server/index.ts", "Company connection changed — choose whether to reconnect or use a pers"],
+ ["server/quota-switch.ts", "while … is signed out"],
+ ["server/quota-switch.ts", "after hitting the usage limit"],
+ ["server/quota-switch.ts", "switched to … . Your request waits on a card above and continues on"],
+ ["server/quota-switch.ts", "switched to … . Your request is still under way here and continues on"],
+ ["server/quota-switch.ts", "switched to … . This conversation is working, so your message was not"],
+ ["server/quota-switch.ts", "switched to … . A teammate's question is waiting for your answer in t"],
+ ["server/quota-switch.ts", "switched to … , but your message could not be found to send again. Se"],
+ ["server/quota-switch.ts", "continuing on … …"],
+ ["server/quota-switch.ts", "could not continue on … : …"],
+ ["server/quota-switch.ts", "continuing with another AI is switched off — nothing switched."],
+ ["server/quota-switch.ts", "… is no longer configured, and the card offered no other AI — nothing"],
+ ["server/quota-switch.ts", "… is no longer configured — nothing switched."],
+ ["server/quota-switch.ts", "this conversation's own AI is no longer configured here, so no other A"],
+ ["server/quota-switch.ts", "… did not answer in time — nothing switched. Try again in a moment."],
+ ["server/quota-switch.ts", "… is no longer available — nothing switched."],
+ ["server/quota-switch.ts", "could not switch to … — …"],
+ ["server/quota-switch.ts", "could not switch to … — the model switch could not be saved."],
+ ["server/quota-switch.ts", "already on"],
+ ["server/quota-switch.ts", "switched to"],
+ ["server/quota-switch.ts", "… . Your request waits on a card above and continues on … once you a"],
+ ["server/quota-switch.ts", "… . Your request is still under way here and continues on … ."],
+ ["server/quota-switch.ts", "… . This conversation is working, so your message was not sent again."],
+ ["server/quota-switch.ts", "… . A teammate's question is waiting for your answer in this conversat"],
+ ["server/quota-switch.ts", "… , but the message that hit quota could not be found to resend — send"],
+ ["server/quota-switch.ts", "continuing on … after hitting quota"],
+ ["server/quota-switch.ts", "could not continue on … — …"],
+ ],
+ "computers and the browser": [
+ ["server/browser/viewers/stream-v2.ts", "The browser could not restart. Wait for active work to finish and try"],
+ ["server/computer-wait.ts", "… is running …"],
+ ["server/computer-wait.ts", "… is using it"],
+ ["server/computer-wait.ts", "— … in queue"],
+ ["server/computer-wait.ts", "; recent waits here have taken …"],
+ ["server/computer-wait.ts", "Starts automatically when the turns ahead finish"],
+ ["server/computer-wait.ts", "Starts automatically when that finishes"],
+ ["server/computer-wait.ts", "Starts automatically when it is free"],
+ ["server/computer-wait.ts", "Waiting for its turn on this computer … . … … ."],
+ ["server/computer-wait.ts", "Waiting for its turn on this computer … — … . … … ."],
+ ["server/computer-wait.ts", "( … held it)"],
+ ["server/computer-wait.ts", "Computer free — continuing after waiting … …"],
+ ["server/computer-wait.ts", "Stopped waiting for the computer after … … ."],
+ ["server/computer-wait.ts", "Computer still busy after … … . Parked — it continues automatically"],
+ ["server/index.ts", "Could not continue on … : …"],
+ ["server/surface.ts", "the cloud computer"],
+ ["server/surface.ts", "the Local VM"],
+ ["server/surface.ts", "this computer"],
+ ["server/surface.ts", "the built-in browser"],
+ ],
+ "questions, approvals and setup cards": [
+ ["server/auto-approve.ts", "the saved command permission"],
+ ["server/auto-approve.ts", "the saved tool permission"],
+ ["server/auto-approve.ts", "Full access"],
+ ["server/auto-approve.ts", "The provider rejected this action despite … ."],
+ ["server/default-bot.ts", "Hey! I'm … . I'm new here."],
+ ["server/default-bot.ts", "Hi! I'm … , your helper for everything here."],
+ ["server/host/ask-cards.ts", "Waiting on your … in @ …"],
+ ["server/host/ask-cards.ts", "Your bot has a question"],
+ ["server/host/ask-cards.ts", "… needs your input: …"],
+ ["server/index.ts", "Command allowed once, but its allowlist rule could not be saved. Try a"],
+ ["server/index.ts", "Couldn't deliver that answer — the request is no longer open, so the a"],
+ ["server/index.ts", "Approve for me: … 's automatic reviewer is not available … , so this"],
+ ["server/index.ts", "Local computer approval"],
+ ["server/index.ts", "Approval needed"],
+ ["server/index.ts", "Your bot has a question"],
+ ["server/model-requests.ts", "'s default AI and model?"],
+ ["server/model-requests.ts", "Whose default model: @"],
+ ["server/outbound-hold.ts", "Send on your behalf?"],
+ ["server/profile-requests.ts", "Set up … ?"],
+ ["server/profile-requests.ts", "Whose profile: @ …"],
+ ["server/read-and-draft.ts", "Refused (reads and drafts only): …"],
+ ["server/skill-request-card.ts", "It keeps … reference file … the bot reads when needed."],
+ ["server/skill-request-card.ts", "Enable skill \" … \"?"],
+ ["server/skill-request-card.ts", "Update skill \" … \"?"],
+ ["server/skill-request-card.ts", "… \n\nAdds one line to the prompt index; the body is read only when used"],
+ ["server/team-memory-requests.ts", "Remembered for the team"],
+ ["server/team-memory-requests.ts", "Remember this for the team?"],
+ ["server/team-setup-requests.ts", "Team setup applied"],
+ ["server/team-setup-requests.ts", "Team setup not applied"],
+ ],
+ "restarts, stops and context": [
+ ["server/host/person-stop.ts", "Stopped here — … is still working; open to stop it too"],
+ ["server/index.ts", "Resuming after a restart"],
+ ["server/index.ts", "… was cut off by a restart; resuming"],
+ ["server/index.ts", "context compaction started ( … )"],
+ ["server/index.ts", "context compacted — re-sent the last … digest …"],
+ ["server/index.ts", "generated image could not be attached — …"],
+ ["server/index.ts", "invalid image"],
+ ["server/index.ts", "Queued follow-up interrupted by restart or restore — it may have alrea"],
+ ["shared/first-reply-rescue.ts", "notice: … hasn't heard back from … yet."],
+ ],
+ "moves to the Cloud": [
+ ["server/cloud-send-arrived.ts", "Now that I live on My Cloud, my webhook \" … \" has a new address. Open"],
+ ["server/cloud-send-arrived.ts", "I'm back on this computer, so my webhook \" … \" has an address here aga"],
+ ],
+ "calls": [
+ ["shared/live-call.ts", "Call with … · …"],
+ ],
+};
+
+
+
+const listed = (finding: Finding, file: string, snippet: string) => finding.file === file && finding.text.includes(snippet);
+
+describe("lines the server writes for a person", () => {
+ const findings = findServerLines(SCANNED.flatMap((top) => [...sources(join(ROOT, top))]), readTree, ROOT);
+ const pending = Object.values(PENDING).flat();
+
+ it("come from the language packs, never as English written into the code", () => {
+ const offending = findings
+ .filter((finding) => !ALLOWED.some((one) => listed(finding, one.file, one.snippet)) && !pending.some(([file, snippet]) => listed(finding, file, snippet)))
+ .map((finding) => `${finding.file}:${finding.line}: ${JSON.stringify(finding.text.slice(0, 140))} (${finding.sink})`);
+ // A line a person reads: add its words under "server." in en.json (and de.json), and write it with serverLine() in
+ // the language lineLanguage gives for the person it is for. Text only a model reads: add it to ALLOWED with why.
+ expect(offending).toEqual([]);
+ });
+
+ it("lists only lines that are still there", () => {
+ const stale = [
+ ...ALLOWED.filter((one) => !findings.some((finding) => listed(finding, one.file, one.snippet))).map((one) => `ALLOWED ${one.file}: ${one.snippet}`),
+ ...pending.filter(([file, snippet]) => !findings.some((finding) => listed(finding, file, snippet))).map(([file, snippet]) => `PENDING ${file}: ${snippet}`),
+ ];
+ // Translated or gone: delete it here.
+ expect(stale).toEqual([]);
+ });
+
+ it("every server line has German words, and the server uses each one", () => {
+ const keys = Object.keys(en).filter((key) => key.startsWith("server."));
+ expect(keys.length).toBeGreaterThan(0);
+ expect(keys.filter((key) => !Object.hasOwn(de, key))).toEqual([]);
+ const code = SCANNED.flatMap((top) => [...sources(join(ROOT, top))]).map((path) => readFileSync(path, "utf8")).join("\n");
+ expect(keys.filter((key) => !code.includes(`"${key}"`))).toEqual([]);
+ });
+
+ it("only server-lines.ts (English) and server-line-packs.ts (the rest) read the language packs on the server", () => {
+ const readers = SCANNED.flatMap((top) => [...sources(join(ROOT, top))])
+ .filter((path) => /from ["'][./]+\/src\/locales\//.test(readFileSync(path, "utf8")))
+ .map((path) => relative(ROOT, path).split("\\").join("/"));
+ expect(readers.sort()).toEqual(["server/server-line-packs.ts", "server/server-lines.ts"]);
+ // The server loads the other languages when it starts; without them every line reads in English.
+ expect(readFileSync(join(ROOT, "server/index.ts"), "utf8")).toMatch(/^import [^\n]*\bimport "\.\/server-line-packs\.ts";$|^import "\.\/server-line-packs\.ts";$/m);
+ });
+});
+
+describe("the guard", () => {
+ const ROOT_HERE = "/repo";
+ const scan = (files: Record<string, string>) =>
+ findServerLines(Object.keys(files).map((file) => `${ROOT_HERE}/${file}`), (path) => files[relative(ROOT_HERE, path)] ?? null, ROOT_HERE)
+ .map((finding) => `${finding.file} ${finding.sink.replace(/ at \S+$/, "")}: ${finding.text}`);
+
+ it("finds a new English line in each place a line is made", () => {
+ expect(scan({
+ "server/a.ts": [
+ `import { reportLine } from "./lines.ts";`,
+ `const DONE = "The report went to the team.";`,
+ `const failed = (why: string) => \`Could not send it: \${why}.\`;`,
+ `function tell(threadId: string, text: string) { store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: \`notice: \${text}\` } }); }`,
+ `store.appendMessage(id, { role: "bot", kind: "text", text: "Your report is on its way." });`,
+ `store.appendMessage(id, { role: "bot", kind: "text", text: ok ? DONE : failed("offline") });`,
+ `tell(id, "Sent to the team just now.");`,
+ `store.appendMessage(id, { role: "bot", kind: "text", text: reportLine(id) });`,
+ `store.patchMessage(id, line, { text: \`Finished at \${time}\` });`,
+ `const note = { kind: "done", botId: bot.id, title: \`\${bot.name} finished the job\`, body };`,
+ `deps.notice(\`Switched to \${name} after the limit.\`);`,
+ `store.appendMessage(id, { role: "bot", kind: "options", card: { title: "Send on your behalf?", options } });`,
+ ].join("\n"),
+ "server/lines.ts": `export function reportLine(id: string): string { return \`Report \${id} is saved for later.\`; }`,
+ })).toEqual([
+ "server/a.ts line: The report went to the team.",
+ "server/a.ts line: Could not send it: … .",
+ "server/a.ts line: Your report is on its way.",
+ "server/a.ts status row: Sent to the team just now.",
+ "server/a.ts line: Finished at … ",
+ "server/a.ts notification: … finished the job",
+ "server/a.ts notice: Switched to … after the limit.",
+ "server/a.ts card card: Send on your behalf?",
+ "server/lines.ts line: Report … is saved for later.",
+ ]);
+ });
+
+ it("lets through a line from the packs, an id, a tool's name and text no line is made of", () => {
+ expect(scan({
+ "server/b.ts": [
+ `const language = lineLanguage(person);`,
+ `store.appendMessage(id, { role: "bot", kind: "text", text: serverLine(language, "server.reports.sent", { report: id }) });`,
+ `store.appendMessage(id, { role: "bot", kind: "activity", tool: { name: "data_show", ok: true } });`,
+ `store.appendMessage(id, { role: "bot", kind: "text", text: reply.text });`,
+ `const prompt = "Tell the person what you found, in their language.";`,
+ `store.appendMessage(id, { role: "user", kind: "text", text: "A person's own words are theirs." });`,
+ ].join("\n"),
+ })).toEqual([]);
+ });
+
+ it("finds English handed to a line from the packs", () => {
+ expect(scan({ "server/c.ts": `store.appendMessage(id, { role: "bot", kind: "text", text: serverLine(language, "server.reports.notYet", { why: "the server is down", when }) });` }))
+ .toEqual(["server/c.ts line: the server is down"]);
+ });
+});
diff --git a/src/locales/tr.json b/src/locales/tr.json
index ecd63d58c3..08f8539c58 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -69,6 +69,20 @@
"notice.dismiss": "Kalıcı olarak kapat",
"notice.notNow": "Şimdi değil",
"notice.openFailed": "Tarayıcınız açılamadı. Lütfen tekrar deneyin.",
+ "server.reports.sent": "MausBot ekibine gönderildi (rapor {report}). Milind ve Omkar e-postayla alıyor.",
+ "server.reports.sentReply": "MausBot ekibine gönderildi (rapor {report}). Milind ve Omkar e-postayla alıyor ve {contact} adresine yanıt verecek.",
+ "server.reports.sentLater": "Önceki bir deneme başarısız olduktan sonra MausBot ekibine gönderildi (rapor {report}). Milind ve Omkar e-postayla alıyor.",
+ "server.reports.sentLaterReply": "Önceki bir deneme başarısız olduktan sonra MausBot ekibine gönderildi (rapor {report}). Milind ve Omkar e-postayla alıyor ve {contact} adresine yanıt verecek.",
+ "server.reports.notYet": "Henüz gönderilmedi: {why}. Rapor kaydedildi ve {when} kendiliğinden gönderilecek, bu yüzden tekrar göndermenize gerek yok.",
+ "server.reports.why.limited": "MausBot ekibi her uygulamadan saatte yalnızca birkaç rapor alıyor",
+ "server.reports.why.offline": "MausBot ekibinin sunucusuna ulaşılamadı",
+ "server.reports.why.busy": "MausBot ekibinin sunucusu şu anda raporu alamadı",
+ "server.reports.when.minute": "yaklaşık {count} dakika içinde",
+ "server.reports.when.minutes": "yaklaşık {count} dakika içinde",
+ "server.reports.when.soon": "mümkün olan en kısa sürede",
+ "server.reports.refused": "MausBot ekibinin sunucusu bu hata raporunu reddetti, bu yüzden hiçbir şey gönderilmedi: {detail}.",
+ "server.reports.full": "Gönderilmedi: {count} hata raporu zaten MausBot ekibine gönderilmeyi bekliyor. Onlar gönderildikten sonra tekrar @devs yazın.",
+ "server.reports.dropped": "Bu konuşmadaki bir hata raporu bir hafta boyunca MausBot ekibine ulaşamadığı için silindi. Yeni bir rapor göndermek için tekrar @devs yazın.",
"star.title": "{app}'u beğendiniz mi?",
"star.body": "GitHub'da vereceğiniz bir yıldız, daha fazla kişinin onu bulmasına yardımcı olur.",
"star.button": "GitHub'da yıldız ver",
diff --git a/src/locales/uk.json b/src/locales/uk.json
index e343724c30..46e2ce823d 100644
--- a/src/locales/uk.json
+++ b/src/locales/uk.json
@@ -37,6 +37,20 @@
"notice.dismiss": "Приховати назавжди",
"notice.notNow": "Не зараз",
"notice.openFailed": "Не вдалося відкрити браузер. Спробуйте ще раз.",
+ "server.reports.sent": "Надіслано команді MausBot (звіт {report}). Milind і Omkar отримають його електронною поштою.",
+ "server.reports.sentReply": "Надіслано команді MausBot (звіт {report}). Milind і Omkar отримають його електронною поштою і відповідять на {contact}.",
+ "server.reports.sentLater": "Надіслано команді MausBot (звіт {report}) після невдалої попередньої спроби. Milind і Omkar отримають його електронною поштою.",
+ "server.reports.sentLaterReply": "Надіслано команді MausBot (звіт {report}) після невдалої попередньої спроби. Milind і Omkar отримають його електронною поштою і відповідять на {contact}.",
+ "server.reports.notYet": "Ще не надіслано: {why}. Звіт збережено, і він надішлеться сам {when}, тож надсилати його повторно не потрібно.",
+ "server.reports.why.limited": "команда MausBot приймає лише кілька звітів на годину від кожного застосунку",
+ "server.reports.why.offline": "не вдалося зв'язатися із сервером команди MausBot",
+ "server.reports.why.busy": "сервер команди MausBot зараз не зміг його прийняти",
+ "server.reports.when.minute": "приблизно за {count} хвилину",
+ "server.reports.when.minutes": "приблизно за {count} хв",
+ "server.reports.when.soon": "щойно з'явиться можливість",
+ "server.reports.refused": "Сервер команди MausBot відхилив цей звіт про помилку, тому нічого не надіслано: {detail}.",
+ "server.reports.full": "Не надіслано: уже {count} звітів про помилки чекають на відправлення команді MausBot. Напишіть @devs ще раз, коли їх буде надіслано.",
+ "server.reports.dropped": "Звіт про помилку з цієї розмови тиждень не міг дійти до команди MausBot, тому його відкинуто. Напишіть @devs ще раз, щоб надіслати новий.",
"star.title": "Подобається {app}?",
"star.body": "Зірка на GitHub допомагає більшій кількості людей знайти його.",
"star.button": "Поставити зірку на GitHub",
diff --git a/src/locales/vi.json b/src/locales/vi.json
index c36609f63f..a22928b4ee 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -69,6 +69,20 @@
"notice.dismiss": "Bỏ qua vĩnh viễn",
"notice.notNow": "Để sau",
"notice.openFailed": "Không thể mở trình duyệt của bạn. Vui lòng thử lại.",
+ "server.reports.sent": "Đã gửi cho đội MausBot (báo cáo {report}). Milind và Omkar sẽ nhận qua email.",
+ "server.reports.sentReply": "Đã gửi cho đội MausBot (báo cáo {report}). Milind và Omkar sẽ nhận qua email và trả lời tới {contact}.",
+ "server.reports.sentLater": "Đã gửi cho đội MausBot (báo cáo {report}) sau khi một lần thử trước đó không thành công. Milind và Omkar sẽ nhận qua email.",
+ "server.reports.sentLaterReply": "Đã gửi cho đội MausBot (báo cáo {report}) sau khi một lần thử trước đó không thành công. Milind và Omkar sẽ nhận qua email và trả lời tới {contact}.",
+ "server.reports.notYet": "Chưa gửi được: {why}. Báo cáo đã được lưu và sẽ tự gửi {when}, nên bạn không cần gửi lại.",
+ "server.reports.why.limited": "đội MausBot chỉ nhận vài báo cáo mỗi giờ từ mỗi ứng dụng",
+ "server.reports.why.offline": "không kết nối được tới máy chủ của đội MausBot",
+ "server.reports.why.busy": "máy chủ của đội MausBot hiện chưa nhận được",
+ "server.reports.when.minute": "sau khoảng {count} phút",
+ "server.reports.when.minutes": "sau khoảng {count} phút",
+ "server.reports.when.soon": "ngay khi có thể",
+ "server.reports.refused": "Máy chủ của đội MausBot đã từ chối báo cáo lỗi này nên chưa có gì được gửi: {detail}.",
+ "server.reports.full": "Chưa gửi: đã có {count} báo cáo lỗi đang chờ gửi tới đội MausBot. Hãy gõ lại @devs sau khi chúng đã được gửi.",
+ "server.reports.dropped": "Một báo cáo lỗi từ cuộc trò chuyện này không thể tới được đội MausBot trong một tuần nên đã bị bỏ. Hãy gõ lại @devs để gửi báo cáo mới.",
"star.title": "Bạn thích {app} chứ?",
"star.body": "Một ngôi sao trên GitHub sẽ giúp nhiều người biết đến ứng dụng hơn.",
"star.button": "Tặng sao trên GitHub",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 80506cc541..a10b13757d 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -68,6 +68,20 @@
"notice.dismiss": "永久關閉",
"notice.notNow": "暫時不要",
"notice.openFailed": "無法開啟瀏覽器,請再試一次。",
+ "server.reports.sent": "已傳送給 MausBot 團隊(回報 {report})。Milind 和 Omkar 會透過電子郵件收到。",
+ "server.reports.sentReply": "已傳送給 MausBot 團隊(回報 {report})。Milind 和 Omkar 會透過電子郵件收到,並回覆到 {contact}。",
+ "server.reports.sentLater": "先前的一次嘗試沒有成功,現已傳送給 MausBot 團隊(回報 {report})。Milind 和 Omkar 會透過電子郵件收到。",
+ "server.reports.sentLaterReply": "先前的一次嘗試沒有成功,現已傳送給 MausBot 團隊(回報 {report})。Milind 和 Omkar 會透過電子郵件收到,並回覆到 {contact}。",
+ "server.reports.notYet": "尚未傳送:{why}。回報已儲存,將{when}自動傳送,不需要再傳送一次。",
+ "server.reports.why.limited": "MausBot 團隊每小時只接收每個應用程式的少量回報",
+ "server.reports.why.offline": "無法連線到 MausBot 團隊的伺服器",
+ "server.reports.why.busy": "MausBot 團隊的伺服器暫時無法接收",
+ "server.reports.when.minute": "在大約 {count} 分鐘後",
+ "server.reports.when.minutes": "在大約 {count} 分鐘後",
+ "server.reports.when.soon": "盡快",
+ "server.reports.refused": "MausBot 團隊的伺服器拒絕了這份錯誤回報,因此沒有傳送任何內容:{detail}。",
+ "server.reports.full": "未傳送:已有 {count} 份錯誤回報正在等待傳送給 MausBot 團隊。等它們傳送後,再輸入一次 @devs。",
+ "server.reports.dropped": "此對話中的一份錯誤回報一週內都無法送達 MausBot 團隊,因此已被捨棄。若要傳送新的回報,請再輸入一次 @devs。",
"star.title": "喜歡 {app} 嗎?",
"star.body": "在 GitHub 上給顆星,能幫助更多人找到它。",
"star.button": "在 GitHub 上給星",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 07fce4257f..31a8a2610b 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -58,6 +58,20 @@
"notice.dismiss": "永久关闭",
"notice.notNow": "暂时不用",
"notice.openFailed": "无法打开浏览器,请重试。",
+ "server.reports.sent": "已发送给 MausBot 团队(报告 {report})。Milind 和 Omkar 会通过邮件收到。",
+ "server.reports.sentReply": "已发送给 MausBot 团队(报告 {report})。Milind 和 Omkar 会通过邮件收到,并回复到 {contact}。",
+ "server.reports.sentLater": "之前的一次尝试没有成功,现已发送给 MausBot 团队(报告 {report})。Milind 和 Omkar 会通过邮件收到。",
+ "server.reports.sentLaterReply": "之前的一次尝试没有成功,现已发送给 MausBot 团队(报告 {report})。Milind 和 Omkar 会通过邮件收到,并回复到 {contact}。",
+ "server.reports.notYet": "尚未发送:{why}。报告已保存,将{when}自动发送,无需再次发送。",
+ "server.reports.why.limited": "MausBot 团队每小时只接收每个应用的少量报告",
+ "server.reports.why.offline": "无法连接到 MausBot 团队的服务器",
+ "server.reports.why.busy": "MausBot 团队的服务器暂时无法接收",
+ "server.reports.when.minute": "在大约 {count} 分钟后",
+ "server.reports.when.minutes": "在大约 {count} 分钟后",
+ "server.reports.when.soon": "尽快",
+ "server.reports.refused": "MausBot 团队的服务器拒绝了这份错误报告,因此没有发送任何内容:{detail}。",
+ "server.reports.full": "未发送:已有 {count} 份错误报告在等待发送给 MausBot 团队。等它们发送后,再输入一次 @devs。",
+ "server.reports.dropped": "此对话中的一份错误报告一周内都无法送达 MausBot 团队,因此已被丢弃。如需发送新的报告,请再输入一次 @devs。",
"star.title": "喜欢 {app} 吗?",
"star.body": "在 GitHub 上点个星,能帮助更多人发现它。",
"star.button": "在 GitHub 上点星",