Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

Quota card: finish pausing the sharing reward

Barack Sokullu58fcf0b62428
diff --git a/docs/compass-quota-rollout.md b/docs/compass-quota-rollout.md
index 781243015..6750c01ee 100644
--- a/docs/compass-quota-rollout.md
+++ b/docs/compass-quota-rollout.md
@@ -5,7 +5,7 @@ Implementation spans `webbrain2` and sibling `webbrain-cloud`. The constructor d
## Release order
1. **Backend compatibility first.** Back up the entire usage JSON while the service is stopped or while holding its store lock. Set `WEEKLY_FREE_USD=0.50` explicitly in the active backend environment for the approved transition while clients update. The constructor default also matches $0.50. Ship the additive usage fields, `/usage` (`/v1/usage` alias), promotion endpoints, persistent ledger, review CLI, and telemetry first. Older clients retain their existing Subscribe card until they update. Verify a free-quota 402 still includes the device-linked `subscribe_url`, and paid/payment-failure responses still point to the existing upgrade/account flows. Confirm the CLI and web workers resolve the same `USAGE_PATH`, and that all workers share the same filesystem lock.
-2. **Extension next.** Ship both Chrome and Firefox together. Check the reward and subscription choices, narrow panels, keyboard focus, claim submission/status, restored conversations, and a return from checkout. Confirm an automatic award leaves browser actions stopped until the explicit Continue/Retry button is selected. Confirm pending claims from older versions are automatically accepted when status is fetched, approved/redeemed devices have no offer to earn again, and existing payment recovery and Plus upgrades still work. Confirm the backend returns promotion state before enabling the new experience to users.
+2. **Extension next.** Ship both Chrome and Firefox together. While the sharing reward is paused (see below) the card has no reward choice, claim form or claim status, so the reward and claim checks in this step apply only when it is enabled. Check the reward and subscription choices, narrow panels, keyboard focus, claim submission/status, restored conversations, and a return from checkout. Confirm an automatic award leaves browser actions stopped until the explicit Continue/Retry button is selected. Confirm pending claims from older versions are automatically accepted when status is fetched, approved/redeemed devices have no offer to earn again, and existing payment recovery and Plus upgrades still work. Confirm the backend returns promotion state before enabling the new experience to users.
3. **Verify the transition amount.** Check the actual web-worker/service/container environment as well as `.env`: exported variables take precedence over `.env`. Query `/usage` from the running service with `X-WebBrain-Device-Id`; both `base_weekly_allowance_usd` and `weekly_limit_usd` must be `0.50`, and `next_reset_at` must be the next Monday 00:00 UTC. Verify an exhausted free device's 402 reports the same amount and retains `subscribe_url`. Do not rely on the example file or a CLI process with a different environment. Keep the explicit $0.50 override while clients adopt the update. A later reduction to $0.375 requires a separate rollout decision after reviewing extension availability, adoption, and consumption; it is not activated automatically.
4. **Observe for 14 full days at $0.50.** Record the UTC activation time, active amount, extension versions, and automatic reward behavior. Review the report daily and reassess the amount after two full UTC weeks. If recovery choices are unavailable or the allowance proves too small, restore the override to `0.75` while leaving the backend ledger and extension controls in place. A rollback must preserve lifetime awards and remaining balances.
@@ -17,11 +17,13 @@ Production storage must support POSIX directory `fsync`: verify file and parent-
## Sharing reward paused
-The extension hides the sharing reward: `SOCIAL_PROMOTION_ENABLED` in `src/*/src/ui/compass-quota.js` is `false`, because the offer invited abuse. The quota card then shows the weekly allowance (`quota.allowance`), the reset time, Subscribe, Refresh status and Continue/Retry. It never requests `/promotions/social`, shows no claim status, and a restored card that had its claim form open comes back without it. Credit a device already earned still appears as the reward balance, and the backend still spends it. The claim flow below is unchanged and still tested (`test/compass-quota-ui.mjs` mounts it with `socialPromotion: true`); setting the flag back to `true` in both builds restores it.
+The extension hides the sharing reward: `SOCIAL_PROMOTION_ENABLED` in `src/*/src/ui/compass-quota.js` is `false`, because the offer invited abuse. The quota card then shows the weekly allowance (`quota.allowance`), the reset time, Subscribe, Refresh status and Continue/Retry. It never requests `/promotions/social`, shows no claim status, and a restored card that had its claim form open comes back without it. Credit a device already earned still appears as the reward balance, and the backend still spends it. The claim flow below is unchanged and still tested (`test/compass-quota-ui.mjs` mounts it with `socialPromotion: true`); setting the flag back to `true` in both builds, and the expectation that pins it in `test/compass-quota.mjs`, restores it. While it is paused, Continue/Retry sends no `continuation_after_reward` event, and a balance that would print as $0.00 counts as none.
+
+The extension switch alone does not stop the reward. The backend still accepts `POST /promotions/social/claims` and awards $0.50 automatically for any syntactically valid post URL under any `X-WebBrain-Device-Id`, `/usage` still approves leftover pending claims, and extension versions released before this switch still show the offer. Pausing it for every client needs a server-side switch in webbrain-cloud: refuse new claims, stop automatic approval, and report `eligible: false` (older extension versions hide the share button then), while earned balances stay spendable.
## Automatic rewards
-A syntactically valid supported public post URL submitted to `/promotions/social/claims` immediately grants the one-time $0.50 reward under the usage-store lock. The response is already `approved`, with `eligible: false` and a $0.50 balance. The quota card offers sharing credit and a Compass subscription; it has no provider-switch choice.
+A syntactically valid supported public post URL submitted to `/promotions/social/claims` immediately grants the one-time $0.50 reward under the usage-store lock. The response is already `approved`, with `eligible: false` and a $0.50 balance. With the reward enabled, the quota card offers sharing credit and a Compass subscription; while it is paused it offers only the subscription. It has no provider-switch choice.
Existing pending claims receive the same award on `/usage`, `/v1/usage`, `/promotions/social`, or a repeated submission. Drafts and rejected claims receive no credit until submitted. Ordinary usage reads still do not allocate claims or rewrite the ledger. Deploy this backend behavior before the extension copy.
diff --git a/src/chrome/src/ui/compass-quota.js b/src/chrome/src/ui/compass-quota.js
index c8d972f7a..d30bbe237 100644
--- a/src/chrome/src/ui/compass-quota.js
+++ b/src/chrome/src/ui/compass-quota.js
@@ -44,10 +44,11 @@ export function createQuotaController({ t, locale, request, openUrl, continueTas
const balance = el('div', '', 'quota-balance');
const reset = el('div', '', 'quota-reset');
const actions = el('div', '', 'quota-choices');
- const claimArea = el('div', '', 'quota-claim');
+ // The share button and claim form exist only while the reward is offered.
+ const claimArea = socialPromotion ? el('div', '', 'quota-claim') : null;
const status = el('div', '', 'quota-status');
status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
- const share = button(t('quota.get'), async () => {
+ const share = socialPromotion && button(t('quota.get'), async () => {
host.dataset.claimOpen = 'true';
try {
if (social?.status === 'pending') { await inflight; await refresh(); return; }
@@ -58,22 +59,24 @@ export function createQuotaController({ t, locale, request, openUrl, continueTas
} catch (error) { status.textContent = error.message; }
}, 'quota-share');
const subscribe = button(t('quota.subscribe'), () => { event('checkout_open'); openUrl(quota.subscribe_url); }, 'subscribe-btn');
- actions.append(...(socialPromotion ? [share] : []), subscribe);
+ actions.append(...[share, subscribe].filter(Boolean));
const resume = button(t(context.retry ? 'sp.retry' : 'sp.continue_btn'), () => {
- if (social && !social.eligible) event('continuation_after_reward');
+ // Reward telemetry: a paused offer has no reward to continue after.
+ if (socialPromotion && social && !social.eligible) event('continuation_after_reward');
continueTask(resume, context);
}, 'subscribe-resume-btn');
resume.dataset.resumeMode = context.mode || 'act';
resume.dataset.resumeForeground = context.foreground ? 'true' : 'false';
const refreshButton = button(t('quota.refresh'), () => refresh(), 'quota-refresh');
- host.append(info, balance, reset, actions, claimArea, status, refreshButton, resume);
+ host.append(...[info, balance, reset, actions, claimArea, status, refreshButton, resume].filter(Boolean));
function renderState() {
if (cards.get(host)?.refresh !== refresh) return;
const base = state.base_weekly_allowance_usd ?? state.weekly_limit_usd ?? state.daily_limit_usd;
const credit = social?.remaining_credit_usd ?? state.promotional_balance_usd;
// Credit a device already earned stays visible while the offer is paused.
- balance.textContent = base == null ? '' : socialPromotion || Number(credit) > 0
+ // A remainder that formatQuotaUsd would print as $0.00 counts as none.
+ balance.textContent = base == null ? '' : socialPromotion || Math.round(Number(credit) * 1e6) > 0
? t('quota.balance', { base: formatQuotaUsd(base, locale()), credit: formatQuotaUsd(credit, locale()) })
: t('quota.allowance', { base: formatQuotaUsd(base, locale()) });
const date = new Date(state.next_reset_at || social?.next_reset_at || '');
diff --git a/src/firefox/src/ui/compass-quota.js b/src/firefox/src/ui/compass-quota.js
index c8d972f7a..d30bbe237 100644
--- a/src/firefox/src/ui/compass-quota.js
+++ b/src/firefox/src/ui/compass-quota.js
@@ -44,10 +44,11 @@ export function createQuotaController({ t, locale, request, openUrl, continueTas
const balance = el('div', '', 'quota-balance');
const reset = el('div', '', 'quota-reset');
const actions = el('div', '', 'quota-choices');
- const claimArea = el('div', '', 'quota-claim');
+ // The share button and claim form exist only while the reward is offered.
+ const claimArea = socialPromotion ? el('div', '', 'quota-claim') : null;
const status = el('div', '', 'quota-status');
status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite');
- const share = button(t('quota.get'), async () => {
+ const share = socialPromotion && button(t('quota.get'), async () => {
host.dataset.claimOpen = 'true';
try {
if (social?.status === 'pending') { await inflight; await refresh(); return; }
@@ -58,22 +59,24 @@ export function createQuotaController({ t, locale, request, openUrl, continueTas
} catch (error) { status.textContent = error.message; }
}, 'quota-share');
const subscribe = button(t('quota.subscribe'), () => { event('checkout_open'); openUrl(quota.subscribe_url); }, 'subscribe-btn');
- actions.append(...(socialPromotion ? [share] : []), subscribe);
+ actions.append(...[share, subscribe].filter(Boolean));
const resume = button(t(context.retry ? 'sp.retry' : 'sp.continue_btn'), () => {
- if (social && !social.eligible) event('continuation_after_reward');
+ // Reward telemetry: a paused offer has no reward to continue after.
+ if (socialPromotion && social && !social.eligible) event('continuation_after_reward');
continueTask(resume, context);
}, 'subscribe-resume-btn');
resume.dataset.resumeMode = context.mode || 'act';
resume.dataset.resumeForeground = context.foreground ? 'true' : 'false';
const refreshButton = button(t('quota.refresh'), () => refresh(), 'quota-refresh');
- host.append(info, balance, reset, actions, claimArea, status, refreshButton, resume);
+ host.append(...[info, balance, reset, actions, claimArea, status, refreshButton, resume].filter(Boolean));
function renderState() {
if (cards.get(host)?.refresh !== refresh) return;
const base = state.base_weekly_allowance_usd ?? state.weekly_limit_usd ?? state.daily_limit_usd;
const credit = social?.remaining_credit_usd ?? state.promotional_balance_usd;
// Credit a device already earned stays visible while the offer is paused.
- balance.textContent = base == null ? '' : socialPromotion || Number(credit) > 0
+ // A remainder that formatQuotaUsd would print as $0.00 counts as none.
+ balance.textContent = base == null ? '' : socialPromotion || Math.round(Number(credit) * 1e6) > 0
? t('quota.balance', { base: formatQuotaUsd(base, locale()), credit: formatQuotaUsd(credit, locale()) })
: t('quota.allowance', { base: formatQuotaUsd(base, locale()) });
const date = new Date(state.next_reset_at || social?.next_reset_at || '');
diff --git a/test/compass-quota-ui.mjs b/test/compass-quota-ui.mjs
index 83f73ce88..6edd4aa92 100644
--- a/test/compass-quota-ui.mjs
+++ b/test/compass-quota-ui.mjs
@@ -12,6 +12,7 @@ await mkdir(output, { recursive: true });
const fixture = (build, locale) => `<!doctype html><meta charset="utf-8"><link rel="stylesheet" href="/src/${build}/styles/sidepanel.css">
<style>:root{--accent:#6c5dd3;--accent-dim:#f0edfb;--accent-hover:#5546b8;--text-primary:#242235;--border:#dedbe8;--bg-secondary:#fff}body{margin:0;padding:12px;box-sizing:border-box;background:#faf9ff;color:#242235;font:14px system-ui;overflow:auto}main{width:100%;box-sizing:border-box}.message{margin:0;width:100%}.message-text{padding:12px;box-sizing:border-box;border:1px solid #dedbe8;border-radius:10px}</style>
<main id="history"><div class="message assistant" data-run-mode="act"><div id="card" class="message-text"></div></div></main>
+<section class="message assistant"><div id="paused" class="message-text"></div></section>
<script type="module">
import { createQuotaController } from '/src/${build}/src/ui/compass-quota.js';
import { quotaTranslations } from '/src/${build}/src/ui/locales/compass-quota-copy.mjs';
@@ -23,7 +24,7 @@ const t=(key,params={})=>(quotaTranslations[code][key] || dict[key] || en[key] |
window.requests=[];window.opened=[];window.switched=[];window.continuations=[];window.settingsOpened=0;window.deferredRefresh=[];
window.claim={eligible:true,status:'draft',claim_id:null,share_url:null,remaining_credit_usd:0};
window.usage={tier:'free',base_weekly_allowance_usd:0.375,weekly_limit_usd:0.375,promotional_balance_usd:0,next_reset_at:'2026-10-12T00:00:00Z'};
-window.makeController=()=>createQuotaController({t,locale:()=>code,request:async(path,body)=>{
+window.makeController=(options={})=>createQuotaController({t,locale:()=>code,request:async(path,body)=>{
requests.push({path,body});if(window.offline)throw Error('offline');
if(path==='/promotions/events')return {};
if(path==='/promotions/social/claims'){
@@ -36,7 +37,9 @@ window.makeController=()=>createQuotaController({t,locale:()=>code,request:async
if(window.delayRefresh)return new Promise((resolve,reject)=>deferredRefresh.push(()=>window.failDelayedRefresh?reject(Error('offline')):resolve(snapshot)));
return snapshot;
},openUrl:url=>opened.push(url),providers:async()=>[{id:'webbrain_cloud',label:'WebBrain Compass'},{id:'own-key',label:'My API key'},{id:'local',label:'Local model'}],switchProvider:async id=>{if(window.providerError)throw Error(window.providerError);switched.push(id);},openSettings:()=>settingsOpened++,continueTask:(_button,context)=>continuations.push(context),persist:()=>{},
- ...(new URLSearchParams(location.search).get('promo')==='off'?{}:{socialPromotion:true})});
+ socialPromotion:new URLSearchParams(location.search).get('promo')!=='off',...options});
+window.remount=()=>{const history=document.querySelector('#history');history.innerHTML=history.innerHTML;controller=makeController();controller.restore(history);};
+window.mountPaused=()=>makeController({socialPromotion:false}).mount(document.querySelector('#paused'),{code:'webbrain_cloud_free_tier_exceeded',usage:{...usage,social_claim:{...claim}},subscribe_url:'https://buy.stripe.com/test?client_reference_id=device-guid'},{mode:'act'});
window.controller=makeController();controller.mount(document.querySelector('#card'),{code:'webbrain_cloud_free_tier_exceeded',usage:{...usage,social_claim:claim},subscribe_url:'https://buy.stripe.com/test?client_reference_id=device-guid'},{mode:'act',foreground:true});
window.ready=true;
</script>`;
@@ -71,9 +74,9 @@ try {
if (process.env.QUOTA_UI_BROWSER && process.env.QUOTA_UI_BROWSER !== build) continue;
const browser = await engine.launch();
try {
- // The sharing reward is paused by default: the card offers only the
+ // The sharing reward is paused in the shipped card: it offers only the
// subscription and never asks for a share link.
- for (const lang of ['en', 'de']) {
+ for (const lang of ['en']) {
const page = await browser.newPage({ viewport: { width: 280, height: 1000 }, timezoneId: 'Europe/Istanbul' });
const errors = []; page.on('pageerror', e => errors.push(e.message));
await page.goto(`${origin}/quota?build=${build}&locale=${lang}&promo=off`);
@@ -94,12 +97,21 @@ try {
assert.match(await page.locator('.quota-balance').textContent(), /Reward balance: \$0\.25/);
assert.doesNotMatch(await page.locator('.quota-status').textContent(), /Approved/); checks += 2;
// A card saved with its claim form open is restored without it.
- await page.evaluate(() => { const card = document.querySelector('#card'); card.dataset.claimOpen = 'true'; claim = { ...claim, eligible: true, status: 'draft', share_url: 'https://webbrain.one/?share=x', remaining_credit_usd: 0 }; const html = document.querySelector('#history').innerHTML; document.querySelector('#history').innerHTML = html; controller = makeController(); controller.restore(document.querySelector('#history')); });
+ await page.evaluate(() => { document.querySelector('#card').dataset.claimOpen = 'true'; claim = { ...claim, eligible: true, status: 'draft', share_url: 'https://webbrain.one/?share=x', remaining_credit_usd: 0 }; remount(); });
await page.locator('.quota-refresh').click();
assert.equal(await page.locator('.quota-claim *').count(), 0);
assert.equal(await page.locator('.quota-share').count(), 0); checks += 2;
+ // Continue after an earlier reward sends no reward telemetry while the offer is paused.
+ await page.evaluate(() => { claim = { ...claim, eligible: false, status: 'redeemed' }; });
+ await page.locator('.quota-refresh').click();
await page.locator('.subscribe-resume-btn').click();
- assert.equal(await page.evaluate(() => continuations.length), 1); checks++;
+ assert.equal(await page.evaluate(() => continuations.length), 1);
+ assert.equal(await page.evaluate(() => requests.filter(r => r.body?.event === 'continuation_after_reward').length), 0); checks += 2;
+ // A remainder too small to display is no reward balance.
+ await page.evaluate(() => { claim = { ...claim, remaining_credit_usd: 4e-7 }; });
+ await page.locator('.quota-refresh').click();
+ await page.waitForFunction(() => !/Reward/.test(document.querySelector('.quota-balance').textContent));
+ assert.equal(await page.locator('.quota-balance').textContent(), 'Weekly allowance: $0.375'); checks++;
}
assert.equal(await page.evaluate(() => requests.filter(r => r.path.startsWith('/promotions/social')).length), 0); checks++;
assert.deepEqual(errors, []); checks++;
@@ -146,7 +158,7 @@ try {
assert.equal(new URL(await page.evaluate(() => opened.at(-1))).searchParams.get('text'), copy); checks += 2;
await page.locator('.quota-claim select').selectOption('bluesky');
await page.locator('.quota-claim input').fill('https://bsky.app/profile/a.bsky.social/post/3abc');
- await page.evaluate(() => { const html = document.querySelector('#history').innerHTML; document.querySelector('#history').innerHTML = html; controller = makeController(); controller.restore(document.querySelector('#history')); });
+ await page.evaluate(() => { remount(); });
assert.equal(await page.locator('.quota-claim textarea').inputValue(), copy);
assert.equal(await page.locator('.quota-claim select').inputValue(), 'bluesky');
assert.match(await page.locator('.quota-claim input').inputValue(), /bsky\.app/); checks += 3;
@@ -199,7 +211,7 @@ try {
assert.match(await page.locator('.quota-balance').textContent(), /\$0\.50/);
assert.equal(await page.evaluate(() => continuations.length), 0); checks += 3;
assert.equal(await page.locator('.quota-providers').count(), 0); checks++;
- await page.evaluate(() => { const html = document.querySelector('#history').innerHTML; document.querySelector('#history').innerHTML = html; controller = makeController(); controller.restore(document.querySelector('#history')); });
+ await page.evaluate(() => { remount(); });
assert.equal(await page.locator('.quota-share:visible').count(), 0); checks++;
await page.locator('.subscribe-resume-btn').click();
assert.equal(await page.evaluate(() => continuations.length), 1);
@@ -220,10 +232,16 @@ try {
assert.equal(await page.locator('#card').evaluate(el => JSON.parse(el.dataset.quota).usage.social_claim.remaining_credit_usd), 0.5); checks++;
assert.equal(await page.evaluate(() => continuations.length), 0); checks++;
}
+ // The card that ships (reward paused), in this locale at 280 px.
+ await page.evaluate(() => mountPaused());
+ assert.equal(await page.locator('#paused .quota-choices button:visible').count(), 1);
+ assert.equal(await page.locator('#paused .quota-share, #paused .quota-claim').count(), 0);
+ assert.equal(await page.locator('#paused').evaluate(el => /quota\.|\{(?:base|credit|time)\}/.test(el.textContent)), false);
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, `${build}/${lang}: paused card overflow`); checks += 4;
assert.deepEqual(errors, []); checks++;
await page.close();
}
- console.log(`${build}: paused reward card, quota UI, keyboard navigation, 23 locales, restored claim form and explicit continuation passed`);
+ console.log(`${build}: paused reward card in 23 locales, quota UI, keyboard navigation, restored claim form and explicit continuation passed`);
} finally { await browser.close(); }
}
console.log(`${checks} rendered UI assertions passed. Screenshots: ${output}`);
diff --git a/test/compass-quota.mjs b/test/compass-quota.mjs
index df1d72655..5702a5ba2 100644
--- a/test/compass-quota.mjs
+++ b/test/compass-quota.mjs
@@ -17,7 +17,7 @@ for (const browser of ['chrome', 'firefox']) {
const { RunUiJournal, runUiUpdatesForCurrentTask } = await import(new URL('run-ui-journal.js', base));
const { runDetachedWithReconnect } = await import(new URL('run-reconnect.js', base));
const { Agent } = await import(new URL('agent/agent.js', base));
- const { formatQuotaUsd, socialComposer, SOCIAL_PROMOTION_ENABLED } = await import(new URL('ui/compass-quota.js', base));
+ const { createQuotaController, formatQuotaUsd, socialComposer, SOCIAL_PROMOTION_ENABLED } = await import(new URL('ui/compass-quota.js', base));
const { quotaTranslations } = await import(new URL('ui/locales/compass-quota-copy.mjs', base));
const payload = {
error: { code: 'webbrain_cloud_free_tier_exceeded', message: 'Weekly quota exhausted.' },
@@ -84,12 +84,61 @@ for (const browser of ['chrome', 'firefox']) {
assert.equal(events.find(e => e.type === 'quota')?.data.quota.usage.base_weekly_allowance_usd, 0.375);
});
test(`${browser}: the sharing reward is paused and every locale can show the plain allowance`, () => {
+ // Pins the shipped default (docs/compass-quota-rollout.md): bringing the
+ // reward back means flipping the flag in both builds and this expectation.
assert.equal(SOCIAL_PROMOTION_ENABLED, false);
for (const [code, copy] of Object.entries(quotaTranslations)) {
assert.match(copy['quota.allowance'], /\{base\}/, code);
assert.doesNotMatch(copy['quota.allowance'], /\{credit\}/, code);
}
});
+ test(`${browser}: the shipped quota card offers no reward and sends no reward telemetry`, async () => {
+ const node = tag => ({
+ tag, children: [], dataset: {}, attributes: {}, listeners: [], textContent: '', className: '', hidden: false,
+ classList: { add() {}, remove() {} },
+ append(...nodes) { this.children.push(...nodes); },
+ replaceChildren(...nodes) { this.children = nodes; },
+ setAttribute(key, value) { this.attributes[key] = String(value); },
+ addEventListener(type, fn) { if (type === 'click') this.listeners.push(fn); },
+ click() { this.listeners.forEach(fn => fn()); },
+ });
+ const all = root => [root, ...root.children.flatMap(all)];
+ const previous = globalThis.document;
+ globalThis.document = { createElement: node };
+ try {
+ const requests = []; const continued = [];
+ let claim = { eligible: false, status: 'redeemed', remaining_credit_usd: 0 };
+ const quota = { code: 'webbrain_cloud_free_tier_exceeded', subscribe_url: 'https://buy.stripe.com/test',
+ usage: { tier: 'free', base_weekly_allowance_usd: 0.375, social_claim: claim } };
+ const copy = quotaTranslations.en;
+ const controller = createQuotaController({
+ t: (key, params = {}) => String(copy[key] || key).replace(/\{(\w+)\}/g, (_, k) => params[k] ?? ''),
+ locale: () => 'en', openUrl() {}, persist() {},
+ continueTask: (_button, context) => continued.push(context),
+ request: async (path, body) => { requests.push({ path, body }); return path === '/usage' ? { ...quota.usage, social_claim: claim } : {}; },
+ });
+ const host = Object.assign(node('div'), { isConnected: true });
+ assert.equal(controller.mount(host, quota, { mode: 'act' }), true);
+ await new Promise(resolve => setImmediate(resolve));
+ const nodes = all(host);
+ assert.equal(nodes.some(n => /quota-share|quota-claim/.test(n.className)), false, 'no share button or claim form');
+ assert.deepEqual(nodes.find(n => n.className === 'quota-choices').children.map(n => n.className), ['subscribe-btn']);
+ assert.equal(nodes.find(n => n.className === 'quota-balance').textContent, 'Weekly allowance: $0.375');
+ nodes.find(n => n.className === 'subscribe-resume-btn').click();
+ assert.equal(continued.length, 1);
+ assert.equal(requests.some(r => r.path.startsWith('/promotions/social')), false);
+ assert.equal(requests.some(r => r.body?.event === 'continuation_after_reward'), false, 'no reward telemetry while paused');
+ // Credit earned before the pause stays visible; a sub-display remainder does not.
+ claim = { ...claim, remaining_credit_usd: 0.25 };
+ await controller.refreshAll();
+ assert.match(nodes.find(n => n.className === 'quota-balance').textContent, /Reward balance: \$0\.25/);
+ claim = { ...claim, remaining_credit_usd: 4e-7 };
+ await controller.refreshAll();
+ assert.equal(nodes.find(n => n.className === 'quota-balance').textContent, 'Weekly allowance: $0.375');
+ } finally {
+ if (previous === undefined) delete globalThis.document; else globalThis.document = previous;
+ }
+ });
test(`${browser}: structured card routing works without a Subscribe string`, () => {
const panel = fs.readFileSync(new URL('ui/sidepanel.js', base), 'utf8');
const start = panel.indexOf('function renderSubscribeError(');