Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Announcement cards from a file on main, without a release (#5345)
Milind Soni2913a2ebb336
diff --git a/.gitattributes b/.gitattributesindex 1337bee46f..01597a9a35 100644--- a/.gitattributes+++ b/.gitattributes@@ -19,6 +19,10 @@ third_party/browser/** text eol=lf# on Windows fails both for a reason that has nothing to do with the evals.evals/live/judge/prompts/** text eol=lfevals/golden/**/*.json text eol=lf+# The announcements file and its JSON Schema: scripts/check-announcements.mjs compares the committed schema with the one+# it generates (LF), and installs read the file as main serves it. The comparison ignores line endings too; this keeps a+# Windows checkout identical to what installs download.+announcements/*.json text eol=lf# The bundled model catalog is compared byte for byte with what# scripts/build-model-catalog.mjs writes (LF), and its licence text with the# LICENSE files, in scripts/build-model-catalog.test.mjs and by --check.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a5ae3f722e..cbdfc4c1aa 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -107,6 +107,11 @@ jobs:run: node scripts/check-model-manifest.mjs --against "$MANIFEST_BASE"- run: pnpm check:contrast- run: pnpm lint+ - name: Validate the announcements file+ # Installs download it from main within the hour (docs/announcements.md), so a bad edit must not land.+ env:+ ANNOUNCEMENTS_BASE: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.event.before }}+ run: node scripts/check-announcements.mjs --against "$ANNOUNCEMENTS_BASE"- name: Source guards# The tests that only read the source: seconds here, and they stay in the shards. On Nov 3-4 2026 one of them was# red on main for 11 hours, and each PR heard about it after about 70 minutes, once its shards had found a runner.diff --git a/SECURITY.md b/SECURITY.mdindex da53a03f0f..3c8dcf019b 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -39,5 +39,9 @@ You'll get a response as soon as possible, normally within a few days.access**. Full access is a standing user decision to approve provider permission requests; it mustnever answer questions or silently broaden product-level confirmations such as credentials,routines, skills, or peer communication.+- The announcements file (`announcements/announcements.json`, downloaded from `main`; `docs/announcements.md`) is+ untrusted input to every install. A card that renders markup, runs anything, navigates the app's own window, opens a+ non-https address, loads a picture from outside the repository's `announcements/` folder, or makes the download carry+ anything identifying the install or the person is a vulnerability.- Spawning must never route user-influenced strings through a shell. Report any `shell: true` /`cmd.exe` string-building you find.diff --git a/announcements/announcements.json b/announcements/announcements.jsonnew file mode 100644index 0000000000..df3016ea3d--- /dev/null+++ b/announcements/announcements.json@@ -0,0 +1,6 @@+{+ "$schema": "./announcements.schema.json",+ "version": 1,+ "updatedAt": "2026-11-11T00:00:00Z",+ "cards": []+}diff --git a/announcements/announcements.schema.json b/announcements/announcements.schema.jsonnew file mode 100644index 0000000000..08e808de66--- /dev/null+++ b/announcements/announcements.schema.json@@ -0,0 +1,528 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "$schema": {+ "type": "string",+ "maxLength": 200+ },+ "version": {+ "type": "number",+ "const": 1+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "cards": {+ "maxItems": 20,+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "minLength": 3,+ "maxLength": 40,+ "pattern": "^[a-z0-9][a-z0-9-]*$"+ },+ "kind": {+ "type": "string",+ "enum": [+ "sponsor",+ "product",+ "tip"+ ]+ },+ "label": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 1,+ "maxLength": 16+ },+ {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "enum": [+ "en",+ "de",+ "es",+ "fr",+ "hi",+ "ja",+ "pt-br",+ "zh",+ "zh-tw",+ "uk",+ "vi",+ "tr",+ "pl",+ "ru",+ "it",+ "ko"+ ]+ },+ "additionalProperties": {+ "type": "string",+ "minLength": 1,+ "maxLength": 16+ }+ }+ ]+ },+ "title": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 1,+ "maxLength": 60+ },+ {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "enum": [+ "en",+ "de",+ "es",+ "fr",+ "hi",+ "ja",+ "pt-br",+ "zh",+ "zh-tw",+ "uk",+ "vi",+ "tr",+ "pl",+ "ru",+ "it",+ "ko"+ ]+ },+ "additionalProperties": {+ "type": "string",+ "minLength": 1,+ "maxLength": 60+ }+ }+ ]+ },+ "body": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 1,+ "maxLength": 240+ },+ {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "enum": [+ "en",+ "de",+ "es",+ "fr",+ "hi",+ "ja",+ "pt-br",+ "zh",+ "zh-tw",+ "uk",+ "vi",+ "tr",+ "pl",+ "ru",+ "it",+ "ko"+ ]+ },+ "additionalProperties": {+ "type": "string",+ "minLength": 1,+ "maxLength": 240+ }+ }+ ]+ },+ "image": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "url": {+ "type": "string",+ "maxLength": 500+ },+ "alt": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 1,+ "maxLength": 120+ },+ {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "enum": [+ "en",+ "de",+ "es",+ "fr",+ "hi",+ "ja",+ "pt-br",+ "zh",+ "zh-tw",+ "uk",+ "vi",+ "tr",+ "pl",+ "ru",+ "it",+ "ko"+ ]+ },+ "additionalProperties": {+ "type": "string",+ "minLength": 1,+ "maxLength": 120+ }+ }+ ]+ }+ },+ "required": [+ "url"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "mark": {+ "type": "string",+ "enum": [+ "claude",+ "codex",+ "grok",+ "kimi",+ "modelgo",+ "greenference",+ "deepseek",+ "copilot",+ "kiro"+ ]+ }+ },+ "required": [+ "mark"+ ],+ "additionalProperties": false+ }+ ]+ },+ "primary": {+ "type": "object",+ "properties": {+ "label": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 1,+ "maxLength": 24+ },+ {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "enum": [+ "en",+ "de",+ "es",+ "fr",+ "hi",+ "ja",+ "pt-br",+ "zh",+ "zh-tw",+ "uk",+ "vi",+ "tr",+ "pl",+ "ru",+ "it",+ "ko"+ ]+ },+ "additionalProperties": {+ "type": "string",+ "minLength": 1,+ "maxLength": 24+ }+ }+ ]+ },+ "action": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "open_url": {+ "type": "string",+ "maxLength": 500+ }+ },+ "required": [+ "open_url"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "open": {+ "type": "string",+ "enum": [+ "api_keys",+ "ai_engines",+ "connected_apps",+ "new_bot",+ "my_cloud"+ ]+ }+ },+ "required": [+ "open"+ ],+ "additionalProperties": false+ }+ ]+ }+ },+ "required": [+ "label",+ "action"+ ],+ "additionalProperties": false+ },+ "secondary": {+ "type": "object",+ "properties": {+ "label": {+ "anyOf": [+ {+ "type": "string",+ "minLength": 1,+ "maxLength": 24+ },+ {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "enum": [+ "en",+ "de",+ "es",+ "fr",+ "hi",+ "ja",+ "pt-br",+ "zh",+ "zh-tw",+ "uk",+ "vi",+ "tr",+ "pl",+ "ru",+ "it",+ "ko"+ ]+ },+ "additionalProperties": {+ "type": "string",+ "minLength": 1,+ "maxLength": 24+ }+ }+ ]+ },+ "action": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "open_url": {+ "type": "string",+ "maxLength": 500+ }+ },+ "required": [+ "open_url"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "open": {+ "type": "string",+ "enum": [+ "api_keys",+ "ai_engines",+ "connected_apps",+ "new_bot",+ "my_cloud"+ ]+ }+ },+ "required": [+ "open"+ ],+ "additionalProperties": false+ }+ ]+ }+ },+ "required": [+ "label",+ "action"+ ],+ "additionalProperties": false+ },+ "starts": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "ends": {+ "type": "string",+ "format": "date-time",+ "pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "audience": {+ "type": "object",+ "properties": {+ "minVersion": {+ "type": "string",+ "pattern": "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}$"+ },+ "maxVersion": {+ "type": "string",+ "pattern": "^\\d{1,6}\\.\\d{1,6}\\.\\d{1,6}$"+ },+ "platforms": {+ "minItems": 1,+ "maxItems": 5,+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "mac",+ "windows",+ "linux",+ "ios",+ "android"+ ]+ }+ },+ "surfaces": {+ "minItems": 1,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "desktop",+ "cloud",+ "server"+ ]+ }+ },+ "plans": {+ "minItems": 1,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "none",+ "cloud",+ "team"+ ]+ }+ },+ "people": {+ "type": "string",+ "enum": [+ "new",+ "existing"+ ]+ },+ "languages": {+ "minItems": 1,+ "maxItems": 16,+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "en",+ "de",+ "es",+ "fr",+ "hi",+ "ja",+ "pt-br",+ "zh",+ "zh-tw",+ "uk",+ "vi",+ "tr",+ "pl",+ "ru",+ "it",+ "ko"+ ]+ }+ },+ "when": {+ "minItems": 1,+ "maxItems": 3,+ "type": "array",+ "items": {+ "type": "string",+ "enum": [+ "no_api_key",+ "one_bot_only",+ "no_routine"+ ]+ }+ }+ },+ "additionalProperties": false+ }+ },+ "required": [+ "id",+ "kind",+ "title",+ "body",+ "primary",+ "ends"+ ],+ "additionalProperties": false+ }+ }+ },+ "required": [+ "version",+ "updatedAt",+ "cards"+ ],+ "additionalProperties": false+}diff --git a/apps/docs/content/docs/security/analytics.mdx b/apps/docs/content/docs/security/analytics.mdxindex 12148feb3a..7464bb2812 100644--- a/apps/docs/content/docs/security/analytics.mdx+++ b/apps/docs/content/docs/security/analytics.mdx@@ -43,7 +43,8 @@ on there lasts until that page reloads. In a browser, switch it off on each serv- URLs, hosts and addresses. PostHog's own `$current_url`, `$host`, `$pathname`, `$referrer`, `$referring_domain`,campaign parameters (`utm_*`, `gclid` and the like) and their `$initial_*` and `$session_entry_*` copies are removedbefore an event leaves the app.-- File paths, and ids of any kind: bot, room, conversation, instance, account or computer.+- File paths, and ids of any kind: bot, room, conversation, instance, account or computer. (An `announcement` event+ names the card, by the id the public announcements file gives it, never anything of yours.)- Instructions, prompts, message content, model output and error messages.## Allowed values@@ -166,6 +167,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin| `product_hunt_card` | You act on the Product Hunt card | `action`: `upvote`, `not_now`, `close` || `boat_offer` | Boat's credit offer: its one-time card is shown or you act on it, or you act on it on the Boat card in Settings → API keys | `action`: `shown` (the card only), `get_boat`, `claim` (the drafted email to Boat opened), `not_now`, `close`; `place`: `card`, `settings` || `modelgo_offer` | ModelGo, a sponsor: its one-time popup or its first-run option is shown, or you act on the popup, the first-run option or the ModelGo row in Settings → API keys | `action`: `shown` (the popup and the first-run option), `get_key` (ModelGo's site opened), `add_key` (Settings: a key was saved there; first run: you opened the ModelGo row to add one; never the popup), `not_now`, `close` (the popup only); `place`: `popup`, `onboarding`, `settings` |+| `announcement` | A card from the project's public announcements file (sponsor offers, product news, tips; [Announcements](https://github.com/milind-soni/OpenMausBot/blob/main/docs/announcements.md)) is shown, or you act on it | `id`: the card's own id from that file, the same for everyone who sees the card; `kind`: `sponsor`, `product`, `tip`; `action`: `shown`, `primary` (its main button), `secondary` (its second button), `close` (Not now, the X or Escape) || `simple_mode_prompt` | The Simple mode popup, shown once in each browser after an update when nothing else is on screen, is shown, its Simple mode switch is flipped, or it is closed (Done, the X, Escape or a click outside) | `action`: `shown`, `toggled`, `closed`; `mode`: `simple`, `advanced`, the mode it was shown or closed in, or the one a flip turned on || `new_look_notice` | The notice that Simple is now the only look, shown once in each browser that was on Advanced mode, when nothing else is on screen, is shown or closed (Done, the X, Escape or a click outside) | `action`: `shown`, `closed` || `advanced_back_notice` | The notice that Advanced mode is back, shown once in each browser that was on Advanced mode before Simple became the only look and is put back on it, when nothing else is on screen, is shown or closed (Done, the X, Escape or a click outside) | `action`: `shown`, `closed` |diff --git a/apps/docs/content/docs/security/index.mdx b/apps/docs/content/docs/security/index.mdxindex 3a95421f54..3103defd7b 100644--- a/apps/docs/content/docs/security/index.mdx+++ b/apps/docs/content/docs/security/index.mdx@@ -15,6 +15,7 @@ MausBot is designed around a local owner, explicit capabilities, and narrow proc- Local computer control is a separate opt-in and per-bot selection.- Paired phones use a default-deny API allowlist and per-device bearer tokens.- Cloud and VPS backends are validated before reuse.+- The app downloads the project's public announcements file from GitHub, at most hourly and with nothing of yours in it, and may show one of its cards (product news, a tip, a sponsor's offer) once per person. The cards are plain text with fixed button actions, never pages or code. `OMB_DISABLE_ANNOUNCEMENTS=1` turns it off on a server.- Usage analytics are optional. In the desktop app, the switch in Settings turns them off, and a server's page its window shows starts with them off too (once that server runs the same version); in a browser, each server's page has its own switch. They send counts and fixed words, never keys, names, addresses or content; [Usage analytics](/docs/security/analytics) lists every event.## Your responsibilitydiff --git a/docs/analytics.md b/docs/analytics.mdindex 397889a388..2b9ead8fa1 100644--- a/docs/analytics.md+++ b/docs/analytics.md@@ -39,7 +39,8 @@ on there lasts until that page reloads. In a browser, switch it off on each serv- URLs, hosts and addresses. PostHog's own `$current_url`, `$host`, `$pathname`, `$referrer`, `$referring_domain`,campaign parameters (`utm_*`, `gclid` and the like) and their `$initial_*` and `$session_entry_*` copies are removedbefore an event leaves the app.-- File paths, and ids of any kind: bot, room, conversation, instance, account or computer.+- File paths, and ids of any kind: bot, room, conversation, instance, account or computer. (An `announcement` event+ names the card, by the id the public announcements file gives it, never anything of yours.)- Instructions, prompts, message content, model output and error messages.## Allowed values@@ -162,6 +163,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin| `product_hunt_card` | You act on the Product Hunt card | `action`: `upvote`, `not_now`, `close` || `boat_offer` | Boat's credit offer: its one-time card is shown or you act on it, or you act on it on the Boat card in Settings → API keys | `action`: `shown` (the card only), `get_boat`, `claim` (the drafted email to Boat opened), `not_now`, `close`; `place`: `card`, `settings` || `modelgo_offer` | ModelGo, a sponsor: its one-time popup or its first-run option is shown, or you act on the popup, the first-run option or the ModelGo row in Settings → API keys | `action`: `shown` (the popup and the first-run option), `get_key` (ModelGo's site opened), `add_key` (Settings: a key was saved there; first run: you opened the ModelGo row to add one; never the popup), `not_now`, `close` (the popup only); `place`: `popup`, `onboarding`, `settings` |+| `announcement` | A card from the project's public announcements file (sponsor offers, product news, tips; [Announcements](https://github.com/milind-soni/OpenMausBot/blob/main/docs/announcements.md)) is shown, or you act on it | `id`: the card's own id from that file, the same for everyone who sees the card; `kind`: `sponsor`, `product`, `tip`; `action`: `shown`, `primary` (its main button), `secondary` (its second button), `close` (Not now, the X or Escape) || `simple_mode_prompt` | The Simple mode popup, shown once in each browser after an update when nothing else is on screen, is shown, its Simple mode switch is flipped, or it is closed (Done, the X, Escape or a click outside) | `action`: `shown`, `toggled`, `closed`; `mode`: `simple`, `advanced`, the mode it was shown or closed in, or the one a flip turned on || `new_look_notice` | The notice that Simple is now the only look, shown once in each browser that was on Advanced mode, when nothing else is on screen, is shown or closed (Done, the X, Escape or a click outside) | `action`: `shown`, `closed` || `advanced_back_notice` | The notice that Advanced mode is back, shown once in each browser that was on Advanced mode before Simple became the only look and is put back on it, when nothing else is on screen, is shown or closed (Done, the X, Escape or a click outside) | `action`: `shown`, `closed` |diff --git a/docs/announcements.md b/docs/announcements.mdnew file mode 100644index 0000000000..fb134c77ac--- /dev/null+++ b/docs/announcements.md@@ -0,0 +1,210 @@+# Announcements: cards without a release++The app can show a card in its corner (a sponsor's offer, product news, a tip) that nobody shipped in a release. The cards+live in one file in this repository, [`announcements/announcements.json`](../announcements/announcements.json). Merge a+change to it on `main` and every install that runs this version or later picks it up within about an hour.++## How it works++- **One file on `main`.** The app's server downloads+ `https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/announcements/announcements.json` when a page of the app+ asks for the cards: at launch, then about hourly while the app is in use. Whoever can merge to `main` can publish a card;+ there is no other sign-in and no backend.+- **The server fetches, the page decides.** The desktop app's own server, a MausBot Cloud and a self-hosted server all+ download the file the same way (`server/announcements/feed.ts`) and hand the cards to their pages at+ `GET /api/announcements`. Each page then decides, from what it already knows, whether a card is for the person looking+ at it (`src/lib/announcements.ts`). Nothing about the person goes anywhere.+- **The same fetch as the model manifest.** Like `server/model-manifest/`, the server keeps a copy bundled with the+ release, a cache of the last good download on disk (`providers/announcements/` in the data folder, which backups and+ Move to Cloud leave out), and downloads at most once an hour (every five minutes after a failure). A download that+ fails, is slow (ten seconds at most), is larger than 64 KB, is not JSON or does not validate is dropped and the last+ good copy is kept. A page's first ask waits at most three seconds for the first download; nothing else ever waits for+ it, and nothing is shown when it fails. The two should share one helper once both are on `main`.+- **Cards, not pages.** The file carries words, a picture's address and one of a few button actions. The app draws the+ card with its own notice card (`src/components/AnnouncementCard.tsx`); nothing in the file is read as HTML or run.++### What the app sends++One plain GET of that public file, from the server: no cookie, no account, no install id, no version, no query string.+GitHub sees the server's IP address, as for any download. When a card has a picture, the person's browser loads it from+the same place, with no cookie and no referrer. Clicking a card's link opens its address exactly as the file has it,+in the system browser on the desktop (a new tab with no opener or referrer in a browser), with nothing added. With+analytics on, the app counts the card (see [Counting](#counting)).++Older versions of the app know nothing of this file and never download it.++## Publishing a card++1. Edit `announcements/announcements.json` on a branch: add a card to `cards` (the first card in the list that is for a+ person is the one they see, so order them by priority) and move `updatedAt` to now. Editors that read JSON Schema+ check the file as you type, from `announcements/announcements.schema.json`.+2. Check it: `node scripts/check-announcements.mjs` (add `--against origin/main` to also check `updatedAt` moved+ forward). CI runs the same check on every pull request and fails on any problem, so a bad edit cannot merge.+3. For a picture, add the file under `announcements/` (for example `announcements/images/phone-app.png`, PNG, JPEG or+ WebP, at most 200 KB, about 600 × 240 pixels) and point `image.url` at its raw address on `main`. It must be merged+ for the picture to load, so merge it with the card or before.+4. Open a pull request and merge it. Installs show the card within about an hour (GitHub's raw cache adds up to five+ minutes), each person once.++**To pull a card back:** delete it from the file (or set its `ends` to now), move `updatedAt` forward and merge. Within+about an hour no install shows it: a page that has it on screen drops it the next time it asks for the cards. Never reuse a card's `id` for a different card: people who saw the old one would+not see the new one, and a card brought back with its old id may reach people who closed it before.++**To change a live card**, edit it in place and keep its `id`: people who closed it will not see it again. A new `id`+shows it again to everyone.++## The format++```json+{+ "$schema": "./announcements.schema.json",+ "version": 1,+ "updatedAt": "2026-12-01T09:00:00Z",+ "cards": [+ {+ "id": "tip-first-api-key",+ "kind": "tip",+ "label": { "en": "Tip", "de": "Tipp" },+ "title": { "en": "Your bots can use any AI provider", "de": "Deine Bots können jeden KI-Anbieter nutzen" },+ "body": { "en": "Paste an API key once and every bot here can use it. You can change which model a bot uses at any time.",+ "de": "Füge einmal einen API-Schlüssel ein, und jeder Bot hier kann ihn nutzen. Das Modell eines Bots kannst du jederzeit ändern." },+ "primary": { "label": { "en": "Open API keys", "de": "API-Schlüssel öffnen" }, "action": { "open": "api_keys" } },+ "ends": "2027-02-01T00:00:00Z",+ "audience": { "people": "new", "when": ["no_api_key"], "surfaces": ["desktop", "cloud"] }+ },+ {+ "id": "sponsor-acme-credit-2026-12",+ "kind": "sponsor",+ "label": "Sponsor",+ "title": "Acme Inference: $5 of free credit",+ "body": "Acme Inference sponsors MausBot. New accounts get $5 of credit for any model they serve.",+ "primary": { "label": "Get a key", "action": { "open_url": "https://example.com/acme?utm_source=openmausbot&utm_medium=sponsorship" } },+ "secondary": { "label": "Add a key", "action": { "open": "api_keys" } },+ "starts": "2026-12-01T00:00:00Z",+ "ends": "2026-12-15T00:00:00Z",+ "audience": { "minVersion": "0.1.153", "plans": ["none", "cloud"] }+ }+ ]+}+```++(The tests read these two from `scripts/testing/fixtures/announcements.example.json`.)++### The file++| Field | Required | What it is |+| --- | --- | --- |+| `version` | yes | `1`. A file with any other version is ignored whole by this app. |+| `updatedAt` | yes | When the file last changed (ISO 8601 with a time zone). Installs keep the copy with the newest one, so a stale cached copy can never bring back a removed card. CI refuses an edit that does not move it forward. |+| `cards` | yes | At most 20 cards, in priority order. |+| `$schema` | no | `"./announcements.schema.json"`, for editors. |++### A card++| Field | Required | What it is |+| --- | --- | --- |+| `id` | yes | Stable and unique: 3–40 lowercase letters, digits and dashes, e.g. `phone-app-2026-12`. Each person sees each id once. |+| `kind` | yes | `sponsor`, `product` or `tip`. An app that does not know a kind skips the card. |+| `label` | sponsor: yes | A short word above the body, e.g. `Sponsor`, `New`, `Tip` (16 characters). A sponsor's card must say it is one. |+| `title` | yes | 60 characters. |+| `body` | yes | 240 characters, at most 3 lines (`\n` breaks a line). |+| `image` | no | Either `{ "url": "<raw address under announcements/ on main>", "alt": "<text>" }` (PNG, JPEG or WebP, shown the card's width and at most 120 pixels high), or `{ "mark": "<name>" }`, a built-in mark beside the title: `claude`, `codex`, `grok`, `kimi`, `modelgo`, `greenference`, `deepseek`, `copilot`, `kiro`. Without one, the card shows its kind's icon. An app that cannot read the picture shows the card without it. |+| `primary` | yes | The main button: `{ "label": <text, 24 characters>, "action": <action> }`. |+| `secondary` | no | A second, quieter button, in the same shape. Without one, the card has **Not now**. |+| `starts` | no | When it may first show (ISO 8601). |+| `ends` | yes | When it stops showing. After `starts`, at most 180 days after the day it merges. A card without `ends` is never shown. |+| `audience` | no | Who it is for; without it, everyone. |++**Text** is plain text: either one string (English), or one per language with English among them:+`{ "en": "Hello", "de": "Hallo", "pt-br": "Olá" }`. The app shows the person's language, else its language without the+region, else English. Languages: `en`, `de`, `es`, `fr`, `hi`, `ja`, `pt-br`, `zh`, `zh-tw`, `uk`, `vi`, `tr`, `pl`, `ru`,+`it`, `ko`. Nothing is read as markup: `<b>` shows as `<b>`, and there is no bold or link inside the body. Control+characters and characters that reorder or hide text are refused.++**An action** is exactly one of:++- `{ "open_url": "https://…" }`: opens the page outside the app (https only, no user name or password in it), with+ nothing added to the address. Put any campaign parameters in the address yourself.+- `{ "open": "<place>" }`: opens one of the app's own places: `api_keys` (Settings → API keys), `ai_engines` (Settings →+ AI engines), `connected_apps` (Connected apps), `new_bot` (makes a new bot, as the sidebar's New bot does) or `my_cloud`+ (Settings → MausBot Cloud). `api_keys`, `ai_engines` and `new_bot` change a place's settings, so a card with one of them+ is not shown to someone who cannot (a Team Cloud's members).++Anything else makes the card invalid.++**The audience** (every key given must match; a key or value this version does not know means the card does not match,+so a card written for a newer app never reaches an older one by accident):++| Key | Values | Matches |+| --- | --- | --- |+| `minVersion`, `maxVersion` | `"0.1.153"` | The page's app version, inclusive. A Cloud's page has its Cloud's version. |+| `platforms` | `mac`, `windows`, `linux`, `ios`, `android` | The device the page is open on. |+| `surfaces` | `desktop`, `cloud`, `server` | The desktop app's own page; a MausBot Cloud's page (in a browser or in the desktop's window); any other server's page (self-hosted, or the app in a browser). |+| `plans` | `none`, `cloud`, `team` | `none`: no Cloud plan of one's own (signed out, or a free account); `cloud`: a Cloud of one's own, or its page; `team`: a Team Cloud's page. Known on the desktop app's page and on a Cloud's page; a card with `plans` never shows on another server's page. |+| `people` | `new`, `existing` | `existing`: a bot here has answered someone before this launch; `new`: none has. |+| `languages` | the language codes above | The app's language, or its language without the region. |+| `when` | `no_api_key`, `one_bot_only`, `no_routine` | Every condition listed holds: no AI provider API key saved here; only one bot shown; no routine. |++To add a value or a condition, add it to `shared/announcements.ts` and its checks; an older app keeps ignoring cards+that use it.++## The rules the app keeps, whatever the file says++- **Once per person per `id`.** The app remembers a card someone closed or used the way it remembers the built-in sponsor card (`MODELGO_OFFER_NOTICE`):+ in the browser, in the desktop app's own record for every page its window shows (My Cloud's included), and in the+ workspace's record. On a Team Cloud the workspace record is the whole team's, so there it uses only the first two.+- **One card on screen, through the notice queue.** A remote card comes after everything else in+ `src/lib/notices.ts`'s queue that is due: the Grok Bot move, the What's new popup, the product-updates question, bots+ in two places, the Cloud trial and account notices, and the built-in sponsor and partner offers; only the GitHub star comes+ after it. Like the built-in sponsor card it may also follow the launch's first notice in the same launch, once that+ notice is closed, after the product-updates question and the built-in sponsor card, so it reaches people on their next+ launch rather than some later one. It never replaces a card still on screen, and never goes ahead of a notice someone+ has to act on (the Grok Bot move, a trial's notice, the account's card), even one left for a later launch: it waits for+ that launch and follows it there.+- **At most one remote card a launch**, and **at most one `sponsor` card in any 7 days** per person (counted from the day+ one was shown).+- **Never** in the launch whose welcome just finished, over MausBot's first-launch card, during a live call, or while a+ move to My Cloud is under way (the built-in sponsor card's exclusions).+- **Never on a branded build** (`brandStatus().source === "file"`), any kind, as the What's new popup.+- **Sponsor cards** also skip a desktop whose organization's policy limits the AI providers (company models only, or a+ list of allowed engines), and a Team Cloud's members who are not its owner or an admin+ (`SPONSOR_CARDS_FOR_TEAM_MEMBERS` in `src/lib/announcements.ts`, off).+- **Invalid is ignored.** A card that fails validation, has no `ends` or is past it is skipped; a file that fails as a+ whole is ignored and the last good copy kept. At most 20 cards and 64 KB are read.++## Turning it off++- **`OMB_DISABLE_ANNOUNCEMENTS=1`** in the server's environment stops the download and every remote card on that server's+ pages, the bundled ones included. For a self-hosted server or an open-source build that should never show them. The+ desktop app's own server inherits the app's environment, so it holds there when the app is started with it set.+- **No in-app switch governs these cards.** The app has no setting for promotional popups: the product-updates question is+ about email, and the usage-analytics switch only stops the counting. A person closes a card with Not now or the X, and+ never sees that card again.++## Counting++With usage analytics on, and only then (the same switch as every other event), each card sends one `announcement` event+per step: `{ id, kind, action }`, `action` being `shown`, `primary`, `secondary` or `close` (the X, Escape or Not now).+The `id` is the card's own id from this public file, the same for everyone. See [Usage analytics](analytics.md).++## Tests and previews++Tests never download the live file: `server/testing/setup.ts` and the verification server+(`scripts/control-omb.ts`, which the renderer previews and UI tests run on) set `OMB_DISABLE_ANNOUNCEMENTS=1`, so their+pages get no cards whatever `main` holds. The server's tests hand the store a fake fetch.++## Moving the built-in sponsor card into the feed later++The built-in sponsor card (`MODELGO_OFFER_NOTICE`) stays built in. To move it: publish a `sponsor` card with the same+words, its mark and `MODELGO_URL` as its `open_url`; release a version whose app treats the old seen id as the card's+(mark `announcement:<id>` seen when `modelgo-offer-2026-11` is), then remove the built-in card. Until every install runs+that version, older ones keep showing the built-in card.++## Design notes++- The fetch runs on the server, not in the page: a Cloud in a browser and the desktop app then behave the same, the page+ needs no new network permission, and many pages share one download an hour.+- The schema is `shared/announcements.ts` (zod). The JSON Schema beside the file is generated from it+ (`node scripts/check-announcements.mjs --write-schema`), and CI fails when the two differ. An install reads the file+ leniently (unknown fields are dropped, an unknown audience key is kept so the card matches no one); CI reads it+ strictly, where an unknown field is a typo.diff --git a/docs/ci.md b/docs/ci.mdindex 2d9ab54723..0be817086c 100644--- a/docs/ci.md+++ b/docs/ci.md@@ -1,8 +1,10 @@# CI job selectionEvery PR still runs the workflow, its `static` job and the `CI` gate: locale-validation, lint, the CI-selection tests, the verification-documentation-checks and the source guards always run. Selection never skips the entire+validation, lint, the announcements file's check+(`scripts/check-announcements.mjs`, which installs download from main within+the hour, so it fails on any invalid edit), the CI-selection tests, the+verification-documentation checks and the source guards always run. Selection never skips the entireworkflow. The source guards are the tests that only read the source (thevocabulary and locale checks, the size and route ratchets, and the like): theytake seconds, and they run in `static` as well as in the shards, so a change@@ -22,6 +24,7 @@ too) into areas, and runs only the jobs some area can affect:| Windows computer control | the `electron/` modules that start computer control and lend a PC's screen: `cua`, `cua-failure`, `cua-connection`, `capabilities`, `screen-status`, `shared-cua-connection`, `shared-computer-access`, `lent-screen-tools`, `lent-screen-failures`, `paced-typing` | the same as server, and Windows CUA || desktop | the rest of `electron/`, `build/`, `electron-builder.yml`, `index.html` | the same as server || control plane | `cloudflare/control-plane/` | the control-plane job |+| announcements | `announcements/`: the cards file, its JSON Schema and pictures | nothing beyond `static`, which validates them || everything | anything else: `.github/` workflows, `package.json`, the lockfile and workspace, tsconfig, vite and vitest config, `third_party/`, `scripts/` code, unknown paths | every job |`static` also validates `server/model-manifest/model-manifest.json` with `scripts/check-model-manifest.mjs`: installsdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 4abd67a4b8..0c0ae0d930 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -984,6 +984,14 @@ On the Workspaces screen, creating a client workspace shows the same kind oflink for that workspace's admin, so a client gets one address, one workspaceand one link.+## Announcements from the project++When someone opens the app, the server downloads the project's public announcements file from GitHub+(`raw.githubusercontent.com`, at most once an hour, a plain GET with nothing of yours in it) and its pages may show one of+its cards in the corner: product news, a tip, or a sponsor's offer, each once per person+([docs/announcements.md](announcements.md)). Set `OMB_DISABLE_ANNOUNCEMENTS=1` in the server's environment to never+download it and never show those cards.+## Attachment storageFiles people attach, and pictures a bot shows inline, live in thediff --git a/electron/desktop-prefs.d.mts b/electron/desktop-prefs.d.mtsindex 7d7bbd63a8..7ed68a617e 100644--- a/electron/desktop-prefs.d.mts+++ b/electron/desktop-prefs.d.mts@@ -32,6 +32,8 @@ export interface DesktopLanguageBridge {}export interface DesktopPrefs {seen(): string[];+ /** One of DESKTOP_NOTICES, or an announcement card's mark (`announcement:<id>`, `announcement-sponsor:<day>`); anything+ * else is not kept. */markSeen(id: string): void;analytics(): boolean | null;setAnalytics(enabled: boolean): void;diff --git a/electron/desktop-prefs.mjs b/electron/desktop-prefs.mjsindex 3ceadf5a20..86446a6ab7 100644--- a/electron/desktop-prefs.mjs+++ b/electron/desktop-prefs.mjs@@ -14,6 +14,16 @@ export { DESKTOP_PORTS } from "./desktop-ports.mjs";/** The only notices a page may record, so no page can write anything else into the file. */export const DESKTOP_NOTICES = Object.freeze(["whats-new-2026-11", "boat-credit-2026-11", "grok-move-2026-11", "modelgo-offer-2026-11"]);const WHATS_NEW = DESKTOP_NOTICES[0];+/** A card from the project's announcements file someone closed (src/lib/announcements.ts), and the last day a sponsor's+ * card was shown: kept beside the fixed notices, the newest few only. */+const ANNOUNCEMENT_SEEN = /^announcement:[a-z0-9][a-z0-9-]{2,39}$/;+const ANNOUNCEMENT_SPONSOR_DAY = /^announcement-sponsor:\d{4}-\d{2}-\d{2}$/;+const MAX_ANNOUNCEMENTS_SEEN = 40;+const keptAnnouncements = list => {+ const marks = list.filter(id => typeof id === "string" && ANNOUNCEMENT_SEEN.test(id));+ const days = list.filter(id => typeof id === "string" && ANNOUNCEMENT_SPONSOR_DAY.test(id)).sort();+ return [...new Set(marks)].slice(-MAX_ANNOUNCEMENTS_SEEN).concat(days.slice(-1));+};/** A locale code such as "de" or "pt-br", or "" for following the system. */const LANGUAGE = /^(?:[a-z]{2,3}(?:-[a-z0-9]{2,8}){0,2})?$/i;const isLanguage = value => typeof value === "string" && value.length <= 24 && LANGUAGE.test(value);@@ -43,7 +53,7 @@ const parseChat = value => value && typeof value === "object" && typeof value.bofunction parse(raw) {const record = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};- const seen = Array.isArray(record.seen) ? DESKTOP_NOTICES.filter(id => record.seen.includes(id)) : [];+ const seen = Array.isArray(record.seen) ? [...DESKTOP_NOTICES.filter(id => record.seen.includes(id)), ...keptAnnouncements(record.seen)] : [];const updatesConsent = parseUpdatesConsent(record.updatesConsent);const quickAsks = record.quickAsks && typeof record.quickAsks === "object" && !Array.isArray(record.quickAsks)? Object.fromEntries(Object.entries(record.quickAsks).flatMap(([server, chat]) => { const parsed = parseChat(chat); return parsed ? [[server, parsed]] : []; }))@@ -86,7 +96,12 @@ export function createDesktopPrefs({ read, write }) {seen: () => [...current().seen],markSeen(id) {const saved = current();- if (DESKTOP_NOTICES.includes(id) && !saved.seen.includes(id)) save({ ...saved, seen: [...saved.seen, id] });+ if (saved.seen.includes(id)) return;+ if (DESKTOP_NOTICES.includes(id)) save({ ...saved, seen: [...saved.seen, id] });+ else if (typeof id === "string" && (ANNOUNCEMENT_SEEN.test(id) || ANNOUNCEMENT_SPONSOR_DAY.test(id))) {+ const fixed = saved.seen.filter(seen => DESKTOP_NOTICES.includes(seen));+ save({ ...saved, seen: [...fixed, ...keptAnnouncements([...saved.seen, id])] });+ }},/** null until a choice is saved. */analytics: () => current().analytics ?? null,diff --git a/electron/desktop-prefs.node-test.mjs b/electron/desktop-prefs.node-test.mjsindex c621f3ba26..826fbe8d6d 100644--- a/electron/desktop-prefs.node-test.mjs+++ b/electron/desktop-prefs.node-test.mjs@@ -55,6 +55,21 @@ test("What's new, Boat's credit offer and the Grok Bot move are the notices a pa}});+test("an announcement card's mark and the last sponsor day are kept beside the fixed notices, the newest few only", () => {+ let saved = { seen: [POPUP] };+ const prefs = createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });+ prefs.markSeen("announcement:phone-app"); prefs.markSeen("announcement:phone-app");+ prefs.markSeen("announcement-sponsor:2026-11-01"); prefs.markSeen("announcement-sponsor:2026-12-01");+ assert.deepEqual(prefs.seen(), [POPUP, "announcement:phone-app", "announcement-sponsor:2026-12-01"], "one sponsor day: the latest");+ for (const id of ["announcement:", "announcement:Bad Id", "announcement:x", `announcement:${"x".repeat(41)}`, "announcement-sponsor:soon", "announcement:../../x"]) prefs.markSeen(id);+ assert.deepEqual(prefs.seen(), [POPUP, "announcement:phone-app", "announcement-sponsor:2026-12-01"], "nothing outside the two shapes is kept");+ for (let index = 0; index < 45; index++) prefs.markSeen(`announcement:card-${index}`);+ const marks = prefs.seen().filter(id => id.startsWith("announcement:"));+ assert.equal(marks.length, 40); assert.equal(marks.at(-1), "announcement:card-44"); assert.ok(prefs.seen().includes(POPUP));+ const restarted = createDesktopPrefs({ read: () => saved, write: () => {} });+ assert.deepEqual(restarted.seen(), prefs.seen(), "survives a restart");+});+test("a write that fails leaves the last whole record on disk, analytics opt-out included", () => {const dir = mkdtempSync(path.join(tmpdir(), "desktop-prefs-"));try {diff --git a/scripts/check-announcements.mjs b/scripts/check-announcements.mjsnew file mode 100644index 0000000000..c3b9ea4f81--- /dev/null+++ b/scripts/check-announcements.mjs@@ -0,0 +1,93 @@+// Validates announcements/announcements.json. Installs download that file from main within the hour, so CI holds it to+// the strict schema and the rules below, and refuses the edit before it can merge.+//+// node scripts/check-announcements.mjs check the file+// node scripts/check-announcements.mjs --against <rev> also require updatedAt to move forward when the file changed+// node scripts/check-announcements.mjs --write-schema regenerate announcements/announcements.schema.json+import { execFileSync } from "node:child_process";+import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";++import {+ ANNOUNCEMENT_IMAGE_PREFIX, ANNOUNCEMENTS_FILE, ANNOUNCEMENTS_SCHEMA_FILE, announcementsJsonSchema, parseAnnouncementFeed,+} from "../shared/announcements.ts";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+/** Half what an install reads (server/announcements/feed.ts), so a growing file fails here first. */+export const MAX_FILE_BYTES = 32 * 1024;+/** A card's picture, as the corner card shows it at most 268 pixels wide. */+export const MAX_IMAGE_BYTES = 200 * 1024;+/** No card stays up longer than this from the day it merges: a forgotten card ends on its own. */+export const MAX_DAYS_AHEAD = 180;+const DAY = 24 * 60 * 60 * 1000;++/** Line endings aside: a Windows checkout may turn LF into CRLF, which changes nothing an install reads. */+export const lf = (text) => text.replace(/\r\n/g, "\n");+export const schemaText = () => `${JSON.stringify(announcementsJsonSchema(), null, 2)}\n`;++/** Problems with the file's text, or an empty list when it is sound. `fileSize(path)` is a picture's size in bytes, or null when+ * the repository has no such file. */+export function announcementProblems(raw, { previous: rawPrevious = null, now = Date.now(), fileSize = (path) => (existsSync(join(root, path)) ? statSync(join(root, path)).size : null) } = {}) {+ const text = lf(raw), previous = rawPrevious === null ? null : lf(rawPrevious);+ if (Buffer.byteLength(text) > MAX_FILE_BYTES) return [`the file is larger than ${MAX_FILE_BYTES} bytes`];+ let doc;+ try {+ doc = JSON.parse(text);+ } catch {+ return ["the file is not valid JSON"];+ }+ const parsed = parseAnnouncementFeed(doc, { strict: true, nowMs: now });+ if (!parsed.ok) return [parsed.error];+ const problems = [];+ for (const card of parsed.feed.cards) {+ if (card.kind === "sponsor" && !card.label) problems.push(`${card.id}: a sponsor's card needs a label, such as "Sponsor", so people can tell it is one`);+ if (Date.parse(card.ends) > now + MAX_DAYS_AHEAD * DAY) problems.push(`${card.id}: ends is more than ${MAX_DAYS_AHEAD} days away`);+ if (card.image && "url" in card.image) {+ const path = `announcements/${card.image.url.slice(ANNOUNCEMENT_IMAGE_PREFIX.length)}`;+ const size = fileSize(path);+ if (size === null) problems.push(`${card.id}: the picture ${path} is not in the repository`);+ else if (size > MAX_IMAGE_BYTES) problems.push(`${card.id}: the picture ${path} is larger than ${MAX_IMAGE_BYTES} bytes`);+ }+ }+ if (previous !== null && text !== previous) {+ let before = null;+ try { before = parseAnnouncementFeed(JSON.parse(previous), { nowMs: now }); } catch {}+ if (before?.ok && Date.parse(parsed.feed.updatedAt) <= Date.parse(before.feed.updatedAt)) {+ problems.push("the file changed but updatedAt did not move forward; installs keep the copy with the newest updatedAt");+ }+ }+ return problems;+}++function main() {+ const { values } = parseArgs({ options: { against: { type: "string" }, "write-schema": { type: "boolean" } } });+ const schemaPath = join(root, ANNOUNCEMENTS_SCHEMA_FILE);+ if (values["write-schema"]) {+ writeFileSync(schemaPath, schemaText());+ console.log(`announcements: wrote ${ANNOUNCEMENTS_SCHEMA_FILE}`);+ return;+ }+ const problems = [];+ if (!existsSync(schemaPath) || lf(readFileSync(schemaPath, "utf8")) !== schemaText()) {+ problems.push(`${ANNOUNCEMENTS_SCHEMA_FILE} is out of date: run node scripts/check-announcements.mjs --write-schema`);+ }+ let previous = null;+ if (values.against) {+ try {+ previous = execFileSync("git", ["show", `${values.against}:${ANNOUNCEMENTS_FILE}`], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });+ } catch {+ console.log("announcements: no earlier copy to compare with");+ }+ }+ problems.push(...announcementProblems(readFileSync(join(root, ANNOUNCEMENTS_FILE), "utf8"), { previous }));+ if (problems.length) {+ for (const problem of problems) console.error(`announcements: ${problem}`);+ process.exitCode = 1;+ return;+ }+ console.log("announcements: valid");+}++if (process.argv[1] === fileURLToPath(import.meta.url)) main();diff --git a/scripts/check-announcements.test.mjs b/scripts/check-announcements.test.mjsnew file mode 100644index 0000000000..b5e42d5d56--- /dev/null+++ b/scripts/check-announcements.test.mjs@@ -0,0 +1,89 @@+import { readFileSync } from "node:fs";+import { Ajv2020 } from "ajv/dist/2020.js";+import formats from "ajv-formats";+import { describe, expect, it } from "vitest";++import { announcementProblems, lf, MAX_DAYS_AHEAD, MAX_FILE_BYTES, MAX_IMAGE_BYTES, schemaText } from "./check-announcements.mjs";++const read = (path) => readFileSync(new URL(`../${path}`, import.meta.url), "utf8");+const committed = read("announcements/announcements.json");+const example = JSON.parse(read("scripts/testing/fixtures/announcements.example.json"));+const NOW = Date.parse("2026-12-01T10:00:00Z");+const DAY = 24 * 60 * 60 * 1000;+const noPictures = () => null;+const problems = (value, options = {}) => announcementProblems(typeof value === "string" ? value : JSON.stringify(value, null, 2), { now: NOW, fileSize: noPictures, ...options });+const tip = (extra = {}) => ({ ...structuredClone(example.cards[0]), ...extra });+const withCards = (...cards) => ({ ...structuredClone(example), cards });++describe("the committed file", () => {+ it("is valid", () => {+ expect(announcementProblems(committed)).toEqual([]);+ });++ it("has its JSON Schema beside it, up to date with the app's own rules", () => {+ expect(lf(read("announcements/announcements.schema.json")), "run node scripts/check-announcements.mjs --write-schema").toBe(schemaText());+ });++ it("the JSON Schema an editor reads takes the committed file and the documented examples", () => {+ const ajv = new Ajv2020({ strict: false, allErrors: true });+ // ajv-formats is CommonJS: the plugin is the module and its .default.+ (formats.default ?? formats)(ajv);+ const validate = ajv.compile(JSON.parse(schemaText()));+ expect(validate(JSON.parse(committed)), JSON.stringify(validate.errors)).toBe(true);+ expect(validate(example), JSON.stringify(validate.errors)).toBe(true);+ expect(validate(withCards(tip({ kind: "survey" })))).toBe(false);+ });+});++describe("what the check refuses", () => {+ it("the documented examples pass", () => {+ expect(problems(example)).toEqual([]);+ });++ it("malformed JSON, and a file too large for the corner", () => {+ expect(problems("{ not json")).toEqual(["the file is not valid JSON"]);+ expect(problems(" ".repeat(MAX_FILE_BYTES + 1))).toEqual([`the file is larger than ${MAX_FILE_BYTES} bytes`]);+ });++ it("a card the app could not show: an unknown kind or action, an http link, overflowing text, a typo'd field", () => {+ for (const card of [tip({ kind: "survey" }), tip({ primary: { label: "Go", action: { open: "billing" } } }), tip({ primary: { label: "Go", action: { open_url: "http://example.com" } } }),+ tip({ title: "x".repeat(61) }), tip({ titel: "Typo" }), tip({ ends: undefined })]) expect(problems(withCards(card)), JSON.stringify(card)).toHaveLength(1);+ });++ it("two cards with one id", () => {+ expect(problems(withCards(tip(), tip()))[0]).toMatch(/used twice/);+ });++ it("a sponsor's card with no label saying it is one", () => {+ const sponsor = { ...structuredClone(example.cards[1]) };+ delete sponsor.label;+ expect(problems(withCards(sponsor))).toEqual([`${sponsor.id}: a sponsor's card needs a label, such as "Sponsor", so people can tell it is one`]);+ });++ it("an end more than MAX_DAYS_AHEAD days away, though not an end already past", () => {+ expect(problems(withCards(tip({ ends: new Date(NOW + (MAX_DAYS_AHEAD + 1) * DAY).toISOString() })))[0]).toMatch(/days away/);+ expect(problems(withCards(tip({ ends: "2026-11-02T00:00:00Z" })))).toEqual([]);+ });++ it("a picture that is not in the repository, or too large", () => {+ const pictured = tip({ image: { url: "https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/announcements/images/tip.png", alt: "A tip" } });+ expect(problems(withCards(pictured))).toEqual(["tip-first-api-key: the picture announcements/images/tip.png is not in the repository"]);+ expect(problems(withCards(pictured), { fileSize: () => MAX_IMAGE_BYTES + 1 })[0]).toMatch(/larger than/);+ expect(problems(withCards(pictured), { fileSize: () => 40_000 })).toEqual([]);+ });++ it("ignores line endings: a CRLF checkout of an unchanged file is the same file", () => {+ const before = JSON.stringify(example, null, 2);+ expect(problems(before.replace(/\n/g, "\r\n"), { previous: before })).toEqual([]);+ expect(problems(before, { previous: before.replace(/\n/g, "\r\n") })).toEqual([]);+ expect(lf(schemaText().replace(/\n/g, "\r\n"))).toBe(schemaText());+ });++ it("a change that does not move updatedAt forward", () => {+ const before = JSON.stringify(example, null, 2);+ const edited = { ...structuredClone(example), cards: [tip({ title: "A new title" })] };+ expect(problems(edited, { previous: before })[0]).toMatch(/updatedAt did not move forward/);+ expect(problems({ ...edited, updatedAt: "2026-12-01T09:30:00Z" }, { previous: before })).toEqual([]);+ expect(problems(example, { previous: before }), "an unchanged file").toEqual([]);+ });+});diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 60cbec019a..a5fe9588ea 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -32,6 +32,9 @@ export const AREA_CHECKS = {// The Windows CUA job starts these the way the installed app does, then lends the PC's screen through them."windows-computer-control": [...SERVER_CHECKS, "windows-cua"],"control-plane": ["control-plane"],+ // The announcements file and its pictures: static validates them (scripts/check-announcements.mjs), and nothing else+ // reads them but the server's bundled copy, which that check covers.+ announcements: [],// The relay is its own package with its own lockfile; nothing outside relay/ reaches it except the shared vectors,// which it keeps a pinned copy of.relay: ["relay"],@@ -209,6 +212,7 @@ const AREAS = [[/^electron\/(?:cua|cua-failure|cua-connection|capabilities|screen-status|shared-cua-connection|shared-computer-access|lent-screen-tools|lent-screen-failures|paced-typing)\.[cm]js$/, "windows-computer-control"],[/^(?:electron|build)\/|^(?:electron-builder\.yml|index\.html|rail\.html)$/, "desktop"],[/^cloudflare\/control-plane\//, "control-plane"],+ [/^announcements\//, "announcements"],[/^relay\//, "relay"],];diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 6018b8e716..90f7ad9f3d 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -133,6 +133,12 @@ describe("CI path scope", () => {expect(selectCiScope([file])).toEqual({ areas: ["desktop"], checks: checks("server") });});+ it("runs nothing beyond static, which validates them, for the announcements file, its schema and pictures", () => {+ expect(selectCiScope(["announcements/announcements.json", "announcements/announcements.schema.json", "announcements/images/phone.png"]))+ .toEqual({ areas: ["announcements"], checks: [] });+ expect(selectCiScope(["announcements/announcements.json", "docs/announcements.md"])).toEqual({ areas: ["announcements", "docs"], checks: ["docs-tests"] });+ });+it("runs only the control-plane job for the control plane", () => {expect(selectCiScope(["cloudflare/control-plane/src/index.ts"])).toEqual({ areas: ["control-plane"], checks: ["control-plane"] });});diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex a2756f0bca..7a1f460b72 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -162,6 +162,8 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, data// Without it the server also scans /opt/homebrew/bin, /usr/local/bin and the// login shell's PATH, finding a developer's own engine CLIs that CI lacks.OMB_TEST_SEALED_PATH: "1",+ // The project's live announcement cards would sit over the corner the UI tests click in.+ OMB_DISABLE_ANNOUNCEMENTS: "1",});// The fake engines' knobs are the one thing a caller may script into the child.for (const [key, value] of Object.entries(parentEnv)) {diff --git a/scripts/testing/fixtures/announcements.example.json b/scripts/testing/fixtures/announcements.example.jsonnew file mode 100644index 0000000000..796643c7af--- /dev/null+++ b/scripts/testing/fixtures/announcements.example.json@@ -0,0 +1,32 @@+{+ "$schema": "../../../announcements/announcements.schema.json",+ "version": 1,+ "updatedAt": "2026-12-01T09:00:00Z",+ "cards": [+ {+ "id": "tip-first-api-key",+ "kind": "tip",+ "label": { "en": "Tip", "de": "Tipp" },+ "title": { "en": "Your bots can use any AI provider", "de": "Deine Bots können jeden KI-Anbieter nutzen" },+ "body": {+ "en": "Paste an API key once and every bot here can use it. You can change which model a bot uses at any time.",+ "de": "Füge einmal einen API-Schlüssel ein, und jeder Bot hier kann ihn nutzen. Das Modell eines Bots kannst du jederzeit ändern."+ },+ "primary": { "label": { "en": "Open API keys", "de": "API-Schlüssel öffnen" }, "action": { "open": "api_keys" } },+ "ends": "2027-02-01T00:00:00Z",+ "audience": { "people": "new", "when": ["no_api_key"], "surfaces": ["desktop", "cloud"] }+ },+ {+ "id": "sponsor-acme-credit-2026-12",+ "kind": "sponsor",+ "label": "Sponsor",+ "title": "Acme Inference: $5 of free credit",+ "body": "Acme Inference sponsors MausBot. New accounts get $5 of credit for any model they serve.",+ "primary": { "label": "Get a key", "action": { "open_url": "https://example.com/acme?utm_source=openmausbot&utm_medium=sponsorship" } },+ "secondary": { "label": "Add a key", "action": { "open": "api_keys" } },+ "starts": "2026-12-01T00:00:00Z",+ "ends": "2026-12-15T00:00:00Z",+ "audience": { "minVersion": "0.1.153", "plans": ["none", "cloud"] }+ }+ ]+}diff --git a/server/announcements/feed.test.ts b/server/announcements/feed.test.tsnew file mode 100644index 0000000000..08a3d13f20--- /dev/null+++ b/server/announcements/feed.test.ts@@ -0,0 +1,141 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { ANNOUNCEMENTS_URL, type AnnouncementFeed } from "../../shared/announcements.ts";+import {+ ANNOUNCEMENTS_DISABLE_ENV, ANNOUNCEMENTS_RETRY_MS, ANNOUNCEMENTS_TTL_MS, AnnouncementStore, announcementsCachePath, BUNDLED_ANNOUNCEMENTS,+} from "./feed.ts";++const NOW = Date.parse("2026-12-01T10:00:00Z");+const scratch: string[] = [];+afterEach(() => { for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); });++const dataDir = () => { const dir = mkdtempSync(join(tmpdir(), "omb-announcements-")); scratch.push(dir); return dir; };+const card = (id: string, extra: Record<string, unknown> = {}) => ({+ id, kind: "product", title: "Title", body: "Body.", primary: { label: "Open", action: { open_url: "https://example.com/" } }, ends: "2026-12-31T00:00:00Z", ...extra,+});+const feed = (updatedAt: string, cards: unknown[]): AnnouncementFeed => ({ version: 1, updatedAt, cards: cards as AnnouncementFeed["cards"] });+const bundled = feed("2026-11-01T00:00:00Z", []);+const answer = (body: unknown, init: ResponseInit = { status: 200 }) => new Response(typeof body === "string" ? body : JSON.stringify(body), init);++function subject(options: { fetch?: typeof fetch; dir?: string; env?: NodeJS.ProcessEnv; bundled?: AnnouncementFeed } = {}) {+ let time = NOW;+ const log = vi.fn();+ const store = new AnnouncementStore({ dataDir: options.dir ?? dataDir(), bundled: options.bundled ?? bundled, now: () => time, log, env: options.env ?? {}, fetch: options.fetch });+ return { store, log, advance: (ms: number) => { time += ms; } };+}++it("bundles the repository's file, and never fetches while switched off", async () => {+ expect(BUNDLED_ANNOUNCEMENTS.version).toBe(1);+ const fetchMock = vi.fn();+ const { store } = subject({ fetch: fetchMock, env: { [ANNOUNCEMENTS_DISABLE_ENV]: "1" }, bundled: feed("2026-11-01T00:00:00Z", [card("bundled-card")]) });+ expect(await store.cardsForPage()).toEqual([]);+ await store.refresh({ force: true });+ expect(fetchMock).not.toHaveBeenCalled();+ expect(store.disabled).toBe(true);+});++it("tests never reach the network: the suite switches it off for every server it starts", () => {+ expect(process.env[ANNOUNCEMENTS_DISABLE_ENV]).toBe("1");+});++describe("downloading the file", () => {+ it("asks main's raw file with a plain GET, nothing of the person's sent, and keeps what it got", async () => {+ const fetchMock = vi.fn(async (..._args: Parameters<typeof fetch>) => answer(feed("2026-12-01T09:00:00Z", [card("phone-app")])));+ const dir = dataDir();+ const { store } = subject({ fetch: fetchMock as unknown as typeof fetch, dir });+ expect((await store.cardsForPage()).map((entry) => entry.id)).toEqual(["phone-app"]);+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toBe(ANNOUNCEMENTS_URL);+ expect(init).toMatchObject({ credentials: "omit", referrerPolicy: "no-referrer", redirect: "error" });+ expect(Object.keys(init!.headers as Record<string, string>).sort()).toEqual(["accept", "user-agent"]);+ expect(url).not.toMatch(/[?#]/);+ expect(existsSync(announcementsCachePath(dir))).toBe(true);+ // A later start reads the copy on disk before any download.+ expect(subject({ dir, fetch: vi.fn() }).store.cards().map((entry) => entry.id)).toEqual(["phone-app"]);+ });++ it("fetches at most hourly, however many pages ask", async () => {+ const fetchMock = vi.fn(async () => answer(feed("2026-12-01T09:00:00Z", [])));+ const { store, advance } = subject({ fetch: fetchMock as unknown as typeof fetch });+ await Promise.all([store.cardsForPage(), store.cardsForPage(), store.cardsForPage()]);+ advance(ANNOUNCEMENTS_TTL_MS - 1000);+ await store.cardsForPage();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ advance(2000);+ await store.refresh();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("offline, rate-limited, too large, slow or not JSON: keeps the last good copy, says nothing to the page, retries later", async () => {+ const dir = dataDir();+ mkdirSync(dirname(announcementsCachePath(dir)), { recursive: true });+ writeFileSync(announcementsCachePath(dir), JSON.stringify({ fetchedAtMs: NOW - ANNOUNCEMENTS_TTL_MS * 2, feed: feed("2026-11-20T00:00:00Z", [card("kept")]) }));+ const failures: Array<() => Promise<Response>> = [+ async () => { throw new TypeError("fetch failed"); },+ async () => answer("rate limited", { status: 429 }),+ async () => answer("x".repeat(70 * 1024)),+ async () => answer("<html>"),+ async () => answer({ version: 2, updatedAt: "2026-12-01T00:00:00Z", cards: [] }),+ ];+ for (const failure of failures) {+ const { store, log } = subject({ dir, fetch: vi.fn(failure) as unknown as typeof fetch });+ expect((await store.cardsForPage()).map((entry) => entry.id), "the page is not kept waiting on a copy it has").toEqual(["kept"]);+ await store.refresh();+ expect(store.cards().map((entry) => entry.id)).toEqual(["kept"]);+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/keeping the current copy/));+ }+ const fetchMock = vi.fn(async () => { throw new Error("offline"); });+ const { store, advance } = subject({ dir, fetch: fetchMock as unknown as typeof fetch });+ await store.refresh();+ await store.refresh();+ expect(fetchMock, "backs off after a failure").toHaveBeenCalledTimes(1);+ advance(ANNOUNCEMENTS_RETRY_MS + 1);+ await store.refresh();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("a page's first ask waits a moment for the first download, never longer", async () => {+ const hanging = vi.fn((_url: unknown, init?: RequestInit) => new Promise<Response>((_resolve, reject) => init?.signal?.addEventListener("abort", () => reject(new Error("aborted")))));+ const { store } = subject({ fetch: hanging as unknown as typeof fetch });+ const started = Date.now();+ expect(await store.cardsForPage(50)).toEqual([]);+ expect(Date.now() - started).toBeLessThan(2_000);+ });++ it("an older copy from GitHub's cache cannot bring back a card a newer one removed", async () => {+ const dir = dataDir();+ const newer = subject({ dir, fetch: vi.fn(async () => answer(feed("2026-12-01T09:00:00Z", []))) as unknown as typeof fetch });+ await newer.store.refresh();+ const stale = subject({ dir, fetch: vi.fn(async () => answer(feed("2026-11-30T00:00:00Z", [card("pulled-back")]))) as unknown as typeof fetch });+ expect(await stale.store.cardsForPage()).toEqual([]);+ expect(JSON.parse(readFileSync(announcementsCachePath(dir), "utf8")).feed.updatedAt).toBe("2026-12-01T09:00:00Z");+ });++ it("skips a card it cannot read and one whose time has passed, and shows the rest", async () => {+ const cards = [card("good"), card("bad", { primary: { label: "Go", action: { run: "x" } } }), card("over", { ends: "2026-11-30T00:00:00Z" })];+ const { store, log } = subject({ fetch: vi.fn(async () => answer(feed("2026-12-01T09:00:00Z", cards))) as unknown as typeof fetch });+ expect((await store.cardsForPage()).map((entry) => entry.id)).toEqual(["good"]);+ expect(log).toHaveBeenCalledWith(expect.stringMatching(/skipping cards\.1/));+ });+});++describe("GET /api/announcements", () => {+ it("answers with the cards, and is open to every signed-in page", async () => {+ const { announcementRoutes, ANNOUNCEMENTS_PATH } = await import("../routes/announcements.ts");+ const { PASS } = await import("../routes/table.ts");+ const { requiredScope } = await import("../request-auth.ts");+ const sent: Array<{ status: number; body: unknown }> = [];+ const json = ((_res: unknown, status: number, body: unknown) => { sent.push({ status, body }); }) as never;+ const context = (method: string, path: string) => ({ req: {} as never, res: {} as never, url: new URL(`http://x${path}`), path, method, auth: {} as never, json, readBody: (async () => ({})) as never });+ expect(await announcementRoutes(context("GET", "/api/other"))).toBe(PASS);+ await announcementRoutes(context("GET", ANNOUNCEMENTS_PATH));+ expect(sent[0]).toEqual({ status: 200, body: { cards: [], disabled: true } });+ await announcementRoutes(context("POST", ANNOUNCEMENTS_PATH));+ expect(sent[1]!.status).toBe(405);+ expect(requiredScope("GET", ANNOUNCEMENTS_PATH)).toBe("client");+ expect(requiredScope("POST", ANNOUNCEMENTS_PATH)).toBe("admin");+ });+});diff --git a/server/announcements/feed.ts b/server/announcements/feed.tsnew file mode 100644index 0000000000..63eb1f42d2--- /dev/null+++ b/server/announcements/feed.ts@@ -0,0 +1,229 @@+// The announcements feed, as the model manifest (server/model-manifest/manifest.ts) keeps its list: a copy bundled with+// this release, a disk cache of the last good download, and a download from main on raw.githubusercontent.com. The+// fetch, cache and failure handling follow that file line for line; the two should become one helper once both are on+// main. Unlike the manifest it never runs on a timer of its own: a page asks for the cards at launch and about hourly+// (src/lib/announcements.ts), and that ask refreshes the copy here when it is an hour old, so a server nobody opens never+// downloads it. The request is a plain anonymous GET: no cookie, no id, no version.+import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";+import { dirname, join } from "node:path";++import bundledFeedJson from "../../announcements/announcements.json" with { type: "json" };+import { ANNOUNCEMENTS_URL, liveCards, parseAnnouncementFeed, type AnnouncementCard, type AnnouncementFeed } from "../../shared/announcements.ts";+import { writeFileAtomic } from "../atomic.ts";+import { DATA_DIR } from "../config.ts";++/** "1" stops the download and every remote card on this server's pages, the bundled ones included. */+export const ANNOUNCEMENTS_DISABLE_ENV = "OMB_DISABLE_ANNOUNCEMENTS";+export const ANNOUNCEMENTS_TTL_MS = 60 * 60 * 1000;+/** Back off failed fetches, so an offline computer does not try on every page load. */+export const ANNOUNCEMENTS_RETRY_MS = 5 * 60 * 1000;+export const ANNOUNCEMENTS_FETCH_TIMEOUT_MS = 10_000;+export const ANNOUNCEMENTS_MAX_BYTES = 64 * 1024;+/** How long a page's ask waits for a first download when there is no copy on disk yet; after that it gets what is here. */+export const ANNOUNCEMENTS_FIRST_WAIT_MS = 3_000;++const parsedBundle = parseAnnouncementFeed(bundledFeedJson, { strict: true, nowMs: Number.MAX_SAFE_INTEGER / 2 });+if (!parsedBundle.ok) throw new Error(`The bundled announcements are invalid (${parsedBundle.error})`);+export const BUNDLED_ANNOUNCEMENTS: AnnouncementFeed = parsedBundle.feed;++/** Under providers/, as the manifest's cache is, so backups and Move to Cloud leave it out. */+export function announcementsCachePath(dataDir: string): string {+ return join(dataDir, "providers", "announcements", "announcements.json");+}++export interface AnnouncementStoreOptions {+ dataDir: string;+ env?: NodeJS.ProcessEnv;+ fetch?: typeof fetch;+ now?: () => number;+ bundled?: AnnouncementFeed;+ timeoutMs?: number;+ maxBytes?: number;+ log?: (message: string) => void;+}++const updatedAtMs = (feed: AnnouncementFeed) => Date.parse(feed.updatedAt);++export class AnnouncementStore {+ private readonly options: AnnouncementStoreOptions;+ private readonly cachePath: string;+ private feed: AnnouncementFeed;+ private fetchedAtMs: number | null = null;+ private lastAttemptMs: number | null = null;+ private diskChecked = false;+ private inflight: Promise<AnnouncementFeed> | undefined;++ constructor(options: AnnouncementStoreOptions) {+ this.options = options;+ this.feed = options.bundled ?? BUNDLED_ANNOUNCEMENTS;+ this.cachePath = announcementsCachePath(options.dataDir);+ }++ private get now(): number {+ return (this.options.now ?? Date.now)();+ }++ private log(text: string): void {+ (this.options.log ?? ((line: string) => console.warn(line)))(`[announcements] ${text}`);+ }++ get disabled(): boolean {+ return (this.options.env ?? process.env)[ANNOUNCEMENTS_DISABLE_ENV] === "1";+ }++ /** The newest usable copy. Reads the disk cache once and never waits on the network. */+ current(): AnnouncementFeed {+ if (!this.diskChecked) this.loadDiskCache();+ return this.feed;+ }++ /** What a page is handed: nothing when switched off, else the cards whose time has not passed. */+ cards(): AnnouncementCard[] {+ return this.disabled ? [] : liveCards(this.current().cards, this.now);+ }++ /** Skipped inside `ttlMs` of the last good fetch and for a while after a failed one, unless `force`. Concurrent calls+ * share one request. Never throws. */+ refresh(options: { force?: boolean; ttlMs?: number } = {}): Promise<AnnouncementFeed> {+ if (this.disabled) return Promise.resolve(this.current());+ this.inflight ??= this.fetchAndStore(Boolean(options.force), options.ttlMs ?? ANNOUNCEMENTS_TTL_MS).finally(() => {+ this.inflight = undefined;+ });+ return this.inflight;+ }++ /** A page's ask: the cards now, after waiting a moment for a first download only when nothing was ever fetched. */+ async cardsForPage(firstWaitMs = ANNOUNCEMENTS_FIRST_WAIT_MS): Promise<AnnouncementCard[]> {+ if (this.disabled) return [];+ this.current();+ const refreshing = this.refresh().catch(() => this.feed);+ if (this.fetchedAtMs === null) {+ let timer: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([refreshing, new Promise((resolve) => { timer = setTimeout(resolve, firstWaitMs); timer.unref?.(); })]);+ clearTimeout(timer);+ }+ return this.cards();+ }++ private get maxBytes(): number {+ return this.options.maxBytes ?? ANNOUNCEMENTS_MAX_BYTES;+ }++ private loadDiskCache(): void {+ this.diskChecked = true;+ try {+ if (!existsSync(this.cachePath) || statSync(this.cachePath).size > this.maxBytes * 2) return;+ const raw = JSON.parse(readFileSync(this.cachePath, "utf8")) as { fetchedAtMs?: unknown; feed?: unknown };+ const parsed = parseAnnouncementFeed(raw.feed, { nowMs: this.now });+ if (!parsed.ok) {+ this.log(`ignoring the cached copy (${parsed.error})`);+ return;+ }+ if (updatedAtMs(this.feed) > updatedAtMs(parsed.feed)) return;+ this.feed = parsed.feed;+ this.fetchedAtMs = typeof raw.fetchedAtMs === "number" && Number.isFinite(raw.fetchedAtMs) ? raw.fetchedAtMs : null;+ } catch (error) {+ this.log(`could not read the cached copy (${message(error)})`);+ }+ }++ private async fetchAndStore(force: boolean, ttlMs: number): Promise<AnnouncementFeed> {+ this.current();+ const now = this.now;+ // Expire timestamps from the future after a clock rollback; the cache crosses restarts, so no monotonic clock.+ const within = (sinceMs: number | null, windowMs: number) => sinceMs !== null && now >= sinceMs && now - sinceMs < windowMs;+ if (!force && within(this.fetchedAtMs, ttlMs)) return this.feed;+ if (!force && within(this.lastAttemptMs, ANNOUNCEMENTS_RETRY_MS)) return this.feed;+ this.lastAttemptMs = now;++ let fetched: AnnouncementFeed;+ try {+ const result = await this.download();+ fetched = result.feed;+ for (const skipped of result.skipped) this.log(`skipping ${skipped}`);+ } catch (error) {+ this.log(`could not refresh the announcements (${message(error)}); keeping the current copy`);+ return this.feed;+ }+ // A stale CDN copy loses to what we already have, so it cannot bring back a card a newer copy removed.+ if (updatedAtMs(fetched) < updatedAtMs(this.feed)) {+ this.log(`ignoring a downloaded copy older than the current one (${fetched.updatedAt})`);+ return this.feed;+ }+ this.feed = fetched;+ this.fetchedAtMs = now;+ this.lastAttemptMs = null;+ try {+ mkdirSync(dirname(this.cachePath), { recursive: true });+ writeFileAtomic(this.cachePath, JSON.stringify({ fetchedAtMs: now, feed: fetched }));+ } catch (error) {+ this.log(`could not save the downloaded announcements (${message(error)})`);+ }+ return this.feed;+ }++ private async download(): Promise<{ feed: AnnouncementFeed; skipped: string[] }> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), this.options.timeoutMs ?? ANNOUNCEMENTS_FETCH_TIMEOUT_MS);+ try {+ const response = await (this.options.fetch ?? fetch)(ANNOUNCEMENTS_URL, {+ headers: { accept: "application/json", "user-agent": "OpenMausBot" },+ // Nothing of the person's goes with it.+ credentials: "omit",+ referrerPolicy: "no-referrer",+ // raw.githubusercontent.com answers directly; anywhere else is not the file we meant to read.+ redirect: "error",+ signal: controller.signal,+ });+ if (response.status !== 200) {+ void response.body?.cancel().catch(() => {});+ throw new Error(`HTTP ${response.status}`);+ }+ const declared = Number(response.headers.get("content-length"));+ if (Number.isFinite(declared) && declared > this.maxBytes) {+ void response.body?.cancel().catch(() => {});+ throw new Error(`larger than ${this.maxBytes} bytes`);+ }+ const text = await readCapped(response, this.maxBytes);+ let json: unknown;+ try { json = JSON.parse(text); } catch { throw new Error("not valid JSON"); }+ const parsed = parseAnnouncementFeed(json, { nowMs: this.now });+ if (!parsed.ok) throw new Error(parsed.error);+ return { feed: parsed.feed, skipped: parsed.skipped };+ } catch (error) {+ if (controller.signal.aborted) throw new Error("it did not answer in time");+ throw error;+ } finally {+ clearTimeout(timer);+ }+ }+}++async function readCapped(response: Response, maxBytes: number): Promise<string> {+ if (!response.body) return "";+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let total = 0;+ let text = "";+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ total += value.byteLength;+ if (total > maxBytes) {+ await reader.cancel().catch(() => {});+ throw new Error(`larger than ${maxBytes} bytes`);+ }+ text += decoder.decode(value, { stream: true });+ }+ return text + decoder.decode();+}++function message(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++let store: AnnouncementStore | undefined;++export function announcementStore(): AnnouncementStore {+ return store ??= new AnnouncementStore({ dataDir: DATA_DIR });+}diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex 536da697a9..9849484a5a 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -34,7 +34,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_COMPUTER_CALL_WAIT_MS", "OMB_COMPUTER_WAIT_MAX_MS", "OMB_CONTROL_PLANE_URL", "OMB_CONTROL_PORT","OMB_CREDENTIAL_STORE", "OMB_CUSTOM_IMAGE_KEY", "OMB_DATA_DIR", "OMB_DECISION_RETENTION_DAYS","OMB_DEEPSEEK_API_KEY", "OMB_DESKTOP_LAUNCH_ID", "OMB_DESKTOP_PARENT", "OMB_DEVS_STATUS_MS",- "OMB_DEV_TRUST_LOCAL_BROWSER", "OMB_DISABLE_MODEL_CATALOG_FETCH", "OMB_DISABLE_MODEL_MANIFEST_FETCH", "OMB_DUCKDB_DIR", "OMB_DUCKDB_MAX_TEMP_SIZE",+ "OMB_DEV_TRUST_LOCAL_BROWSER", "OMB_DISABLE_ANNOUNCEMENTS", "OMB_DISABLE_MODEL_CATALOG_FETCH", "OMB_DISABLE_MODEL_MANIFEST_FETCH", "OMB_DUCKDB_DIR", "OMB_DUCKDB_MAX_TEMP_SIZE","OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENTERPRISE_DIR", "OMB_ENVIRONMENT_LABEL", "OMB_EOF","OMB_FIRST_REPLY_NOTICE_MS", "OMB_FISH_AUDIO_API", "OMB_FISH_AUDIO_API_KEY", "OMB_FLEET_SOCKET", "OMB_GATE_","OMB_GEMINI_API_KEY", "OMB_GEMINI_IMAGE_KEY", "OMB_GEMINI_TTS_API", "OMB_GOAL_WAIT_MAX_MS",diff --git a/server/request-auth.ts b/server/request-auth.tsindex 777dc4872d..cff4038ec1 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -451,6 +451,8 @@ export const CLIENT_ALLOW: ReadonlyArray<{ methods: readonly string[]; path: Reg{ methods: ["GET"], path: /^\/api\/team\/people$/ },// the workspace's banner picture: everyone signed in here sees it; changing it (PUT, DELETE) is an admin's{ methods: ["GET"], path: /^\/api\/workspace\/banner$/ },+ // the project's announcement cards, the same public file for everyone (routes/announcements.ts)+ { methods: ["GET"], path: /^\/api\/announcements$/ },// a teammate's picture: the handler serves it to the team's own members only{ methods: ["GET"], path: /^\/api\/team\/people\/p_[\w-]{22}\/picture$/ },{ methods: ["PUT"], path: /^\/api\/bots\/[\w-]+\/reports-to$/ },diff --git a/server/routes/announcements.ts b/server/routes/announcements.tsnew file mode 100644index 0000000000..f85e45447d--- /dev/null+++ b/server/routes/announcements.ts@@ -0,0 +1,14 @@+import { announcementStore } from "../announcements/feed.ts";+import { PASS, type RouteHandler } from "./table.ts";++export const ANNOUNCEMENTS_PATH = "/api/announcements";++/** GET /api/announcements: the project's announcement cards whose time has not passed, for every signed-in page alike+ * (request-auth.ts lets a Team Cloud's members read it). Each page decides for itself which card, if any, it shows.+ * Asking refreshes this server's copy when it is an hour old; it never fails for want of the network. */+export const announcementRoutes: RouteHandler = async ({ res, path, method, json }) => {+ if (path !== ANNOUNCEMENTS_PATH) return PASS;+ if (method !== "GET") return json(res, 405, { error: "Use GET." });+ const store = announcementStore();+ return json(res, 200, { cards: await store.cardsForPage(), ...(store.disabled ? { disabled: true } : {}) });+};diff --git a/server/routes/table.ts b/server/routes/table.tsindex a157b7ff19..a587fa2607 100644--- a/server/routes/table.ts+++ b/server/routes/table.ts@@ -2,6 +2,7 @@import type { IncomingMessage, ServerResponse } from "node:http";import type { json, readBody } from "../harness/http.ts";import type { RequestAuth } from "../request-auth.ts";+import { announcementRoutes } from "./announcements.ts";import { cloudSyncRoutes } from "./cloud-sync.ts";import { ownMcpHttpRoutes } from "./own-mcp-http.ts";import { webPanelRoutes } from "./web-panels.ts";@@ -23,7 +24,7 @@ export interface RouteContext {export type RouteHandler = (ctx: RouteContext) => Promise<typeof PASS | void>;/** Modules with no wiring from index.ts are listed here; index.ts pushes the rest. */-export const ROUTES: RouteHandler[] = [cloudSyncRoutes, ownMcpHttpRoutes, webPanelRoutes];+export const ROUTES: RouteHandler[] = [cloudSyncRoutes, ownMcpHttpRoutes, webPanelRoutes, announcementRoutes];/** True means stop routing. A handler that wrote a response but returned PASS still counts as answered. */export async function dispatchRoutes(routes: readonly RouteHandler[], ctx: RouteContext): Promise<boolean> {diff --git a/server/testing/setup.ts b/server/testing/setup.tsindex ad49b54594..bae32da789 100644--- a/server/testing/setup.ts+++ b/server/testing/setup.ts@@ -20,6 +20,8 @@ process.env.OMB_DISABLE_MODEL_MANIFEST_FETCH = "1";delete process.env.HERMES_HOME;// A ChatGPT-plan turn links the person's Codex home ($CODEX_HOME or ~/.codex) into its own: keep it in the throwaway home.delete process.env.CODEX_HOME;+// No server in a test downloads the project's announcement cards; its tests hand the store a fake fetch.+process.env.OMB_DISABLE_ANNOUNCEMENTS = "1";// Named explicitly although homedir() already covers it: the device tests delete this directory wholesale.process.env.OMB_COMPANION_DIR = join(home, ".openmausbot-companion");diff --git a/shared/announcements.test.ts b/shared/announcements.test.tsnew file mode 100644index 0000000000..10f896c58b--- /dev/null+++ b/shared/announcements.test.ts@@ -0,0 +1,176 @@+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";+import {+ ANNOUNCEMENT_IMAGE_PREFIX, audienceMatches, compareVersions, isAnnouncementImageUrl, isHttpsUrl, LIMITS, liveCards, localized, MAX_CARDS,+ parseAnnouncementCard, parseAnnouncementFeed, type AnnouncementFacts,+} from "./announcements";++const NOW = Date.parse("2026-12-01T10:00:00Z");+const example = JSON.parse(readFileSync(new URL("../scripts/testing/fixtures/announcements.example.json", import.meta.url), "utf8")) as { cards: Record<string, unknown>[] };+const card = (extra: Record<string, unknown> = {}) => ({+ id: "tip-one", kind: "tip", title: "A title", body: "A body.", primary: { label: "Open", action: { open: "api_keys" } }, ends: "2026-12-31T00:00:00Z", ...extra,+});+const feed = (cards: unknown[], extra: Record<string, unknown> = {}) => ({ version: 1, updatedAt: "2026-12-01T09:00:00Z", cards, ...extra });+const facts = (extra: Partial<AnnouncementFacts> = {}): AnnouncementFacts => ({+ nowMs: NOW, version: "0.1.160", platform: "mac", surface: "desktop", plan: "none", people: "existing", locale: "en",+ conditions: { no_api_key: false, one_bot_only: false, no_routine: false }, ...extra,+});++describe("the file", () => {+ it("reads the documented examples, in either mode", () => {+ for (const strict of [false, true]) {+ const parsed = parseAnnouncementFeed({ ...example, $schema: undefined }, { strict, nowMs: NOW });+ expect(parsed.ok && parsed.feed.cards.map((entry) => entry.id)).toEqual(["tip-first-api-key", "sponsor-acme-credit-2026-12"]);+ }+ });++ it("refuses the whole file when its outer shape is wrong, so the last good copy stays", () => {+ expect(parseAnnouncementFeed(feed([]), { nowMs: NOW }).ok).toBe(true);+ expect(parseAnnouncementFeed({ ...feed([]), version: 2 }, { nowMs: NOW }).ok, "a later format").toBe(false);+ expect(parseAnnouncementFeed({ version: 1, cards: [] }, { nowMs: NOW }).ok, "no updatedAt").toBe(false);+ expect(parseAnnouncementFeed(feed([], { updatedAt: "2026-12-05T00:00:00Z" }), { nowMs: NOW }).ok, "updatedAt in the future").toBe(false);+ expect(parseAnnouncementFeed(feed({} as never), { nowMs: NOW }).ok).toBe(false);+ expect(parseAnnouncementFeed("<html>", { nowMs: NOW }).ok).toBe(false);+ });++ it("an install skips a card it cannot read and keeps the rest; CI refuses the file instead", () => {+ const cards = [card({ id: "good-one" }), card({ id: "bad-kind", kind: "survey" }), card({ id: "good-one" }), card({ id: "no-end", ends: undefined })];+ const lenient = parseAnnouncementFeed(feed(cards), { nowMs: NOW });+ expect(lenient.ok && lenient.feed.cards.map((entry) => entry.id)).toEqual(["good-one"]);+ expect(lenient.ok && lenient.skipped).toHaveLength(3);+ expect(parseAnnouncementFeed(feed(cards), { strict: true, nowMs: NOW }).ok).toBe(false);+ });++ it("reads at most MAX_CARDS cards; CI refuses more", () => {+ const many = Array.from({ length: MAX_CARDS + 5 }, (_, index) => card({ id: `card-${index}` }));+ const parsed = parseAnnouncementFeed(feed(many), { nowMs: NOW });+ expect(parsed.ok && parsed.feed.cards).toHaveLength(MAX_CARDS);+ expect(parseAnnouncementFeed(feed(many), { strict: true, nowMs: NOW }).ok).toBe(false);+ });++ it("a field a later version adds is ignored by an install, and refused by CI as a typo", () => {+ const later = card({ layout: "wide", theme: { accent: "red" } });+ const parsed = parseAnnouncementCard(later);+ expect(parsed.ok && Object.keys(parsed.card)).not.toContain("layout");+ expect(parseAnnouncementCard(later, { strict: true }).ok).toBe(false);+ });+});++describe("a card", () => {+ it("needs an end, after its start", () => {+ expect(parseAnnouncementCard(card({ ends: undefined })).ok).toBe(false);+ expect(parseAnnouncementCard(card({ starts: "2027-01-01T00:00:00Z" })).ok).toBe(false);+ expect(parseAnnouncementCard(card({ starts: "2026-12-02T00:00:00Z" })).ok).toBe(true);+ });++ it("has a stable id of lowercase letters, digits and dashes", () => {+ for (const id of ["Tip", "a", "tip one", "-tip", "tip_one", "x".repeat(LIMITS.id + 1)]) expect(parseAnnouncementCard(card({ id })).ok, id).toBe(false);+ });++ it("holds every text to its length, in every language", () => {+ expect(parseAnnouncementCard(card({ title: "x".repeat(LIMITS.title) })).ok).toBe(true);+ expect(parseAnnouncementCard(card({ title: "x".repeat(LIMITS.title + 1) })).ok).toBe(false);+ expect(parseAnnouncementCard(card({ body: { en: "Fine.", de: "x".repeat(LIMITS.body + 1) } })).ok).toBe(false);+ expect(parseAnnouncementCard(card({ label: "x".repeat(LIMITS.label + 1) })).ok).toBe(false);+ expect(parseAnnouncementCard(card({ primary: { label: "x".repeat(LIMITS.button + 1), action: { open: "api_keys" } } })).ok).toBe(false);+ expect(parseAnnouncementCard(card({ body: "One\nTwo\nThree" })).ok).toBe(true);+ expect(parseAnnouncementCard(card({ body: "1\n2\n3\n4" })).ok, "too many lines for the corner").toBe(false);+ });++ it("refuses text that hides or reorders itself, and a map with no English", () => {+ for (const title of ["Pay evil", "zerowidth", "tab\there", "line\nbreak", " padded"]) expect(parseAnnouncementCard(card({ title })).ok, JSON.stringify(title)).toBe(false);+ expect(parseAnnouncementCard(card({ title: { de: "Nur Deutsch" } })).ok).toBe(false);+ });++ it("is never markup: angle brackets stay text, nothing is read as HTML", () => {+ const parsed = parseAnnouncementCard(card({ body: "<img src=x onerror=alert(1)> <b>bold</b>" }));+ expect(parsed.ok && parsed.card.body).toBe("<img src=x onerror=alert(1)> <b>bold</b>");+ });++ it("does one of a few actions: an https page, or one of the app's own places", () => {+ const action = (value: unknown) => parseAnnouncementCard(card({ primary: { label: "Go", action: value } })).ok;+ expect(action({ open_url: "https://example.com/page?a=1" })).toBe(true);+ expect(action({ open: "connected_apps" })).toBe(true);+ for (const bad of [{ open_url: "http://example.com" }, { open_url: "javascript:alert(1)" }, { open_url: "https://user:[email protected]" }, { open_url: "file:///etc/passwd" },+ { open: "settings/../../" }, { open: "billing" }, { run: "rm -rf /" }, { open_url: "https://example.com", open: "api_keys" }, {}]) expect(action(bad), JSON.stringify(bad)).toBe(false);+ });++ it("shows a picture only from this repository's announcements folder, and an install drops one it cannot read", () => {+ expect(isAnnouncementImageUrl(`${ANNOUNCEMENT_IMAGE_PREFIX}images/phone.png`)).toBe(true);+ for (const bad of [`${ANNOUNCEMENT_IMAGE_PREFIX}../secret.png`, `${ANNOUNCEMENT_IMAGE_PREFIX}images/x.svg`, "https://example.com/x.png",+ `${ANNOUNCEMENT_IMAGE_PREFIX}images/x.png?track=1`, ANNOUNCEMENT_IMAGE_PREFIX.replace("https", "http") + "x.png"]) expect(isAnnouncementImageUrl(bad), bad).toBe(false);+ const parsed = parseAnnouncementCard(card({ image: { url: "https://example.com/tracker.png" } }));+ expect(parsed.ok && parsed.card.image).toBeUndefined();+ expect(parseAnnouncementCard(card({ image: { url: "https://example.com/tracker.png" } }), { strict: true }).ok).toBe(false);+ const mark = parseAnnouncementCard(card({ image: { mark: "modelgo" } }));+ expect(mark.ok && mark.card.image).toEqual({ mark: "modelgo" });+ });+});++it("an https address has a host and nothing hidden in it", () => {+ expect(isHttpsUrl("https://github.com/milind-soni/OpenMausBot")).toBe(true);+ for (const bad of ["https://localhost/x", "https:// spaced.com", "https://a.com/\u0000", "ftp://a.com", "//a.com"]) expect(isHttpsUrl(bad), bad).toBe(false);+});++it("a text falls back from the region to the language to English", () => {+ const text = { en: "Hello", de: "Hallo", "pt-br": "Olá" };+ expect(localized(text, "de")).toBe("Hallo");+ expect(localized(text, "pt-BR")).toBe("Olá");+ expect(localized(text, "de-at")).toBe("Hallo");+ expect(localized(text, "ja")).toBe("Hello");+ expect(localized("Plain", "ja")).toBe("Plain");+});++it("drops cards whose time has passed", () => {+ const cards = [card({ id: "past", ends: "2026-11-30T00:00:00Z" }), card({ id: "now" })].map((entry) => { const parsed = parseAnnouncementCard(entry); if (!parsed.ok) throw new Error(parsed.error); return parsed.card; });+ expect(liveCards(cards, NOW).map((entry) => entry.id)).toEqual(["now"]);+});++describe("who a card is for", () => {+ it("is everyone without an audience", () => {+ expect(audienceMatches(undefined, facts())).toBe(true);+ expect(audienceMatches({}, facts())).toBe(true);+ });++ it("an audience key this version does not know reaches no one", () => {+ expect(audienceMatches({ countries: ["de"] }, facts())).toBe(false);+ expect(audienceMatches({ people: "new", plans: ["none"], futureKey: true }, facts({ people: "new" }))).toBe(false);+ });++ it("compares versions, and an unreadable version matches no range", () => {+ expect(compareVersions("0.1.160", "0.1.153")).toBe(1);+ expect(compareVersions("0.1.9", "0.1.10")).toBe(-1);+ expect(audienceMatches({ minVersion: "0.1.160" }, facts())).toBe(true);+ expect(audienceMatches({ minVersion: "0.1.161" }, facts())).toBe(false);+ expect(audienceMatches({ maxVersion: "0.1.159" }, facts())).toBe(false);+ expect(audienceMatches({ minVersion: "0.1.1" }, facts({ version: "dev" }))).toBe(false);+ expect(audienceMatches({ minVersion: "one" }, facts())).toBe(false);+ });++ it("matches lists, and a value it does not know never matches", () => {+ expect(audienceMatches({ platforms: ["mac", "visionos"] }, facts())).toBe(true);+ expect(audienceMatches({ platforms: ["visionos"] }, facts())).toBe(false);+ expect(audienceMatches({ platforms: ["mac"] }, facts({ platform: null }))).toBe(false);+ expect(audienceMatches({ surfaces: ["cloud"] }, facts())).toBe(false);+ expect(audienceMatches({ people: "new" }, facts())).toBe(false);+ expect(audienceMatches({ people: "returning" }, facts())).toBe(false);+ expect(audienceMatches({ languages: ["pt-br"] }, facts({ locale: "pt-br" }))).toBe(true);+ expect(audienceMatches({ languages: ["de"] }, facts({ locale: "de-at" }))).toBe(true);+ expect(audienceMatches({ languages: ["de"] }, facts())).toBe(false);+ expect(audienceMatches({ platforms: "mac" }, facts()), "not a list").toBe(false);+ });++ it("needs every condition, and one it cannot check fails", () => {+ const conditions = { no_api_key: true, one_bot_only: true, no_routine: false };+ expect(audienceMatches({ when: ["no_api_key", "one_bot_only"] }, facts({ conditions }))).toBe(true);+ expect(audienceMatches({ when: ["no_api_key", "no_routine"] }, facts({ conditions }))).toBe(false);+ expect(audienceMatches({ when: ["no_api_key", "no_connected_app"] }, facts({ conditions }))).toBe(false);+ });++ it("waits for the plan while it is read, and a page that cannot know it matches no plan", () => {+ expect(audienceMatches({ plans: ["none"] }, facts({ plan: null }))).toBeNull();+ expect(audienceMatches({ plans: ["none"], people: "new" }, facts({ plan: null })), "what is known already rules it out").toBe(false);+ expect(audienceMatches({ plans: ["cloud"] }, facts({ plan: undefined }))).toBe(false);+ expect(audienceMatches({ plans: ["team", "cloud"] }, facts({ plan: "team" }))).toBe(true);+ });+});diff --git a/shared/announcements.ts b/shared/announcements.tsnew file mode 100644index 0000000000..bbffd7b3ea--- /dev/null+++ b/shared/announcements.ts@@ -0,0 +1,318 @@+// The announcements feed: cards the project publishes by editing announcements/announcements.json on main. The app+// downloads that file and draws each card itself with its own notice card; the file carries words, a picture's+// address, one of a few fixed button actions and who the card is for, never markup or code.+//+// The file is untrusted input, though it is ours: a bad merge reaches every install within the hour. So every text has+// a length limit and no control or direction characters, links are https only, buttons open an external page or one of+// the app's own places named below, pictures come from this repository's own folder, and a card the app cannot read+// fully is skipped. `strict` is what CI holds the file to (scripts/check-announcements.mjs); an install reads it+// leniently, so a field a later version adds never hides a card from this one, while an unknown kind, action or+// audience key does.+import { z } from "zod";++export const ANNOUNCEMENTS_FILE = "announcements/announcements.json";+export const ANNOUNCEMENTS_SCHEMA_FILE = "announcements/announcements.schema.json";+export const ANNOUNCEMENTS_URL = `https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/${ANNOUNCEMENTS_FILE}`;+/** Pictures: files in the repository's announcements/ folder on main, as raw.githubusercontent.com serves them. */+export const ANNOUNCEMENT_IMAGE_PREFIX = "https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/announcements/";++/** An install reads at most this many cards, in file order; CI refuses a longer list. */+export const MAX_CARDS = 20;+export const MAX_LOCALES = 16;+export const LIMITS = { id: 40, label: 16, title: 60, body: 240, button: 24, alt: 120, url: 500, bodyLines: 3 } as const;++export const ANNOUNCEMENT_KINDS = ["sponsor", "product", "tip"] as const;+export type AnnouncementKind = (typeof ANNOUNCEMENT_KINDS)[number];++/** The app's own places a button may open. Each is something the app already opens from its own menus. */+export const ANNOUNCEMENT_PLACES = ["api_keys", "ai_engines", "connected_apps", "new_bot", "my_cloud"] as const;+export type AnnouncementPlace = (typeof ANNOUNCEMENT_PLACES)[number];+/** Places only someone who may change this place's settings can use: a card that opens one skips everyone else. */+export const ADMIN_PLACES: ReadonlySet<AnnouncementPlace> = new Set(["api_keys", "ai_engines", "new_bot"]);++/** Built-in marks a card may show beside its title instead of a picture. */+export const ANNOUNCEMENT_MARKS = ["claude", "codex", "grok", "kimi", "modelgo", "greenference", "deepseek", "copilot", "kiro"] as const;+export type AnnouncementMark = (typeof ANNOUNCEMENT_MARKS)[number];++export const ANNOUNCEMENT_PLATFORMS = ["mac", "windows", "linux", "ios", "android"] as const;+export type AnnouncementPlatform = (typeof ANNOUNCEMENT_PLATFORMS)[number];+/** `desktop`: the desktop app's own page. `cloud`: a MausBot Cloud's page, in a browser or in the desktop's window.+ * `server`: any other server's page, a self-hosted one or the app in a browser. */+export const ANNOUNCEMENT_SURFACES = ["desktop", "cloud", "server"] as const;+export type AnnouncementSurface = (typeof ANNOUNCEMENT_SURFACES)[number];+/** `none`: no MausBot Cloud plan of one's own (signed out, or a free account). `cloud`: a Cloud of one's own, or its+ * page. `team`: a Team Cloud's page. */+export const ANNOUNCEMENT_PLANS = ["none", "cloud", "team"] as const;+export type AnnouncementPlan = (typeof ANNOUNCEMENT_PLANS)[number];+/** `new`: nobody has had a reply on this place before this launch. `existing`: someone has. */+export const ANNOUNCEMENT_PEOPLE = ["new", "existing"] as const;+export type AnnouncementPeople = (typeof ANNOUNCEMENT_PEOPLE)[number];+/** Conditions the app reads from what it already has on screen; every one listed must hold. */+export const ANNOUNCEMENT_CONDITIONS = ["no_api_key", "one_bot_only", "no_routine"] as const;+export type AnnouncementCondition = (typeof ANNOUNCEMENT_CONDITIONS)[number];+/** The app's languages, as its language menu lists them (localeChoices). */+export const ANNOUNCEMENT_LOCALES = ["en", "de", "es", "fr", "hi", "ja", "pt-br", "zh", "zh-tw", "uk", "vi", "tr", "pl", "ru", "it", "ko"] as const;+export const AUDIENCE_KEYS = ["minVersion", "maxVersion", "platforms", "surfaces", "plans", "people", "languages", "when"] as const;++// Control characters, and the ones that reorder or hide text (bidi overrides and isolates, zero-width joiners).+// eslint-disable-next-line no-control-regex+const LINE_FORBIDDEN = /[\u0000-\u001f\u007f-\u009f---]/u;+// eslint-disable-next-line no-control-regex+const BODY_FORBIDDEN = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f---]/u;+const LOCALE_KEY = /^[a-z]{2,3}(?:-[a-z0-9]{2,8})?$/;+const ID = /^[a-z0-9][a-z0-9-]*$/;+const VERSION = /^\d{1,6}\.\d{1,6}\.\d{1,6}$/;+const IMAGE_PATH = /^[a-z0-9][a-z0-9._/-]*\.(?:png|jpe?g|webp)$/;+/** Allows for a slow local clock, as the model manifest does. */+const FUTURE_TOLERANCE_MS = 24 * 60 * 60 * 1000;++/** True for an https address with a host and nothing hidden in it: no user name or password, no spaces. */+export function isHttpsUrl(value: string): boolean {+ if (value.length > LIMITS.url || /\s/.test(value) || LINE_FORBIDDEN.test(value)) return false;+ try {+ const url = new URL(value);+ return url.protocol === "https:" && !url.username && !url.password && url.hostname.includes(".") && !url.hostname.endsWith(".");+ } catch {+ return false;+ }+}++export function isAnnouncementImageUrl(value: string): boolean {+ if (!isHttpsUrl(value) || !value.startsWith(ANNOUNCEMENT_IMAGE_PREFIX)) return false;+ const rest = value.slice(ANNOUNCEMENT_IMAGE_PREFIX.length);+ return IMAGE_PATH.test(rest) && !rest.split("/").some((part) => part === "" || part === "." || part === "..");+}++type ObjectOf = typeof z.object;++function oneText(max: number, body: boolean) {+ return z.string().min(1).max(max)+ .refine((value) => !(body ? BODY_FORBIDDEN : LINE_FORBIDDEN).test(value), "control or direction characters")+ .refine((value) => !body || value.split("\n").length <= LIMITS.bodyLines, `at most ${LIMITS.bodyLines} lines`)+ .refine((value) => value.trim() === value, "leading or trailing spaces");+}++/** Plain text: one string (English), or one per language with English among them. */+function text(max: number, strict: boolean, body = false) {+ const one = oneText(max, body);+ // partialRecord: a record keyed by an enum would need every language.+ const map = (strict ? z.partialRecord(z.enum(ANNOUNCEMENT_LOCALES), one) : z.record(z.string().regex(LOCALE_KEY), one)) as z.ZodType<Record<string, string>>;+ return z.union([+ one,+ map.refine((map) => Object.hasOwn(map, "en"), "needs an \"en\" text")+ .refine((map) => Object.keys(map).length <= MAX_LOCALES, `at most ${MAX_LOCALES} languages`),+ ]);+}+export type AnnouncementText = string | Record<string, string>;++const httpsUrl = z.string().max(LIMITS.url).refine(isHttpsUrl, "an https address");++/** Exactly one key, in every mode: anything else is an action this version cannot do. */+export const actionSchema = z.union([+ z.strictObject({ open_url: httpsUrl }),+ z.strictObject({ open: z.enum(ANNOUNCEMENT_PLACES) }),+]);+export type AnnouncementAction = z.infer<typeof actionSchema>;++function imageSchema(objectOf: ObjectOf, strict: boolean) {+ return z.union([+ objectOf({ url: z.string().max(LIMITS.url).refine(isAnnouncementImageUrl, `a .png, .jpg or .webp file under ${ANNOUNCEMENT_IMAGE_PREFIX}`), alt: text(LIMITS.alt, strict).optional() }),+ objectOf({ mark: z.enum(ANNOUNCEMENT_MARKS) }),+ ]);+}++function audienceSchema(strict: boolean) {+ const list = <const T extends readonly [string, ...string[]]>(values: T) =>+ strict ? z.array(z.enum(values)).min(1).max(values.length) : z.array(z.string().max(40)).min(1).max(40);+ const fields = {+ minVersion: strict ? z.string().regex(VERSION).optional() : z.string().max(40).optional(),+ maxVersion: strict ? z.string().regex(VERSION).optional() : z.string().max(40).optional(),+ platforms: list(ANNOUNCEMENT_PLATFORMS).optional(),+ surfaces: list(ANNOUNCEMENT_SURFACES).optional(),+ plans: list(ANNOUNCEMENT_PLANS).optional(),+ people: strict ? z.enum(ANNOUNCEMENT_PEOPLE).optional() : z.string().max(40).optional(),+ languages: strict ? z.array(z.enum(ANNOUNCEMENT_LOCALES)).min(1).max(ANNOUNCEMENT_LOCALES.length).optional() : z.array(z.string().max(40)).min(1).max(40).optional(),+ when: list(ANNOUNCEMENT_CONDITIONS).optional(),+ };+ // An install keeps a key it does not know, so the card then reaches no one rather than everyone.+ return strict ? z.strictObject(fields) : z.looseObject(fields);+}++function buttonSchema(objectOf: ObjectOf, strict: boolean) {+ return objectOf({ label: text(LIMITS.button, strict), action: actionSchema });+}++function cardSchema(strict: boolean) {+ const objectOf = strict ? (z.strictObject as unknown as ObjectOf) : z.object;+ return objectOf({+ id: z.string().min(3).max(LIMITS.id).regex(ID),+ kind: z.enum(ANNOUNCEMENT_KINDS),+ label: text(LIMITS.label, strict).optional(),+ title: text(LIMITS.title, strict),+ body: text(LIMITS.body, strict, true),+ // An install shows a card whose picture it cannot read without it; CI refuses the picture.+ image: strict ? imageSchema(objectOf, strict).optional() : z.unknown().optional(),+ primary: buttonSchema(objectOf, strict),+ secondary: buttonSchema(objectOf, strict).optional(),+ starts: z.iso.datetime({ offset: true }).optional(),+ ends: z.iso.datetime({ offset: true }),+ audience: audienceSchema(strict).optional(),+ }).refine((card) => card.starts === undefined || Date.parse(card.starts) < Date.parse(card.ends), "ends must be after starts");+}++const strictCard = cardSchema(true);+const lenientCard = cardSchema(false);+const lenientImage = imageSchema(z.object, false);++export type AnnouncementImage = { url: string; alt?: AnnouncementText } | { mark: AnnouncementMark };+export type AnnouncementCard = Omit<z.infer<typeof lenientCard>, "image" | "audience"> & {+ image?: AnnouncementImage;+ audience?: Record<string, unknown>;+};++function feedSchema(strict: boolean, nowMs: number) {+ const objectOf = strict ? (z.strictObject as unknown as ObjectOf) : z.object;+ return objectOf({+ $schema: z.string().max(200).optional(),+ version: z.literal(1),+ updatedAt: z.iso.datetime({ offset: true }).refine((value) => Date.parse(value) <= nowMs + FUTURE_TOLERANCE_MS, "updatedAt is in the future"),+ cards: strict ? z.array(z.unknown()).max(MAX_CARDS) : z.array(z.unknown()),+ });+}++/** For the JSON Schema beside the file (announcements.schema.json), which editors read. CI keeps the two equal. */+export function announcementsJsonSchema(): unknown {+ const feed = z.strictObject({+ $schema: z.string().max(200).optional(),+ version: z.literal(1),+ updatedAt: z.iso.datetime({ offset: true }),+ cards: z.array(strictCard).max(MAX_CARDS),+ });+ return z.toJSONSchema(feed, { target: "draft-2020-12", unrepresentable: "any" });+}++export interface AnnouncementFeed {+ version: 1;+ updatedAt: string;+ cards: AnnouncementCard[];+}++export type FeedResult =+ | { ok: true; feed: AnnouncementFeed; skipped: string[] }+ | { ok: false; error: string };++function issue(error: z.ZodError, where: string): string {+ const first = error.issues[0]!;+ return `${[where, ...first.path].filter((part) => part !== "").join(".")}: ${first.message}`;+}++/** One card, or why it was skipped. */+export function parseAnnouncementCard(value: unknown, options: { strict?: boolean } = {}): { ok: true; card: AnnouncementCard } | { ok: false; error: string } {+ const parsed = (options.strict ? strictCard : lenientCard).safeParse(value);+ if (!parsed.success) return { ok: false, error: issue(parsed.error, "card") };+ const { image, ...card } = parsed.data as z.infer<typeof lenientCard>;+ const picture = image === undefined ? undefined : lenientImage.safeParse(image);+ return { ok: true, card: { ...card, ...(picture?.success ? { image: picture.data as AnnouncementImage } : {}) } as AnnouncementCard };+}++/**+ * The whole file. A file whose outer shape is wrong is refused, so the last good copy stays. Read leniently, a card+ * that does not parse, or repeats an earlier card's id, is skipped and named in `skipped`, and only the first MAX_CARDS+ * are read; `strict` refuses the file for any of those instead.+ */+export function parseAnnouncementFeed(value: unknown, options: { strict?: boolean; nowMs?: number } = {}): FeedResult {+ const strict = options.strict === true;+ const outer = feedSchema(strict, options.nowMs ?? Date.now()).safeParse(value);+ if (!outer.success) return { ok: false, error: issue(outer.error, "") || "feed" };+ const cards: AnnouncementCard[] = [];+ const skipped: string[] = [];+ const ids = new Set<string>();+ for (const [index, raw] of outer.data.cards.slice(0, MAX_CARDS).entries()) {+ const parsed = parseAnnouncementCard(raw, { strict });+ const problem = !parsed.ok ? parsed.error : ids.has(parsed.card.id) ? `card: the id ${parsed.card.id} is used twice` : null;+ if (problem) {+ if (strict) return { ok: false, error: `cards.${index} ${problem}` };+ skipped.push(`cards.${index} ${problem}`);+ continue;+ }+ if (parsed.ok) {+ ids.add(parsed.card.id);+ cards.push(parsed.card);+ }+ }+ return { ok: true, feed: { version: 1, updatedAt: outer.data.updatedAt, cards }, skipped };+}++/** Cards whose time has not passed, as a server hands them to its pages. */+export function liveCards(cards: readonly AnnouncementCard[], nowMs: number): AnnouncementCard[] {+ return cards.filter((card) => Date.parse(card.ends) > nowMs);+}++/** A text in `locale`, or its language without the region, or English. */+export function localized(value: AnnouncementText, locale: string): string {+ if (typeof value === "string") return value;+ const tag = locale.toLowerCase();+ return value[tag] ?? value[tag.split("-")[0]!] ?? value.en ?? "";+}++function versionParts(value: string): [number, number, number] | null {+ const match = /^(\d{1,6})\.(\d{1,6})\.(\d{1,6})(?:[-+].*)?$/.exec(value.trim());+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;+}++export function compareVersions(a: string, b: string): number | null {+ const left = versionParts(a), right = versionParts(b);+ if (!left || !right) return null;+ for (let i = 0; i < 3; i++) if (left[i] !== right[i]) return left[i]! < right[i]! ? -1 : 1;+ return 0;+}++/** What the app knows of the person and this page. `plan` is null while it is being read and undefined where this page+ * cannot know it; `platform` null when the browser does not say. */+export interface AnnouncementFacts {+ nowMs: number;+ version: string;+ platform: AnnouncementPlatform | null;+ surface: AnnouncementSurface;+ plan: AnnouncementPlan | null | undefined;+ people: AnnouncementPeople;+ locale: string;+ conditions: Readonly<Record<AnnouncementCondition, boolean>>;+}++const listed = (value: unknown): string[] | null => Array.isArray(value) && value.every((entry) => typeof entry === "string") ? value : null;++/** True when the card is for these facts; false for an audience this version cannot read (an unknown key, a condition+ * it cannot check); null while a fact it needs is still loading. */+export function audienceMatches(audience: Record<string, unknown> | undefined, facts: AnnouncementFacts): boolean | null {+ if (!audience) return true;+ if (Object.keys(audience).some((key) => !(AUDIENCE_KEYS as readonly string[]).includes(key))) return false;+ const { minVersion, maxVersion, platforms, surfaces, plans, people, languages, when } = audience;+ if (minVersion !== undefined && !((compareVersions(facts.version, String(minVersion)) ?? -1) >= 0)) return false;+ if (maxVersion !== undefined && !((compareVersions(facts.version, String(maxVersion)) ?? 1) <= 0)) return false;+ const check = (value: unknown, fact: string | null | undefined): boolean => {+ const values = listed(value);+ return values !== null && fact !== null && fact !== undefined && values.includes(fact);+ };+ if (platforms !== undefined && !check(platforms, facts.platform)) return false;+ if (surfaces !== undefined && !check(surfaces, facts.surface)) return false;+ if (people !== undefined && people !== facts.people) return false;+ if (languages !== undefined) {+ const values = listed(languages), tag = facts.locale.toLowerCase();+ if (!values?.some((value) => value === tag || value === tag.split("-")[0])) return false;+ }+ if (when !== undefined) {+ const values = listed(when);+ if (!values || values.some((value) => !(ANNOUNCEMENT_CONDITIONS as readonly string[]).includes(value) || !facts.conditions[value as AnnouncementCondition])) return false;+ }+ if (plans !== undefined) {+ if (facts.plan === null) return null;+ if (!check(plans, facts.plan)) return false;+ }+ return true;+}++/** The places a card's buttons open. */+export function cardPlaces(card: AnnouncementCard): AnnouncementPlace[] {+ return [card.primary, card.secondary].flatMap((button) => button && "open" in button.action ? [button.action.open] : []);+}diff --git a/src/components/AnnouncementCard.tsx b/src/components/AnnouncementCard.tsxnew file mode 100644index 0000000000..3dd368000c--- /dev/null+++ b/src/components/AnnouncementCard.tsx@@ -0,0 +1,71 @@+import { useState, type ComponentType } from "react";+import { Lightbulb, Megaphone, Sparkles } from "lucide-react";+import { cn } from "@/lib/cn";+import { activeLocale } from "@/lib/i18n";+import type { Action } from "@/state/store";+import {+ localized, type AnnouncementAction, type AnnouncementCard as Card, type AnnouncementKind, type AnnouncementMark, type AnnouncementPlace,+} from "../../shared/announcements";+import { openKeySettings } from "./keys/key-focus";+import { LinkButton, NoticeCard, NotNowButton, PRIMARY_BUTTON } from "./NoticeCard";+import { ClaudeMark, CodexMark, CopilotMark, DeepSeekMark, GreenferenceMark, GrokMark, KimiMark, KiroMark, ModelgoMark, type IconProps } from "./ProviderIcons";++export type AnnouncementButton = "primary" | "secondary";++const KIND_ICON: Record<AnnouncementKind, ComponentType<IconProps>> = { sponsor: Sparkles, product: Megaphone, tip: Lightbulb };+const MARK: Record<AnnouncementMark, ComponentType<IconProps>> = {+ claude: ClaudeMark, codex: CodexMark, grok: GrokMark, kimi: KimiMark, modelgo: ModelgoMark, greenference: GreenferenceMark,+ deepseek: DeepSeekMark, copilot: CopilotMark, kiro: KiroMark,+};++/** Each place is one the app already opens from its own menus; nothing here navigates the window anywhere. */+export function announcementPlaceAction(place: AnnouncementPlace): Action {+ switch (place) {+ case "api_keys": return openKeySettings();+ case "ai_engines": return { type: "toggleAppSettings", open: true, section: "engines" };+ case "connected_apps": return { type: "togglePlugins", open: true, surface: "apps" };+ case "new_bot": return { type: "newBot" };+ case "my_cloud": return { type: "toggleAppSettings", open: true, section: "cloudAccount" };+ }+}++const SECONDARY_LINK = "inline-flex items-center gap-1 py-2 text-[12px] text-ink-secondary hover:text-ink";++function Button({ label, action, primary, onDone, open }: {+ label: string; action: AnnouncementAction; primary: boolean; onDone: () => void; open: (place: AnnouncementPlace) => void;+}) {+ const className = primary ? cn(PRIMARY_BUTTON, "w-full") : SECONDARY_LINK;+ // An external page opens the way every notice's link does: the system browser on the desktop, a new tab with no+ // opener or referrer in a browser. The address is the file's, with nothing added.+ if ("open_url" in action) return <LinkButton url={action.open_url} label={label} className={className} onOpened={onDone} />;+ return <button type="button" className={className} onClick={() => { onDone(); open(action.open); }}>{label}</button>;+}++/** A card from the announcements file, drawn as every corner notice is. Its words are plain text: nothing in the file is+ * read as markup. A picture is a file in the repository's announcements/ folder, fetched with no cookie or referrer and+ * held to the card's width and 120 pixels high; one that fails to load leaves the card without it. */+export function AnnouncementCard({ card, onDone, open, locale = activeLocale() }: {+ card: Card;+ onDone: (action: "primary" | "secondary" | "close") => void;+ open: (place: AnnouncementPlace) => void;+ locale?: string;+}) {+ const [pictureFailed, setPictureFailed] = useState(false);+ const say = (text: Card["title"]) => localized(text, locale);+ const image = card.image;+ const Icon = image && "mark" in image ? MARK[image.mark] : KIND_ICON[card.kind];+ const titleId = `announcement-${card.id}-title`;+ return <NoticeCard titleId={titleId} notice="announcement" icon={Icon} title={say(card.title)} onDismiss={() => onDone("close")}>+ {card.label && <p data-announcement-label className="mt-1 text-[11px] font-medium uppercase leading-4 tracking-wide text-ink-tertiary">{say(card.label)}</p>}+ {image && "url" in image && !pictureFailed && <img src={image.url} alt={image.alt ? say(image.alt) : ""} loading="lazy" decoding="async"+ referrerPolicy="no-referrer" crossOrigin="anonymous" draggable={false} onError={() => setPictureFailed(true)}+ className="mt-2 block h-auto max-h-[120px] w-full rounded-lg object-cover" />}+ <p className="mt-1 whitespace-pre-line break-words text-[13px] leading-[18px] text-ink-secondary">{say(card.body)}</p>+ <div className="mt-3 flex flex-col gap-2">+ <Button label={say(card.primary.label)} action={card.primary.action} primary onDone={() => onDone("primary")} open={open} />+ {card.secondary+ ? <Button label={say(card.secondary.label)} action={card.secondary.action} primary={false} onDone={() => onDone("secondary")} open={open} />+ : <NotNowButton onClick={() => onDone("close")} />}+ </div>+ </NoticeCard>;+}diff --git a/src/components/AppNotices.test.ts b/src/components/AppNotices.test.tsindex ed96a8ab1a..f6906e7001 100644--- a/src/components/AppNotices.test.ts+++ b/src/components/AppNotices.test.ts@@ -45,6 +45,7 @@ import { ADVANCED_MODE_KEY, setAdvancedMode } from "@/lib/interface-mode";import { SIMPLE_MODE_PROMPT_KEY } from "@/lib/simple-mode-prompt";import { ADVANCED_BACK_KEY } from "@/lib/new-look";import { api } from "@/state/store";+import { forgetAnnouncementCards, seenKey } from "@/lib/announcements";const DAY = 86_400_000, NOW = new Date(2026, 9, 9, 12).getTime();const plans = [@@ -140,6 +141,8 @@ const launchCardsSeen = () => { desk.saved = { seen: [WHATS_NEW_NOTICE] }; storaconst hints = () => f.state.config.onboarding.hintsSeen as string[];beforeEach(() => {+ // The page's announcement cards live beside the component for the session; no test inherits another's.+ forgetAnnouncementCards();vi.clearAllMocks(); vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });storage = new Map(); f.values = []; f.index = 0; f.effects = []; f.updater = null; f.brand = "default"; f.dispatch = vi.fn(); now = NOW; desk = desktopMachine();setLocale("en"); viewer = LOCAL_VIEWER; account = signedOut; snapshot = { status: "none" }; offer = TRIAL_OFFER;@@ -1532,6 +1535,165 @@ describe("ModelGo's sponsor card", () => {});+describe("cards from the announcements file", () => {+ const card = (id: string, extra: Record<string, unknown> = {}) => ({ id, kind: "product", label: "New", title: `Title of ${id}`, body: `Body of ${id}.`,+ primary: { label: `Open ${id}`, action: { open_url: `https://example.com/${id}` } }, ends: new Date(NOW + 30 * DAY).toISOString(), ...extra });+ let feed: unknown[];+ const events = () => vi.mocked(track).mock.calls.filter(([name]) => name === "announcement").map(([, props]) => props);+ beforeEach(() => {+ forgetAnnouncementCards(); feed = [card("phone-app")];+ const config = vi.mocked(api).getMockImplementation()!;+ vi.mocked(api).mockImplementation(async (path, init) => path === "/api/announcements" ? { cards: feed } : config(path, init));+ });++ it("shows the first card for this person as a corner card: its label, title, body and button, and Not now", async () => {+ const shown = await launch();+ for (const text of ["New", "Title of phone-app", "Body of phone-app.", "Open phone-app", "Not now"]) expect(shown).toContain(text);+ expect(shown).toContain('data-notice="announcement"'); expect(shown).not.toContain('aria-modal="true"');+ expect(events()).toEqual([{ id: "phone-app", kind: "product", action: "shown" }]);+ expect(await settle()).toContain("Title of phone-app");+ expect(events(), "one shown event, however often it draws").toHaveLength(1);+ });++ it("its button opens the file's address outside the app, as it is, and the card is gone for good on every record", async () => {+ await launch(); press("Open phone-app"); await flush();+ expect(window.ogb!.openExternal).toHaveBeenCalledWith("https://example.com/phone-app");+ expect(events().at(-1)).toEqual({ id: "phone-app", kind: "product", action: "primary" });+ expect(render()).toBe("");+ expect(storage.get(seenKey("phone-app"))).toBe("1"); expect(hints()).toContain(seenKey("phone-app")); expect(desk.saved?.seen).toContain(seenKey("phone-app"));+ expect(await relaunch()).not.toContain("Title of phone-app");+ });++ it("a button for one of the app's places opens it in the app, and only that", async () => {+ feed = [card("keys-tip", { kind: "tip", primary: { label: "Open API keys", action: { open: "api_keys" } }, secondary: { label: "Connect apps", action: { open: "connected_apps" } } })];+ expect(await launch()).not.toContain("Not now");+ press("Connect apps");+ expect(f.dispatch).toHaveBeenCalledWith({ type: "togglePlugins", open: true, surface: "apps" });+ expect(events().at(-1)).toEqual({ id: "keys-tip", kind: "tip", action: "secondary" });+ expect(window.ogb!.openExternal).not.toHaveBeenCalled();+ });++ it("one card a launch: the next waits for the next launch", async () => {+ feed = [card("first-card"), card("second-card")];+ await launch(); press("Not now"); await flush();+ expect(events().at(-1)).toEqual({ id: "first-card", kind: "product", action: "close" });+ expect(await settle(), "the same page").toBe("");+ expect(await launch(), "the same launch").toBe("");+ expect(await relaunch()).toContain("Title of second-card");+ });++ it("follows the built-in sponsor card in its launch once that closes, never beside it", async () => {+ storage.delete(MODELGO_OFFER_NOTICE);+ const first = await launch();+ expect(first).toContain("ModelGo"); expect(first).not.toContain("Title of phone-app");+ press("Not now"); await flush();+ const after = await settle();+ expect(after).toContain("Title of phone-app"); expect(after).not.toContain("ModelGo");+ expect(launchNotice()).toBe(MODELGO_OFFER_NOTICE);+ });++ it("follows a closed What's new in the same launch, then no other remote card that launch", async () => {+ feed = [card("first-card"), card("second-card")];+ returning(); desk.saved = null; storage.delete(WHATS_NEW_NOTICE); storage.set(CLOUD_INTRO, "1");+ const popup = await launch();+ expect(popup).toContain("Meet the new MausBot Cloud"); expect(popup, "never two at once").not.toContain("Title of first-card");+ expect(events()).toEqual([]);+ press("Not now"); await flush();+ const after = await settle();+ expect(after, "right after What's new closes").toContain("Title of first-card"); expect(after).not.toContain("Meet the new MausBot Cloud");+ expect(launchNotice(), "What's new keeps the launch").toBe(WHATS_NEW_NOTICE);+ expect(await launch(), "a reload in the same launch").toContain("Title of first-card");+ press("Not now"); await flush();+ expect(await settle(), "one remote card a launch").toBe("");+ expect(await launch(), "nor after a reload").toBe("");+ expect(await relaunch()).toContain("Title of second-card");+ });++ it("never over a notice to act on: the move popup keeps the corner, and the card follows it once closed", async () => {+ storage.delete(GROK_MOVE_NOTICE); returning();+ vi.stubGlobal("document", { activeElement: null, body: null, documentElement: { dataset: {} }, getElementById: () => null,+ querySelector: (selector: string) => selector === "[data-grok-move-popup]" ? { querySelectorAll: () => [] } : null, querySelectorAll: () => [] });+ const grok = await launch();+ expect(grok).toContain("data-grok-move-popup"); expect(grok).not.toContain("Title of phone-app");+ expect(await settle(), "it stays up alone").not.toContain("Title of phone-app");+ press("Not now"); await flush();+ expect(await settle(), "after the move's popup").toContain("Title of phone-app");+ });++ it("a card left up keeps the corner: a card that arrives meanwhile waits for it to close", async () => {+ returning(); storage.delete(STAR_NOTICE); storage.set(CLOUD_INTRO, "1"); feed = [];+ expect(await launch()).toContain("Enjoying MausBot?");+ feed = [card("phone-app")]; forgetAnnouncementCards();+ const still = await settle();+ expect(still, "the star took the launch and is still up").toContain("Enjoying MausBot?"); expect(still).not.toContain("Title of phone-app");+ press("Not now"); await flush();+ expect(await settle()).toContain("Title of phone-app");+ });++ it("not after another remote card in the same launch, even with a third card due", async () => {+ feed = [card("first-card"), card("second-card"), card("third-card")];+ expect(await launch()).toContain("Title of first-card");+ expect(launchNotice()).toBe("announcement");+ press("Not now"); await flush();+ expect(await settle()).toBe("");+ expect(await launch(), "a reload").toBe("");+ });++ it("never in the launch the welcome took, nor over a live call", async () => {+ f.state.liveCall = { status: "active" };+ expect(await launch()).not.toContain("Title of phone-app");+ f.state.liveCall = undefined; session.clear(); markWelcomeFinished();+ expect(await launch()).not.toContain("Title of phone-app");+ });++ it("its words are text: markup in the file shows as written and runs nothing", async () => {+ feed = [card("markup", { body: "<img src=x onerror=alert(1)><b>bold</b>" })];+ const shown = await launch();+ expect(shown).toContain("<img src=x onerror=alert(1)><b>bold</b>");+ expect(shown).not.toContain("<b>");+ });++ it("follows the person's language, falling back to English", async () => {+ feed = [card("translated", { title: { en: "English title", de: "Deutscher Titel" } })];+ setLocale("de");+ expect(await launch()).toContain("Deutscher Titel");+ });++ it("skips a card for someone else and a card it cannot read, and shows nothing on a branded build", async () => {+ feed = [card("cloud-only", { audience: { surfaces: ["cloud"] } }), card("future-key", { audience: { country: ["de"] } }), card("broken", { primary: { label: "Go", action: { eval: "x" } } }), card("for-desktop")];+ expect(await launch()).toContain("Title of for-desktop");+ f.brand = "file"; forgetAnnouncementCards(); storage.set(seenKey("for-desktop"), "1"); feed = [card("branded")];+ expect(await relaunch()).not.toContain("Title of branded");+ });++ describe("a sponsor's card", () => {+ const sponsor = (id: string) => card(id, { kind: "sponsor", label: "Sponsor" });++ it("one a week: a second sponsor waits while a product card may show", async () => {+ feed = [sponsor("sponsor-one"), sponsor("sponsor-two"), card("product-news")];+ expect(await launch()).toContain("Title of sponsor-one");+ press("Not now"); await flush();+ expect(await relaunch()).toContain("Title of product-news");+ press("Not now"); await flush();+ expect(await relaunch()).toBe("");+ now += 7 * DAY;+ expect(await relaunch()).toContain("Title of sponsor-two");+ });++ it("never where an organization restricts providers, nor to a Team Cloud's members who are not its owner or an admin", async () => {+ feed = [sponsor("sponsor-one"), card("product-news")];+ f.state.config.managedPolicy = { organizationName: "Acme", companyModelsOnly: false, allowedEngines: ["claudeAgent"] };+ expect(await launch()).toContain("Title of product-news");+ f.state.config.managedPolicy = undefined; storage.set(seenKey("product-news"), "1");+ viewer = { hosted: true, canSave: false, cloudHome: true }; f.state.config.cloudHome = true; f.state.config.team = { id: "t", name: "Team" };+ f.state.config.onboarding.hintsSeen = [...withTourFinished(undefined), "cloud-setup-hidden"]; showWindow(VPS);+ expect(await relaunch(), "a member").toBe("");+ viewer = { hosted: true, canSave: true, cloudHome: true };+ expect(await relaunch(), "the team's owner or an admin").toContain("Title of sponsor-one");+ });+ });+});+describe("Update MausBot on your phone", () => {const TITLE = "Update MausBot on your phone", MODELGO = "ModelGo is now in MausBot";const OLD = { id: "0f8c2a41-1111-4222-8333-444455556666", name: "Ada's iPhone", createdAt: 1, lastSeenAt: 1, cloudDesktopAccess: false };diff --git a/src/components/AppNotices.tsx b/src/components/AppNotices.tsxindex fea2d845e8..c7c47fbace 100644--- a/src/components/AppNotices.tsx+++ b/src/components/AppNotices.tsx@@ -3,8 +3,10 @@ import { Rocket, Star } from "lucide-react";import type { CloudAccountState } from "../../electron/cloud-account.mjs";import type { CloudOffer } from "../../electron/cloud-home.mjs";import { api, useStore } from "@/state/store";-import { APP_REPOSITORY } from "@/lib/app-links";+import { APP_REPOSITORY, appVersion } from "@/lib/app-links";import { track } from "@/lib/analytics";+import { announcementConditions, announcementPlan, announcementPlatform, announcementSurface, markLaunchAnnouncement, pickAnnouncement, providersRestricted, rememberCardSeen, rememberSponsorDay,+ reportAnnouncement, SPONSOR_CARDS_FOR_TEAM_MEMBERS, useAnnouncementCards, type SeenRecord } from "@/lib/announcements";import { boatOfferRuns } from "@/lib/boat-offer";import { modelgoOfferable, reportModelgoOffer } from "@/lib/modelgo-offer";import { brandStatus } from "@/lib/brand";@@ -12,7 +14,7 @@ import { buyOfferAllowed, cloudNoticeKind, cloudPlanView, cloudTrialNotice, clouimport { jobRoutine, useCloudIntent } from "@/lib/cloud-intent";import { CLOUD_INTENT_GIVEN, cloudSetupStage } from "@/lib/cloud-setup";import { cornerPopupWaits, firstChatQuiet, firstReplyPending } from "@/lib/corner-popup";-import { BOAT_OFFER_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, markLaunchNotice, MODELGO_OFFER_NOTICE, nextNotice, noticeSeen, PHONE_UPDATE_NOTICE, phoneUpdateHint, PRODUCT_HUNT_NOTICE, PRODUCT_HUNT_UNTIL, PRODUCT_HUNT_URL, SIMPLE_MODE_NOTICE, STAR_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE } from "@/lib/notices";+import { ANNOUNCEMENT_NOTICE, BOAT_OFFER_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, markLaunchNotice, MODELGO_OFFER_NOTICE, nextNotice, noticeSeen, PHONE_UPDATE_NOTICE, phoneUpdateHint, PRODUCT_HUNT_NOTICE, PRODUCT_HUNT_UNTIL, PRODUCT_HUNT_URL, SIMPLE_MODE_NOTICE, STAR_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE } from "@/lib/notices";import { useTwoPlaces } from "@/lib/two-places";import { SIMPLE_ONLY } from "@/lib/simple-only";import { useAdvancedBackDue, useNewLookDue } from "@/lib/new-look";@@ -23,7 +25,8 @@ import { cloudSignInDue, onboardingCloudOffered, welcomeFinishedThisLaunch, typeimport { launchDialogShown, markLaunchDialog } from "@/lib/launch-dialogs";import { useUpdaterState } from "@/lib/updater";import { phonePairingSettingsAction } from "@/lib/phone-pairing";-import { t } from "@/lib/i18n";+import { activeLocale, t } from "@/lib/i18n";+import { AnnouncementCard, announcementPlaceAction } from "./AnnouncementCard";import { BoatOfferCard, reportBoatOffer, type BoatOfferAction } from "./BoatOffer";import { engineReady } from "./EngineLibrary";import { ModelgoOfferCard, type ModelgoCardAction } from "./ModelgoOffer";@@ -91,6 +94,7 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { qconst [simpleShown, setSimpleShown] = useState(false);const [boatShown, setBoatShown] = useState(false);const [modelgoShown, setModelgoShown] = useState(false);+ const [announcementShown, setAnnouncementShown] = useState<string | null>(null);const [grokShown, setGrokShown] = useState(false);const [grokOpen, setGrokOpen] = useState(false);const [grokLanded, setGrokLanded] = useState(false);@@ -207,6 +211,23 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { q// the welcome or MausBot's card took, or during a live call.const modelgoNow = !modelgoHere || moving || welcomeFinishedThisLaunch() || launchDialogShown() === "mausbot" || desktopState?.seen.includes(MODELGO_OFFER_NOTICE) ? false: organization === null || moving === null || firstChat === null || mausBotFirst || (state.liveCall && state.liveCall.status !== "ended") || (desktop && !desktopState) ? null : true;+ // A card from the project's announcements file: the built-in sponsor card's exclusions, and src/lib/announcements.ts's rules for+ // which card and for whom (once per person, one sponsor card a week, none on a branded build).+ const branded = brandStatus().source === "file", team = Boolean(state.config?.team);+ const remoteCards = useAnnouncementCards(!branded);+ const surface = announcementSurface(local, Boolean(state.config?.cloudHome || viewer?.cloudHome));+ const seenRecord: SeenRecord = { record, desktop: desktopState?.seen ?? [], team };+ const picked = remoteCards.length === 0 ? null : pickAnnouncement(remoteCards, {+ facts: { nowMs: now(), version: appVersion(), platform: announcementPlatform(globalThis.navigator?.userAgent), surface, plan: announcementPlan(surface, view, team),+ people: usedBefore(state.bots) ? "existing" : "new", locale: activeLocale(), conditions: announcementConditions(state) },+ seen: seenRecord, branded, admin: viewer?.canSave !== false,+ sponsors: !providersRestricted(state.config?.managedPolicy) && (SPONSOR_CARDS_FOR_TEAM_MEMBERS || !team || viewer?.canSave === true),+ });+ const announcement = picked && picked !== "wait" ? picked : null;+ const announcementNow = !picked || moving || welcomeFinishedThisLaunch() || launchDialogShown() === "mausbot" ? false+ : picked === "wait" || !viewer || organization === null || moving === null || firstChat === null || mausBotFirst || (state.liveCall && state.liveCall.status !== "ended") || (desktop && !desktopState) ? null : true;+ const remembering = { desktop, liveIds: new Set(remoteCards.map(card => card.id)), save: (hintsSeen: string[]) => void api("/api/config", { method: "PUT", body: JSON.stringify({ onboarding: { hintsSeen } }) })+ .then(config => dispatch({ type: "configStatus", config })).catch(() => {}) };const retiredPhones = phonesToTell(linkPhones, record);const phoneNow = retiredPhones?.length === 0 ? false: retiredPhones === undefined || !viewer || mausBotFirst || (state.liveCall && state.liveCall.status !== "ended") ? null : true;@@ -215,7 +236,7 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { q// FOLLOWERS); nothing else does.const notice = waits ? null: firstChatQuiet(state) ? (grokNow === true && (launch === null || launch === GROK_MOVE_NOTICE) ? GROK_MOVE_NOTICE : null)- : cards || whatsNewHere || consentHere || simpleDue || boatHere || modelgoHere || twoFact !== false || grokNow !== false || phoneNow !== false ? nextNotice({+ : cards || whatsNewHere || consentHere || simpleDue || boatHere || modelgoHere || announcementNow !== false || twoFact !== false || grokNow !== false || phoneNow !== false ? nextNotice({[GROK_MOVE_NOTICE]: grokNow,[PHONE_UPDATE_NOTICE]: phoneNow,// As the What's new popup: never in the launch whose welcome just finished, nor over MausBot's first-launch card.@@ -233,11 +254,12 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { q[MODELGO_OFFER_NOTICE]: modelgoNow,[BOAT_OFFER_NOTICE]: !boatHere || moving || afterWelcome === true || !usedBefore(state.bots) || desktopState?.seen.includes(BOAT_OFFER_NOTICE) ? false: organization === null || moving === null || afterWelcome === null || mausBotFirst || (desktop && !desktopState) ? null : !organization,+ [ANNOUNCEMENT_NOTICE]: announcementNow,[STAR_NOTICE]: !bridge || moving || brandStatus().source === "file" || !usedBefore(state.bots) ? false : moving === null ? null : true,}, id => id === CLOUD_INTRO ? stage === "done" && !introOpen: id === STAR_NOTICE || id === PRODUCT_HUNT_NOTICE || id === BOAT_OFFER_NOTICE || id === MODELGO_OFFER_NOTICE ? noticeSeen(record, id) : false, launch, closed) : null;- const shownKey = notice === CLOUD_TRIAL_NOTICE ? key : notice;+ const shownKey = notice === CLOUD_TRIAL_NOTICE ? key : notice === ANNOUNCEMENT_NOTICE ? `${notice}:${announcement?.id}` : notice;useEffect(() => {if (!shownKey || !notice) return;markLaunchNotice(notice);@@ -261,6 +283,11 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { q} else if (shownKey === MODELGO_OFFER_NOTICE && !modelgoShown) {setModelgoShown(true);reportModelgoOffer("shown", "popup");+ } else if (notice === ANNOUNCEMENT_NOTICE && announcement && announcementShown !== announcement.id) {+ setAnnouncementShown(announcement.id);+ markLaunchAnnouncement(announcement.id);+ reportAnnouncement(announcement, "shown");+ if (announcement.kind === "sponsor") rememberSponsorDay(seenRecord, now(), remembering);} else if (shownKey === GROK_MOVE_NOTICE && !grokShown) {setGrokShown(true);reportGrokMovePopup("shown");@@ -353,6 +380,12 @@ export function AppNotices({ quiet = false, viewer = null, now = Date.now }: { q};return <ModelgoOfferCard onDone={done} />;}+ if (notice === ANNOUNCEMENT_NOTICE && announcement) {+ const done = (action: "primary" | "secondary" | "close") => {+ reportAnnouncement(announcement, action); close(); rememberCardSeen(seenRecord, announcement.id, remembering);+ };+ return <AnnouncementCard key={announcement.id} card={announcement} onDone={done} open={place => dispatch(announcementPlaceAction(place))} />;+ }if (notice === STAR_NOTICE) return <StarCard onDismiss={() => { close(); save(STAR_NOTICE); }} />;return null;}diff --git a/src/lib/announcements.test.ts b/src/lib/announcements.test.tsnew file mode 100644index 0000000000..dfdd0d616a--- /dev/null+++ b/src/lib/announcements.test.ts@@ -0,0 +1,186 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { EMPTY_ONBOARDING, type OnboardingStatus } from "@/lib/onboarding";+import { localeChoices } from "@/locales";+import { ANNOUNCEMENT_LOCALES, parseAnnouncementCard, type AnnouncementCard, type AnnouncementFacts } from "../../shared/announcements";++vi.mock("@/lib/analytics", () => ({ track: vi.fn(), emailGateDone: () => true }));+vi.mock("@/state/store", () => ({ api: vi.fn() }));+import { track } from "@/lib/analytics";+import {+ announcementConditions, announcementPlan, announcementPlatform, announcementSurface, cardSeen, hintsWith, lastSponsorDay, launchAnnouncement, markLaunchAnnouncement,+ pickAnnouncement, providersRestricted, rememberCardSeen, rememberSponsorDay, reportAnnouncement, seenKey, SPONSOR_CARDS_FOR_TEAM_MEMBERS, SPONSOR_REST_DAYS,+ sponsorDayKey, type PickContext, type SeenRecord,+} from "./announcements";++const DAY = 86_400_000, NOW = new Date(2026, 11, 1, 12).getTime();+let storage: Map<string, string>, session: Map<string, string>;+beforeEach(() => {+ storage = new Map(); session = new Map();+ vi.stubGlobal("localStorage", { getItem: (key: string) => storage.get(key) ?? null, setItem: (key: string, value: string) => storage.set(key, value) });+ vi.stubGlobal("sessionStorage", { getItem: (key: string) => session.get(key) ?? null, setItem: (key: string, value: string) => session.set(key, value) });+});+afterEach(() => { vi.unstubAllGlobals(); vi.mocked(track).mockClear(); });++const make = (id: string, extra: Record<string, unknown> = {}): AnnouncementCard => {+ const parsed = parseAnnouncementCard({ id, kind: "product", title: "T", body: "B", primary: { label: "Go", action: { open_url: "https://example.com/" } }, ends: "2027-01-01T00:00:00Z", ...extra });+ if (!parsed.ok) throw new Error(parsed.error);+ return parsed.card;+};+const record = (hintsSeen: string[] = []): OnboardingStatus => ({ ...EMPTY_ONBOARDING, completedAt: "2026-09-01", version: 1, hintsSeen });+const facts = (extra: Partial<AnnouncementFacts> = {}): AnnouncementFacts => ({+ nowMs: NOW, version: "0.1.160", platform: "mac", surface: "desktop", plan: "none", people: "existing", locale: "en",+ conditions: { no_api_key: false, one_bot_only: false, no_routine: false }, ...extra,+});+const seen = (extra: Partial<SeenRecord> = {}): SeenRecord => ({ record: record(), desktop: [], team: false, ...extra });+const context = (extra: Partial<PickContext> = {}): PickContext => ({ facts: facts(), seen: seen(), branded: false, sponsors: true, admin: true, ...extra });+const pick = (cards: AnnouncementCard[], extra: Partial<PickContext> = {}) => { const due = pickAnnouncement(cards, context(extra)); return due && due !== "wait" ? due.id : due; };++describe("which card is due", () => {+ it("the first in file order that is for this person", () => {+ expect(pick([make("card-a", { audience: { surfaces: ["cloud"] } }), make("card-b"), make("card-c")])).toBe("card-b");+ expect(pick([])).toBeNull();+ });++ it("only between its start and its end, by this page's clock", () => {+ expect(pick([make("later", { starts: new Date(NOW + DAY).toISOString() })])).toBeNull();+ expect(pick([make("over", { ends: new Date(NOW - 1).toISOString() })])).toBeNull();+ expect(pick([make("now", { starts: new Date(NOW - DAY).toISOString() })])).toBe("now");+ });++ it("once per person: this browser, this desktop or the workspace's record", () => {+ const cards = [make("card-a"), make("card-b")];+ storage.set(seenKey("card-a"), "1");+ expect(pick(cards)).toBe("card-b");+ expect(pick(cards, { seen: seen({ desktop: [seenKey("card-b")] }) })).toBeNull();+ storage.clear();+ expect(pick(cards, { seen: seen({ record: record([seenKey("card-a")]) }) })).toBe("card-b");+ expect(pick(cards, { seen: seen({ record: record([seenKey("card-a")]), team: true }) }), "a Team Cloud's record is the team's, not the person's").toBe("card-a");+ });++ it("at most one remote card in a launch: the one it showed, until it is closed", () => {+ const cards = [make("card-a"), make("card-b")];+ markLaunchAnnouncement("card-b");+ expect(launchAnnouncement()).toBe("card-b");+ expect(pick(cards), "a reload shows the same card").toBe("card-b");+ storage.set(seenKey("card-b"), "1");+ expect(pick(cards), "closed: nothing else this launch").toBeNull();+ session.clear();+ expect(pick(cards), "the next launch").toBe("card-a");+ });++ it("none on a branded build", () => {+ expect(pick([make("card-a", { kind: "tip" }), make("card-b", { kind: "sponsor" })], { branded: true })).toBeNull();+ });++ it("a sponsor's card only where sponsors may show, and one a week", () => {+ const cards = [make("sponsor-one", { kind: "sponsor" }), make("product")];+ expect(pick(cards)).toBe("sponsor-one");+ expect(pick(cards, { sponsors: false })).toBe("product");+ storage.set("omb.announcement.sponsor-day", new Date(NOW - 3 * DAY).toISOString().slice(0, 10));+ expect(pick(cards), "a sponsor's card three days ago").toBe("product");+ storage.clear();+ expect(pick(cards, { seen: seen({ desktop: [sponsorDayKey("2026-11-29")] }) })).toBe("product");+ expect(pick(cards, { seen: seen({ record: record([sponsorDayKey("2026-11-20")]) }) }), `${SPONSOR_REST_DAYS} days on`).toBe("sponsor-one");+ expect(SPONSOR_CARDS_FOR_TEAM_MEMBERS).toBe(false);+ });++ it("a card that opens an admin's place skips someone who cannot change settings here", () => {+ const keys = make("keys", { primary: { label: "Keys", action: { open: "api_keys" } } });+ const apps = make("apps", { primary: { label: "Apps", action: { open: "connected_apps" } } });+ expect(pick([keys, apps], { admin: false })).toBe("apps");+ expect(pick([keys, apps])).toBe("keys");+ });++ it("waits while a fact the first candidate needs is read, and skips a card it cannot read the audience of", () => {+ expect(pickAnnouncement([make("plan", { audience: { plans: ["cloud"] } }), make("card-b")], context({ facts: facts({ plan: null }) }))).toBe("wait");+ expect(pick([make("future", { audience: { countries: ["de"] } }), make("card-b")])).toBe("card-b");+ });+});++describe("remembering", () => {+ it("a closed card in this browser, on this desktop and in the workspace record", () => {+ const desktop = { seen: vi.fn(async () => {}) }, save = vi.fn();+ rememberCardSeen(seen(), "card-a", { desktop, liveIds: new Set(["card-a"]), save });+ expect(storage.get(seenKey("card-a"))).toBe("1");+ expect(desktop.seen).toHaveBeenCalledWith(seenKey("card-a"));+ expect(save).toHaveBeenCalledWith([seenKey("card-a")]);+ expect(cardSeen(seen(), "card-a")).toBe(true);+ });++ it("never in a Team Cloud's record, which is the whole team's", () => {+ const save = vi.fn();+ rememberCardSeen(seen({ team: true }), "card-a", { liveIds: new Set(["card-a"]), save });+ expect(save).not.toHaveBeenCalled();+ expect(storage.get(seenKey("card-a"))).toBe("1");+ });++ it("the day a sponsor's card showed, replacing the last one", () => {+ const save = vi.fn();+ rememberSponsorDay(seen({ record: record(["tour", sponsorDayKey("2026-10-01")]) }), NOW, { liveIds: new Set(), save });+ expect(save).toHaveBeenCalledWith(["tour", sponsorDayKey("2026-12-01")]);+ expect(lastSponsorDay(seen())).toBe("2026-12-01");+ });++ it("keeps the workspace record small: marks of cards gone from the feed leave, at most ten stay, and a full record is left alone", () => {+ const marks = Array.from({ length: 12 }, (_, index) => seenKey(`card-${index}`));+ const live = new Set([...marks.map((mark) => mark.slice("announcement:".length)), "new-card"]);+ const next = hintsWith(record(["tour", seenKey("gone"), ...marks]), seenKey("new-card"), live)!;+ expect(next).not.toContain(seenKey("gone"));+ expect(next.filter((hint) => hint.startsWith("announcement:"))).toHaveLength(10);+ expect(next.at(-1)).toBe(seenKey("new-card"));+ expect(next[0]).toBe("tour");+ expect(hintsWith(record(Array.from({ length: 100 }, (_, index) => `hint-${index}`)), seenKey("x"), new Set(["x"]))).toBeNull();+ expect(hintsWith(record([seenKey("x")]), seenKey("x"), new Set(["x"]))).toBeNull();+ expect(seenKey("x".repeat(40)).length, "fits the record's 60 characters").toBeLessThanOrEqual(60);+ });+});++describe("what the page knows", () => {+ it("the platform from the browser", () => {+ expect(announcementPlatform("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36")).toBe("mac");+ expect(announcementPlatform("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")).toBe("windows");+ expect(announcementPlatform("Mozilla/5.0 (X11; Linux x86_64)")).toBe("linux");+ expect(announcementPlatform("Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)")).toBe("ios");+ expect(announcementPlatform("Mozilla/5.0 (Linux; Android 15)")).toBe("android");+ expect(announcementPlatform(undefined)).toBeNull();+ });++ it("the surface and the plan", () => {+ expect(announcementSurface(true, false)).toBe("desktop");+ expect(announcementSurface(false, true)).toBe("cloud");+ expect(announcementSurface(false, false)).toBe("server");+ expect(announcementPlan("cloud", null, true)).toBe("team");+ expect(announcementPlan("cloud", null, false)).toBe("cloud");+ expect(announcementPlan("server", null, false)).toBeUndefined();+ expect(announcementPlan("desktop", { kind: "connecting" }, false)).toBeNull();+ expect(announcementPlan("desktop", { kind: "free" }, false)).toBe("none");+ expect(announcementPlan("desktop", { kind: "paid", label: "Pro", checking: false }, false)).toBe("cloud");+ });++ it("the conditions a tip may ask for", () => {+ const state = (config: unknown, bots: unknown[], routines: unknown[], ready = true) =>+ announcementConditions({ config: config as never, bots: bots as never, routines: routines as never, routinesLoadState: ready ? "ready" : "loading" });+ expect(state({ anthropic: { configured: false } }, [{}], [])).toEqual({ no_api_key: true, one_bot_only: true, no_routine: true });+ expect(state({ openrouter: { configured: true } }, [{}, {}, { hidden: true }], [{}])).toEqual({ no_api_key: false, one_bot_only: false, no_routine: false });+ expect(state(null, [], [], false)).toEqual({ no_api_key: false, one_bot_only: false, no_routine: false });+ });++ it("an organization that limits providers gets no sponsor's card; a Team Cloud's own rules do not count", () => {+ const policy = (extra: Record<string, unknown>) => ({ organizationName: "Org", version: 1, companyModelsOnly: false, allowedEngines: "all", mcp: { allowCustom: true, allowlist: [] },+ computers: { thisComputer: true, localVm: true, box: true, vps: true }, remoteAccess: true, ...extra }) as never;+ expect(providersRestricted(null)).toBe(false);+ expect(providersRestricted(policy({}))).toBe(false);+ expect(providersRestricted(policy({ companyModelsOnly: true }))).toBe(true);+ expect(providersRestricted(policy({ allowedEngines: ["claudeAgent"] }))).toBe(true);+ expect(providersRestricted(policy({ allowedEngines: ["claudeAgent"], team: true }))).toBe(false);+ });+});++it("counts one event per card and step, with the card's public id and nothing else", () => {+ reportAnnouncement(make("card-a", { kind: "tip" }), "primary");+ expect(track).toHaveBeenCalledWith("announcement", { id: "card-a", kind: "tip", action: "primary" });+});++it("a card's texts may be in any of the app's languages, and only those", () => {+ expect([...ANNOUNCEMENT_LOCALES]).toEqual(localeChoices.map((choice) => choice.code));+});diff --git a/src/lib/announcements.ts b/src/lib/announcements.tsnew file mode 100644index 0000000000..bb05a384af--- /dev/null+++ b/src/lib/announcements.ts@@ -0,0 +1,245 @@+// The project's announcement cards on this page: which one, if any, is due, and the record that each person sees each+// card once. The server hands over the cards (server/routes/announcements.ts); everything about who sees one is decided+// here, from what the page already knows, and nothing about the person leaves it. AppNotices shows the card through the+// notice queue, after every notice someone must act on.+import { useEffect, useSyncExternalStore } from "react";+import { track } from "@/lib/analytics";+import { hintSeen, type OnboardingStatus } from "@/lib/onboarding";+import { localDay } from "@/lib/notices";+import type { CloudPlanView } from "@/lib/cloud-plan";+import type { ManagedPolicySummary } from "@/state/config-status";+import { api, type AppState } from "@/state/store";+import {+ ADMIN_PLACES, audienceMatches, cardPlaces, parseAnnouncementCard, type AnnouncementCard, type AnnouncementFacts, type AnnouncementKind,+ type AnnouncementPlan, type AnnouncementPlatform, type AnnouncementSurface,+} from "../../shared/announcements";++/** Sponsor cards for a Team Cloud's members who are not its owner or an admin. Off: a sponsor's card is for whoever+ * chooses the team's providers. The owner's call; flip this to show them to every member. */+export const SPONSOR_CARDS_FOR_TEAM_MEMBERS = false;+/** At most one sponsor card in this many days, per person. */+export const SPONSOR_REST_DAYS = 7;+export const ANNOUNCEMENT_REFRESH_MS = 60 * 60 * 1000;+const RETRY_MS = 5 * 60 * 1000;++const SEEN_PREFIX = "announcement:";+const SPONSOR_DAY_PREFIX = "announcement-sponsor:";+const LAUNCH_KEY = "omb.launch.announcement";+const SPONSOR_DAY_STORAGE = "omb.announcement.sponsor-day";+/** The workspace record keeps this many cards' marks at most, beside the app's own hints (server/config.ts caps them all). */+const MAX_KEPT_HINTS = 10;+const HINTS_CAP = 100;++export const seenKey = (id: string) => `${SEEN_PREFIX}${id}`;+export const sponsorDayKey = (day: string) => `${SPONSOR_DAY_PREFIX}${day}`;++// ---- The cards this server hands over: asked at launch, then about hourly while the app is in use.++let cards: AnnouncementCard[] = [];+let askedAt: number | null = null;+let answered = false;+let asking = false;+const listeners = new Set<() => void>();++function readCards(answer: unknown): AnnouncementCard[] {+ const list = (answer as { cards?: unknown } | null)?.cards;+ if (!Array.isArray(list)) return [];+ return list.flatMap((raw) => {+ const parsed = parseAnnouncementCard(raw);+ return parsed.ok ? [parsed.card] : [];+ });+}++function ask(now: number): void {+ if (asking || (askedAt !== null && now >= askedAt && now - askedAt < (answered ? ANNOUNCEMENT_REFRESH_MS : RETRY_MS))) return;+ asking = true;+ askedAt = now;+ void api("/api/announcements").then((answer) => { cards = readCards(answer); answered = true; }, () => {})+ .finally(() => { asking = false; for (const listener of listeners) listener(); });+}++const subscribe = (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; };+const snapshot = () => cards;++/** The cards this page's server handed over; none until it answers, and none where `enabled` is false. Each render asks+ * again once the last answer is an hour old, so a page in use follows the file without a timer of its own. */+export function useAnnouncementCards(enabled: boolean, now: () => number = Date.now): AnnouncementCard[] {+ const current = useSyncExternalStore(subscribe, snapshot, snapshot);+ useEffect(() => { if (enabled) ask(now()); });+ return enabled ? current : [];+}++/** Tests: start from a page that has asked nothing. */+export function forgetAnnouncementCards(): void {+ cards = []; askedAt = null; answered = false; asking = false;+}++// ---- What this page knows.++const stored = (key: string): string | null => { try { return localStorage.getItem(key); } catch { return null; } };+const store = (key: string, value: string) => { try { localStorage.setItem(key, value); } catch {} };++export function announcementPlatform(userAgent: string | undefined): AnnouncementPlatform | null {+ if (!userAgent) return null;+ if (/iPhone|iPad|iPod/.test(userAgent)) return "ios";+ if (/Android/.test(userAgent)) return "android";+ if (/Macintosh|Mac OS X/.test(userAgent)) return "mac";+ if (/Windows/.test(userAgent)) return "windows";+ if (/Linux|X11|CrOS/.test(userAgent)) return "linux";+ return null;+}++/** The desktop app's own page, a MausBot Cloud's page, or any other server's. */+export function announcementSurface(local: boolean, cloudHome: boolean): AnnouncementSurface {+ return local ? "desktop" : cloudHome ? "cloud" : "server";+}++/** On the desktop's page, from its Cloud sign-in (null while it is read); on a Cloud's page, that Cloud's; elsewhere unknown. */+export function announcementPlan(surface: AnnouncementSurface, view: CloudPlanView | null, team: boolean): AnnouncementPlan | null | undefined {+ if (surface === "cloud") return team ? "team" : "cloud";+ if (surface === "server" || !view) return undefined;+ if (view.kind === "unknown" || view.kind === "connecting") return null;+ return view.kind === "free" || view.kind === "signed-out" || view.kind === "removed" ? "none" : "cloud";+}++const PROVIDER_KEYS = ["anthropic", "openai", "openrouter", "openaiCompat", "xai", "mistral", "cerebras", "groq", "greenference", "modelgo", "meta", "deepseek", "opencodeGo"] as const;++export function announcementConditions(state: Pick<AppState, "config" | "bots" | "routines" | "routinesLoadState">): AnnouncementFacts["conditions"] {+ const config = state.config as Partial<Record<(typeof PROVIDER_KEYS)[number], { configured?: boolean }>> | null;+ return {+ no_api_key: Boolean(config) && !PROVIDER_KEYS.some((key) => config?.[key]?.configured === true),+ one_bot_only: state.bots.filter((bot) => !bot.hidden).length === 1,+ no_routine: state.routinesLoadState === "ready" && state.routines.length === 0,+ };+}++/** An organization's policy that limits the providers people may use: no sponsor's card there. A Team Cloud's own rules+ * are not that. */+export function providersRestricted(policy: ManagedPolicySummary | null | undefined): boolean {+ return Boolean(policy && !policy.team && (policy.companyModelsOnly || policy.allowedEngines !== "all"));+}++// ---- Who has seen what: this browser's storage, this desktop's record for every page its window shows, and the+// workspace's own record. A Team Cloud's record is the whole team's, so there only the first two count.++export interface SeenRecord {+ record: OnboardingStatus | undefined;+ /** This desktop's record (DesktopNoticesState.seen), on any page of its window; empty in a browser. */+ desktop: readonly string[];+ /** A Team Cloud's page. */+ team: boolean;+}++const has = (seen: SeenRecord, key: string) => stored(key) === "1" || seen.desktop.includes(key) || (!seen.team && hintSeen(seen.record, key));++export function cardSeen(seen: SeenRecord, id: string): boolean {+ return has(seen, seenKey(id));+}++/** The last day this person was shown a sponsor's card, as YYYY-MM-DD, or null. */+export function lastSponsorDay(seen: SeenRecord): string | null {+ const marks = [...seen.desktop, ...(seen.team ? [] : seen.record?.hintsSeen ?? [])]+ .filter((entry) => entry.startsWith(SPONSOR_DAY_PREFIX)).map((entry) => entry.slice(SPONSOR_DAY_PREFIX.length));+ const days = [stored(SPONSOR_DAY_STORAGE), ...marks].filter((day): day is string => typeof day === "string" && /^\d{4}-\d{2}-\d{2}$/.test(day));+ return days.sort().at(-1) ?? null;+}++const dayNumber = (day: string) => { const [year, month, date] = day.split("-").map(Number); return Math.round(new Date(year!, month! - 1, date!).getTime() / 86_400_000); };++export function sponsorRested(seen: SeenRecord, now: number): boolean {+ const last = lastSponsorDay(seen);+ return last === null || dayNumber(localDay(now)) - dayNumber(last) >= SPONSOR_REST_DAYS;+}++/** The workspace record's hints with one more announcement mark: marks of cards no longer in the feed go first, and at+ * most MAX_KEPT_HINTS stay, so the record never fills with them. A sponsor day replaces the last one. Null when nothing+ * changes or the record has no room. */+export function hintsWith(record: OnboardingStatus | undefined, key: string, liveIds: ReadonlySet<string>): string[] | null {+ const hints = record?.hintsSeen ?? [];+ if (hints.includes(key)) return null;+ const sponsorDay = key.startsWith(SPONSOR_DAY_PREFIX);+ const others = hints.filter((hint) => !hint.startsWith(SEEN_PREFIX) && !hint.startsWith(SPONSOR_DAY_PREFIX));+ const marks = hints.filter((hint) => hint.startsWith(SEEN_PREFIX) && liveIds.has(hint.slice(SEEN_PREFIX.length)));+ const days = hints.filter((hint) => hint.startsWith(SPONSOR_DAY_PREFIX));+ const next = [...others, ...[...marks, ...(sponsorDay ? [] : [key])].slice(-MAX_KEPT_HINTS), ...(sponsorDay ? [key] : days.slice(-1))];+ return next.length > HINTS_CAP ? null : next;+}++export interface RememberOptions {+ desktop?: { seen(id: string): Promise<void> };+ /** The cards the server handed over: marks of any other card leave the workspace record. */+ liveIds: ReadonlySet<string>;+ /** Sends the workspace record's new hints. */+ save: (hintsSeen: string[]) => void;+}++function remember(seen: SeenRecord, key: string, options: RememberOptions): void {+ void options.desktop?.seen(key).catch(() => {});+ if (seen.team) return;+ const hints = hintsWith(seen.record, key, options.liveIds);+ if (hints) options.save(hints);+}++/** The person closed or acted on this card: it never shows to them again, here or on their other pages. */+export function rememberCardSeen(seen: SeenRecord, id: string, options: RememberOptions): void {+ store(seenKey(id), "1");+ remember(seen, seenKey(id), options);+}++/** A sponsor's card was shown today: the next one waits SPONSOR_REST_DAYS. */+export function rememberSponsorDay(seen: SeenRecord, now: number, options: RememberOptions): void {+ const day = localDay(now);+ store(SPONSOR_DAY_STORAGE, day);+ remember(seen, sponsorDayKey(day), options);+}++// ---- One remote card per launch: the card this window's session showed.++let launchMemory: string | null = null;+export function launchAnnouncement(): string | null {+ try { return sessionStorage.getItem(LAUNCH_KEY) ?? launchMemory; } catch { return launchMemory; }+}+export function markLaunchAnnouncement(id: string): void {+ if (launchAnnouncement()) return;+ try { sessionStorage.setItem(LAUNCH_KEY, id); } catch { launchMemory = id; }+}++// ---- The card that is due.++export interface PickContext {+ facts: AnnouncementFacts;+ seen: SeenRecord;+ /** A branded build: no remote cards at all, as no What's new popup. */+ branded: boolean;+ /** Sponsor cards may show to this person here (not where an organization restricts providers, nor to a Team Cloud's+ * members unless SPONSOR_CARDS_FOR_TEAM_MEMBERS). */+ sponsors: boolean;+ /** This person may change this place's settings: a card that opens an admin's place skips everyone else. */+ admin: boolean;+}++/** The first card in file order that is due, "wait" while a fact the first candidate needs is still loading, or null. */+export function pickAnnouncement(list: readonly AnnouncementCard[], context: PickContext): AnnouncementCard | "wait" | null {+ if (context.branded) return null;+ const now = context.facts.nowMs, launch = launchAnnouncement();+ if (launch !== null && cardSeen(context.seen, launch)) return null;+ const rested = sponsorRested(context.seen, now);+ for (const card of list) {+ if ((card.starts && Date.parse(card.starts) > now) || Date.parse(card.ends) <= now) continue;+ if (cardSeen(context.seen, card.id) || (launch !== null && launch !== card.id)) continue;+ if (card.kind === "sponsor" && (!context.sponsors || (!rested && launch !== card.id))) continue;+ if (!context.admin && cardPlaces(card).some((place) => ADMIN_PLACES.has(place))) continue;+ const matches = audienceMatches(card.audience, context.facts);+ if (matches === null) return "wait";+ if (matches) return card;+ }+ return null;+}++export type AnnouncementAction = "shown" | "primary" | "secondary" | "close";++/** One event per card and step, under the same analytics switch as every other event. The id is the card's own, from+ * the public file, the same for everyone. */+export function reportAnnouncement(card: { id: string; kind: AnnouncementKind }, action: AnnouncementAction): void {+ track("announcement", { id: card.id, kind: card.kind, action });+}diff --git a/src/lib/notices.test.ts b/src/lib/notices.test.tsindex a09638d7f4..6fea085098 100644--- a/src/lib/notices.test.ts+++ b/src/lib/notices.test.ts@@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";import { EMPTY_ONBOARDING, type OnboardingStatus } from "@/lib/onboarding";import { withTourReset } from "@/lib/guided-tour";import { DESKTOP_NOTICES } from "../../electron/desktop-prefs.mjs";-import { BOAT_OFFER_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, FOLLOWERS, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, localDay, markLaunchNotice, MODELGO_OFFER_NOTICE, MUST_ACT,+import { ANNOUNCEMENT_NOTICE, BOAT_OFFER_NOTICE, CLOUD_INTRO, CLOUD_NOTICE, CLOUD_TRIAL_NOTICE, dismissNotice, dismissNotices, FOLLOWERS, GROK_MOVE_NOTICE, introShown, introStage, launchNotice, localDay, markLaunchNotice, MODELGO_OFFER_NOTICE, MUST_ACT,nextNotice, noticeSeen, NOTICES, OLD_PRO_DISMISSALS, PHONE_UPDATE_NOTICE, phoneUpdateHint, PRODUCT_HUNT_NOTICE, SIMPLE_MODE_NOTICE, STAR_NOTICE, TWO_PLACES_NOTICE, UPDATES_CONSENT_NOTICE, usedBefore, WHATS_NEW_NOTICE, type NoticeFacts,type NoticeId } from "./notices";@@ -17,9 +17,9 @@ afterEach(() => vi.unstubAllGlobals());const record = (hintsSeen: string[] = []): OnboardingStatus => ({ ...EMPTY_ONBOARDING, completedAt: "2026-09-01", version: 1, hintsSeen });const facts = (intro: boolean | null, trial: boolean | null, cloud: boolean | null, star: boolean | null, launch: boolean | null = false, popup: boolean | null = false,consent: boolean | null = false, simple: boolean | null = false, boat: boolean | null = false, two: boolean | null = false, grok: boolean | null = false, modelgo: boolean | null = false,- phone: boolean | null = false): NoticeFacts =>+ phone: boolean | null = false, announcement: boolean | null = false): NoticeFacts =>({ [GROK_MOVE_NOTICE]: grok, [PHONE_UPDATE_NOTICE]: phone, [SIMPLE_MODE_NOTICE]: simple, [WHATS_NEW_NOTICE]: popup, [UPDATES_CONSENT_NOTICE]: consent, [TWO_PLACES_NOTICE]: two, [PRODUCT_HUNT_NOTICE]: launch, [CLOUD_INTRO]: intro, [CLOUD_TRIAL_NOTICE]: trial, [CLOUD_NOTICE]: cloud,- [MODELGO_OFFER_NOTICE]: modelgo, [BOAT_OFFER_NOTICE]: boat, [STAR_NOTICE]: star });+ [MODELGO_OFFER_NOTICE]: modelgo, [BOAT_OFFER_NOTICE]: boat, [ANNOUNCEMENT_NOTICE]: announcement, [STAR_NOTICE]: star });const none = () => false;const DAY = 86_400_000, NOON = new Date(2026, 9, 9, 12).getTime();@@ -37,7 +37,7 @@ it("is one queue: the Simple mode popup first, then What's new, the product-updaexpect(nextNotice(facts(true, true, true, true, true, true, true, true), none)).toBe(SIMPLE_MODE_NOTICE);expect(nextNotice(facts(true, true, true, true, true, true, true, null), none), "nothing shows while the Simple mode popup waits").toBeNull();expect(nextNotice(facts(true, true, true, true, true, true, true, true), id => id === SIMPLE_MODE_NOTICE)).toBe(WHATS_NEW_NOTICE);- expect(NOTICES).toEqual([GROK_MOVE_NOTICE, PHONE_UPDATE_NOTICE, SIMPLE_MODE_NOTICE, WHATS_NEW_NOTICE, UPDATES_CONSENT_NOTICE, TWO_PLACES_NOTICE, PRODUCT_HUNT_NOTICE, CLOUD_INTRO, CLOUD_TRIAL_NOTICE, CLOUD_NOTICE, MODELGO_OFFER_NOTICE, BOAT_OFFER_NOTICE, STAR_NOTICE]);+ expect(NOTICES).toEqual([GROK_MOVE_NOTICE, PHONE_UPDATE_NOTICE, SIMPLE_MODE_NOTICE, WHATS_NEW_NOTICE, UPDATES_CONSENT_NOTICE, TWO_PLACES_NOTICE, PRODUCT_HUNT_NOTICE, CLOUD_INTRO, CLOUD_TRIAL_NOTICE, CLOUD_NOTICE, MODELGO_OFFER_NOTICE, BOAT_OFFER_NOTICE, ANNOUNCEMENT_NOTICE, STAR_NOTICE]);expect(nextNotice(facts(true, true, true, true, true, false, false, false, false, true), none), "bots in two places come before any promotion").toBe(TWO_PLACES_NOTICE);expect(nextNotice(facts(true, true, true, true, true, false, true, false, false, true), none), "after the product-updates question").toBe(UPDATES_CONSENT_NOTICE);expect(nextNotice(facts(true, true, true, true, true, false, false, false, false, null), none), "nothing lower shows while main hasn't answered").toBeNull();@@ -211,7 +211,7 @@ it("an Update MausBot on your phone dismissal is kept per phone, in short hints,});it("ModelGo's card follows the launch's notice in the same launch once it is closed, after the question, never ahead of a notice to act on", () => {- expect([...FOLLOWERS]).toEqual([UPDATES_CONSENT_NOTICE, MODELGO_OFFER_NOTICE]);+ expect([...FOLLOWERS]).toEqual([UPDATES_CONSENT_NOTICE, MODELGO_OFFER_NOTICE, ANNOUNCEMENT_NOTICE]);expect([...MUST_ACT]).toEqual([GROK_MOVE_NOTICE, PHONE_UPDATE_NOTICE, CLOUD_TRIAL_NOTICE, CLOUD_NOTICE]);const due = ({ popup = true, consent = false, trial = false, cloud = false, grok = false, intro = false, two = false }: Partial<Record<"popup" | "trial" | "cloud" | "grok" | "intro" | "two", boolean | null>> & { consent?: boolean | null }) =>facts(intro, trial, cloud, true, false, popup, consent, false, true, two, grok, true);@@ -238,3 +238,38 @@ it("ModelGo's card follows the launch's notice in the same launch once it is cloexpect(nextNotice({ ...due({}), [MODELGO_OFFER_NOTICE]: false }, popupSeen, WHATS_NEW_NOTICE, true), "where it may not show: nothing").toBeNull();expect(nextNotice({ ...due({}), [MODELGO_OFFER_NOTICE]: null }, popupSeen, WHATS_NEW_NOTICE, true), "while unknown: nothing yet").toBeNull();});++it("a card from the announcements file comes after every notice someone must act on and every built-in offer, before the star", () => {+ const remote = ({ consent = false, trial = false, cloud = false, modelgo = false, boat = false, card = true, popup = false, grok = false, phone = false }: { consent?: boolean | null;+ trial?: boolean | null; cloud?: boolean | null; modelgo?: boolean | null; boat?: boolean | null; card?: boolean | null; popup?: boolean | null; grok?: boolean | null; phone?: boolean | null }) =>+ facts(false, trial, cloud, true, false, popup, consent, false, boat, false, grok, modelgo, phone, card);+ expect(nextNotice(remote({}), none)).toBe(ANNOUNCEMENT_NOTICE);+ for (const [first, id] of [[{ phone: true }, PHONE_UPDATE_NOTICE], [{ consent: true }, UPDATES_CONSENT_NOTICE], [{ trial: true }, CLOUD_TRIAL_NOTICE], [{ cloud: true }, CLOUD_NOTICE],+ [{ modelgo: true }, MODELGO_OFFER_NOTICE], [{ boat: true }, BOAT_OFFER_NOTICE]] as const) expect(nextNotice(remote(first), none), id).toBe(id);+ expect(nextNotice(remote({ card: null }), none), "the star waits while it is undecided").toBeNull();+ expect(nextNotice(remote({ card: false }), none)).toBe(STAR_NOTICE);+ expect(nextNotice(remote({ boat: true }), none, BOAT_OFFER_NOTICE), "never over a card still up").toBe(BOAT_OFFER_NOTICE);+ expect(nextNotice(remote({ boat: true }), id => id === BOAT_OFFER_NOTICE, BOAT_OFFER_NOTICE, true), "it follows that card once it is closed").toBe(ANNOUNCEMENT_NOTICE);+});++it("a card from the announcements file follows the launch's notice in the same launch, after the question and the sponsor's card, never ahead of a notice to act on", () => {+ const remote = (extra: Partial<Record<"popup" | "consent" | "modelgo" | "boat" | "trial" | "cloud" | "grok" | "phone" | "card", boolean | null>> = {}) => {+ const { popup = true, consent = false, modelgo = false, boat = false, trial = false, cloud = false, grok = false, phone = false, card = true } = extra;+ return facts(false, trial, cloud, true, false, popup, consent, false, boat, false, grok, modelgo, phone, card);+ };+ const popupSeen = (id: NoticeId) => id === WHATS_NEW_NOTICE;+ expect(nextNotice(remote(), none), "What's new goes first").toBe(WHATS_NEW_NOTICE);+ expect(nextNotice(remote(), none, WHATS_NEW_NOTICE), "never over it while it is up").toBe(WHATS_NEW_NOTICE);+ expect(nextNotice(remote(), popupSeen, WHATS_NEW_NOTICE, true), "follows a closed What's new").toBe(ANNOUNCEMENT_NOTICE);+ expect(nextNotice(remote({ popup: false }), none, WHATS_NEW_NOTICE), "and after a reload").toBe(ANNOUNCEMENT_NOTICE);+ expect(nextNotice(remote({ consent: true }), popupSeen, WHATS_NEW_NOTICE, true), "the product-updates question first").toBe(UPDATES_CONSENT_NOTICE);+ expect(nextNotice(remote({ consent: null }), popupSeen, WHATS_NEW_NOTICE, true), "which holds it while unanswered").toBeNull();+ expect(nextNotice(remote({ modelgo: true }), popupSeen, WHATS_NEW_NOTICE, true), "then the sponsor's card").toBe(MODELGO_OFFER_NOTICE);+ expect(nextNotice(remote({ modelgo: null }), popupSeen, WHATS_NEW_NOTICE, true), "which holds it while undecided").toBeNull();+ expect(nextNotice(remote({ modelgo: true }), id => id === WHATS_NEW_NOTICE || id === MODELGO_OFFER_NOTICE, WHATS_NEW_NOTICE, true), "then the announcement").toBe(ANNOUNCEMENT_NOTICE);+ expect(nextNotice(remote({ boat: true }), popupSeen, WHATS_NEW_NOTICE, true), "Boat's offer is no follower: it waits, the announcement does not").toBe(ANNOUNCEMENT_NOTICE);+ for (const [name, held] of [["grok", remote({ grok: true })], ["phone", remote({ phone: true })], ["trial", remote({ trial: true })], ["cloud", remote({ cloud: true })], ["trial unknown", remote({ trial: null })]] as const)+ expect(nextNotice(held, popupSeen, WHATS_NEW_NOTICE, true), `${name}: held for that notice's launch`).toBeNull();+ expect(nextNotice(remote({ popup: false, trial: true }), none, CLOUD_TRIAL_NOTICE, true), "and follows it there").toBe(ANNOUNCEMENT_NOTICE);+ expect(nextNotice(remote({ card: false }), popupSeen, WHATS_NEW_NOTICE, true), "none due (one a launch, a sponsor a week): nothing").toBeNull();+});diff --git a/src/lib/notices.ts b/src/lib/notices.tsindex 23390a45cd..d61518c961 100644--- a/src/lib/notices.ts+++ b/src/lib/notices.ts@@ -22,6 +22,10 @@ export const GROK_MOVE_NOTICE = "grok-move-2026-11";export const MODELGO_OFFER_NOTICE = "modelgo-offer-2026-11";/** Update MausBot on your phone: once per phone with an older app after this computer's secure link ended. */export const PHONE_UPDATE_NOTICE = "phone-app-update";+/** A card from the project's announcements file (src/lib/announcements.ts keeps which ones each person saw, and allows one a+ * launch): after every notice someone must act on and every built-in offer, and, as the sponsor's card, it may follow the+ * launch's notice once that is closed, after the product-updates question and the sponsor's card. */+export const ANNOUNCEMENT_NOTICE = "announcement";/*** Every notice, in the order a launch asks them: one launch shows one notice first, the first one due, and only FOLLOWERS may@@ -40,6 +44,7 @@ export const NOTICES = [CLOUD_NOTICE,MODELGO_OFFER_NOTICE,BOAT_OFFER_NOTICE,+ ANNOUNCEMENT_NOTICE,STAR_NOTICE,] as const;@@ -47,15 +52,17 @@ export type NoticeId = (typeof NOTICES)[number];export type NoticeFacts = Record<NoticeId, boolean | null>;-/** What may still come in a launch another notice took: the product-updates question, and the sponsor's card, which everyone- * is to see on the first launch it may show in. Each in its place in NOTICES. */-export const FOLLOWERS: readonly NoticeId[] = [UPDATES_CONSENT_NOTICE, MODELGO_OFFER_NOTICE];-/** Notices the person has to act on. The sponsor's card never goes ahead of one, even one left for a later launch: it waits- * for that launch and follows it there. */+/** What may still come in a launch another notice took: the product-updates question, the sponsor's card and a card from the+ * announcements file, which everyone is to see on the first launch they may show in. Each in its place in NOTICES. */+export const FOLLOWERS: readonly NoticeId[] = [UPDATES_CONSENT_NOTICE, MODELGO_OFFER_NOTICE, ANNOUNCEMENT_NOTICE];+/** The followers that are cards of their own: they never go ahead of a notice to act on, nor replace a card still up. */+const FOLLOWING_CARDS: readonly NoticeId[] = [MODELGO_OFFER_NOTICE, ANNOUNCEMENT_NOTICE];+/** Notices the person has to act on. The sponsor's card and an announcement card never go ahead of one, even one left for a+ * later launch: they wait for that launch and follow it there. */export const MUST_ACT: readonly NoticeId[] = [GROK_MOVE_NOTICE, PHONE_UPDATE_NOTICE, CLOUD_TRIAL_NOTICE, CLOUD_NOTICE];/** `launch`: the notice this launch already showed (launchNotice), the only one besides FOLLOWERS that may show again in it.- * `closed`: that notice was closed in this page, so it doesn't come back however its facts read. The sponsor's card follows+ * `closed`: that notice was closed in this page, so it doesn't come back however its facts read. The following cards follow* only once the launch's notice is gone, so two cards never share the corner. */export function nextNotice(facts: NoticeFacts, seen: (id: NoticeId) => boolean, launch: NoticeId | null = null, closed = false): NoticeId | null {const launchUp = launch !== null && !closed && !seen(launch) && facts[launch] !== false;@@ -66,7 +73,7 @@ export function nextNotice(facts: NoticeFacts, seen: (id: NoticeId) => boolean,if (id !== launch && MUST_ACT.includes(id) && facts[id] !== false) held = true;continue;}- if (id === MODELGO_OFFER_NOTICE && id !== launch && (held || launchUp)) continue;+ if (FOLLOWING_CARDS.includes(id) && id !== launch && (held || launchUp)) continue;if (facts[id] === null) return null;if (facts[id]) return id;}