Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(updates-consent): retain account choices and reclaim active receipts
Sebastian B941f3c4eafdb
diff --git a/electron/updates-consent.d.mts b/electron/updates-consent.d.mtsindex ec84fc49a5..2a54e4d208 100644--- a/electron/updates-consent.d.mts+++ b/electron/updates-consent.d.mts@@ -4,6 +4,8 @@ export declare const UPDATES_CONSENT_STATUSES: readonly UpdatesConsentStatus[];export interface UpdatesConsentRecord {status: UpdatesConsentStatus; version: string; at: number;account?: string; email?: string; receipt?: string; replacedReceipts?: string[]; pending?: true;+ receiptEmails?: Record<string, string>;+ pendingAccounts?: { status: UpdatesConsentStatus; version: string; at: number; account: string }[];}export declare function parseUpdatesConsent(value: unknown): UpdatesConsentRecord | null;export declare function parseAccountConsent(result: unknown): { status: UpdatesConsentStatus; textVersion: string } | null;diff --git a/electron/updates-consent.mjs b/electron/updates-consent.mjsindex faffecdc40..9340500ef4 100644--- a/electron/updates-consent.mjs+++ b/electron/updates-consent.mjs@@ -15,27 +15,37 @@ const STATE_WAIT_MS = 8_000;* The record kept on this computer. `account`: the MausBot Cloud account the answer belongs to (given while signed in,* or carried over to it). `email`: typed while signed out. `receipt`: the Admin's handle for that email-only answer,* the only way this computer can withdraw it. `replacedReceipts`: receipts of email-only opt-ins that a later answer- * replaced (another email, or an account), each kept until its withdrawal succeeds. `pending`: the Admin has not- * recorded it yet.+ * replaced (another email, or an account), each kept until its withdrawal succeeds. `receiptEmails`: the addresses+ * those receipts belong to. `pendingAccounts`: unsent choices retained for other accounts. `pending`: the Admin+ * has not recorded this answer yet.*/export function parseUpdatesConsent(value) {if (!value || typeof value !== "object" || Array.isArray(value)) return null;if (!UPDATES_CONSENT_STATUSES.includes(value.status) || !VERSION.test(value.version ?? "") || !Number.isSafeInteger(value.at) || value.at <= 0) return null;const email = cleanEmail(value.email);+ const pendingAccounts = (Array.isArray(value.pendingAccounts) ? value.pendingAccounts : []).flatMap(choice => {+ const parsed = parseUpdatesConsent({ status: choice?.status, version: choice?.version, at: choice?.at, account: choice?.account });+ return parsed?.account ? [parsed] : [];+ });return {status: value.status, version: value.version, at: value.at,...(text(value.account, 128) ? { account: value.account } : {}),...(email ? { email } : {}),...(typeof value.receipt === "string" && RECEIPT.test(value.receipt) ? { receipt: value.receipt } : {}),- ...withReplacedReceipts({}, Array.isArray(value.replacedReceipts) ? value.replacedReceipts.filter(receipt => typeof receipt === "string" && RECEIPT.test(receipt)) : []),+ ...withReplacedReceipts({ receiptEmails: value.receiptEmails }, Array.isArray(value.replacedReceipts) ? value.replacedReceipts.filter(receipt => typeof receipt === "string" && RECEIPT.test(receipt)) : []),+ ...(pendingAccounts.length ? { pendingAccounts } : {}),...(value.pending === true ? { pending: true } : {}),};}-function withReplacedReceipts(record, receipts, withdrawn = null) {- const { replacedReceipts = [], ...rest } = record;+function withReplacedReceipts(record, receipts, withdrawn = null, email = null) {+ const { replacedReceipts = [], receiptEmails, ...rest } = record;const left = [...new Set([...replacedReceipts, ...receipts])].filter(receipt => receipt && receipt !== withdrawn);- return left.length ? { ...rest, replacedReceipts: left } : rest;+ const emails = Object.fromEntries(left.flatMap(receipt => {+ const address = cleanEmail(receipts.includes(receipt) && email ? email : receiptEmails?.[receipt]);+ return address ? [[receipt, address]] : [];+ }));+ return { ...rest, ...(left.length ? { replacedReceipts: left } : {}), ...(Object.keys(emails).length ? { receiptEmails: emails } : {}) };}/** The Admin's answer for an account: null while it has no recorded choice. Anything else unreadable throws. */@@ -59,7 +69,22 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.nowconst current = client()?.state();return current?.status === "connected" && current.account ? current.account : null;};- const save = record => { prefs.setUpdatesConsent(record); onChange(); };+ const save = (record, recorded = null) => {+ const previous = prefs.updatesConsent();+ const pendingAccounts = new Map((previous?.pendingAccounts ?? []).map(choice => [choice.account, choice]));+ if (previous?.pending && previous.account) pendingAccounts.set(previous.account,+ { status: previous.status, version: previous.version, at: previous.at, account: previous.account });+ if (recorded) {+ const pending = pendingAccounts.get(recorded.account);+ if (pending?.status === recorded.status && pending.version === recorded.version && pending.at === recorded.at) {+ pendingAccounts.delete(recorded.account);+ if (record.account === recorded.account) record = { ...record, pending: false };+ }+ }+ pendingAccounts.delete(record.account);+ prefs.setUpdatesConsent({ ...record, pendingAccounts: [...pendingAccounts.values()] });+ onChange();+ };async function signedOutSync(local, sameAnswer) {if (!local?.pending || local.account) return;@@ -69,7 +94,7 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.nowconst latest = prefs.updatesConsent();if (!latest) return;if (!latest.account && latest.email === local.email && (latest.status === "opted_in" || !latest.receipt)) save(withReplacedReceipts({ ...latest, receipt }, [], receipt));- else save(withReplacedReceipts(latest, [receipt]));+ else save(withReplacedReceipts(latest, [receipt], null, local.email));} else if (local.status !== "opted_in" && local.receipt) {await client().withdrawUpdatesConsent({ status: local.status, receipt: local.receipt });if (sameAnswer()) save({ ...local, pending: false });@@ -86,19 +111,33 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.nowasync function reconcile(sameAnswer, fresh) {if (!client() || !await available()) return;+ const local = prefs.updatesConsent();+ if (!signedIn() && local?.pending && local.status === "opted_in" && local.email &&+ local.replacedReceipts?.some(receipt => !local.receiptEmails?.[receipt])) {+ await send(sameAnswer, fresh);+ if (fresh()) await withdrawReplaced();+ return;+ }await withdrawReplaced();await send(sameAnswer, fresh);await withdrawReplaced();}async function send(sameAnswer, fresh) {- const local = prefs.updatesConsent(), who = signedIn();+ let local = prefs.updatesConsent();+ const who = signedIn();if (!who) return signedOutSync(local, sameAnswer);+ const pending = local?.pendingAccounts?.find(choice => choice.account === who.id);+ if (pending) {+ save({ ...local, ...pending, pending: true });+ local = prefs.updatesConsent();+ }const { receipt, ...rest } = local ?? {};- const keep = record => { if (fresh()) save(withReplacedReceipts(record, [receipt])); };+ const keep = record => { if (fresh()) save(withReplacedReceipts({ ...record, receiptEmails: local?.receiptEmails }, [receipt], null, local?.email)); };if (local?.pending && local.account === who.id) {await client().recordUpdatesConsent(local.status, local.version);- keep({ ...rest, pending: false });+ if (fresh()) keep({ ...rest, pending: false });+ else save(prefs.updatesConsent(), local);return;}const remote = parseAccountConsent(await client().updatesConsent());@@ -149,13 +188,16 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.nowif (input.email && !typed) throw new Error("Enter a valid email address.");const who = signedIn(), previous = prefs.updatesConsent();const email = !who && status === "opted_in" ? typed ?? previous?.email ?? null : previous?.email ?? null;+ const returningReceipt = !who && status === "opted_in" && email+ ? previous?.replacedReceipts?.find(receipt => previous.receiptEmails?.[receipt] === email) : null;const sameReceipt = !who && (status !== "opted_in" || email === null ||(previous?.status === "opted_in" && email === previous.email));choices++;save(withReplacedReceipts({ status, version: UPDATES_CONSENT_VERSION, at: now(), pending: true,...(who ? { account: who.id } : {}), ...(email ? { email } : {}),- ...(sameReceipt && previous?.receipt ? { receipt: previous.receipt } : {}), replacedReceipts: previous?.replacedReceipts },- sameReceipt ? [] : [previous?.receipt]));+ ...(returningReceipt || (sameReceipt && previous?.receipt) ? { receipt: returningReceipt || previous.receipt } : {}),+ replacedReceipts: previous?.replacedReceipts, receiptEmails: previous?.receiptEmails },+ sameReceipt ? [] : [previous?.receipt], returningReceipt, previous?.email));await sync().catch(() => {});return snapshot();}diff --git a/electron/updates-consent.node-test.mjs b/electron/updates-consent.node-test.mjsindex 1d10aefaf5..8cee0948cb 100644--- a/electron/updates-consent.node-test.mjs+++ b/electron/updates-consent.node-test.mjs@@ -43,6 +43,7 @@ async function world(t) {return send(200, { ok: true });}if (!bearer) return send(401, { error: "invalid_token" });+ if (req.method === "POST" && f.failAccountPosts > 0) { f.failAccountPosts--; return send(503, { error: "unavailable" }); }if (req.method === "POST") f.account = { status: body.status, textVersion: body.textVersion, source: "desktop", decidedAt: f.now };return send(200, { cloudContractVersion: 1, consent: req.method === "GET" ? previous : f.account });}@@ -266,7 +267,7 @@ test("signed out, an overtaken email is withdrawn before its replacement even afconst k = await world(t);k.failWithdrawals = 2;await overtake(k, { status: "opted_in", email: "[email protected]" }, { status: "opted_in", email: "[email protected]" });- assert.deepEqual(k.saved.updatesConsent, { status: "opted_in", version: UPDATES_CONSENT_VERSION, at: k.now, email: "[email protected]", replacedReceipts: [receiptOf("[email protected]")], pending: true });+ assert.deepEqual(k.saved.updatesConsent, { status: "opted_in", version: UPDATES_CONSENT_VERSION, at: k.now, email: "[email protected]", replacedReceipts: [receiptOf("[email protected]")], receiptEmails: { [receiptOf("[email protected]")]: "[email protected]" }, pending: true });k.launch();await k.consent.sync();assert.deepEqual(k.requests.map(request => request.body), [@@ -392,7 +393,7 @@ test("a matching account answer queues an older email receipt until its withdrawawait assert.rejects(f.consent.sync(), /Cloud request failed/);assert.equal(f.emails.get("[email protected]"), "opted_in");assert.deepEqual(f.saved.updatesConsent, { status, version: "2026-10-24", at: f.now,- account: "account-1", email: "[email protected]", replacedReceipts: [receiptOf("[email protected]")] });+ account: "account-1", email: "[email protected]", replacedReceipts: [receiptOf("[email protected]")], receiptEmails: { [receiptOf("[email protected]")]: "[email protected]" } });f.launch();await f.consent.sync();assert.equal(f.emails.get("[email protected]"), "withdrawn");@@ -511,7 +512,7 @@ test("an unanswered account withdraws another account's retained email receipt wf.launch();await f.consent.sync();assert.equal(f.emails.get("[email protected]"), "withdrawn");- assert.deepEqual(afterFailure, { ...ownerAnswer, replacedReceipts: [receiptOf("[email protected]")] });+ assert.deepEqual(afterFailure, { ...ownerAnswer, replacedReceipts: [receiptOf("[email protected]")], receiptEmails: { [receiptOf("[email protected]")]: "[email protected]" } });assert.deepEqual(f.saved.updatesConsent, ownerAnswer);const state = await f.consent.state();assert.equal(state.due, true);@@ -524,3 +525,122 @@ test("an unanswered account withdraws another account's retained email receipt w{ status: "withdrawn", receipt: receiptOf("[email protected]") }]);});});++test("a failed account withdrawal survives another account's answer and restarts until its owner retries", async t => {+ for (const choice of [null, "opted_in"]) await t.test(choice ?? "read only", async t => {+ const f = await world(t);+ await f.signInNow();+ await f.consent.choose({ status: "opted_in" });+ const original = structuredClone(f.account), held = Promise.withResolvers();+ t.after(() => held.resolve());+ const first = f.requests.length;+ f.gate = held.promise;+ const withdrawing = f.consent.choose({ status: "withdrawn" });+ await until(() => f.requests.length === first + 1);+ await f.client.signOut();+ f.accountId = "account-2";+ f.accessToken = `omc_${"B".repeat(43)}`;+ f.account = { status: "declined", textVersion: UPDATES_CONSENT_VERSION, source: "cloud_page", decidedAt: f.now };+ await f.signInNow();+ f.failAccountPosts = 1;+ f.gate = null;+ held.resolve();+ await withdrawing;+ assert.deepEqual(f.requests.slice(first).map(({ method }) => method), ["POST", "GET"]);+ assert.equal(f.account.status, "declined");+ assert.equal((await f.consent.state()).status, "declined");+ if (choice) {+ f.failAccountPosts = 1;+ await f.consent.choose({ status: choice });+ assert.equal(f.account.status, "declined");+ }+ f.launch();+ await f.consent.sync();+ assert.equal(f.account.status, choice ?? "declined");+ await f.client.signOut();+ f.accountId = "account-1";+ f.accessToken = accessToken;+ f.account = original;+ await f.signInNow();+ f.failAccountPosts = 1;+ await assert.rejects(f.consent.sync(), /Cloud request failed/);+ f.launch();+ const retry = f.requests.length;+ f.consent.accountChanged(f.client.state());+ await f.consent.sync();+ assert.equal(f.account.status, "withdrawn");+ assert.deepEqual(f.requests.slice(retry).map(({ method, body }) => ({ method, body })), [+ { method: "POST", body: { status: "withdrawn", textVersion: UPDATES_CONSENT_VERSION } }]);+ assert.equal(f.saved.updatesConsent.pending, undefined);+ });+});++test("signed out, returning to a queued email after restart never withdraws its active opt-in when resubmission fails", async t => {+ for (const legacy of [false, true]) await t.test(`legacy queue=${legacy}`, async t => {+ const f = await world(t);+ await f.consent.choose({ status: "opted_in", email: "[email protected]" });+ f.failWithdrawals = 1;+ await f.consent.choose({ status: "opted_in", email: "[email protected]" });+ assert.equal(f.emails.get("[email protected]"), "opted_in");+ assert.equal(f.saved.updatesConsent.pending, true);+ if (legacy) delete f.saved.updatesConsent.receiptEmails;+ f.launch();+ const held = Promise.withResolvers(), first = f.requests.length;+ t.after(() => held.resolve());+ f.gate = held.promise;+ const returning = f.consent.choose({ status: "opted_in", email: " [email protected] " });+ await until(() => f.requests.length === first + 1);+ f.failOptIns = 1;+ f.gate = null;+ held.resolve();+ await returning;+ assert.equal(f.emails.get("[email protected]"), "opted_in");+ assert.deepEqual(f.saved.updatesConsent, { status: "opted_in", version: UPDATES_CONSENT_VERSION, at: f.now,+ email: "[email protected]", ...(legacy ? { replacedReceipts: [RECEIPT] } : { receipt: RECEIPT }), pending: true });+ assert.deepEqual(f.requests.slice(first).map(request => request.body.status), ["opted_in"]);+ f.launch();+ await f.consent.sync();+ assert.equal(f.emails.get("[email protected]"), "opted_in");+ assert.equal(f.saved.updatesConsent.pending, undefined);+ await f.consent.choose({ status: "withdrawn" });+ assert.equal(f.emails.get("[email protected]"), "withdrawn");+ });+});++test("a successful account post clears its pending choice even if another account is current", async t => {+ for (const answerOnB of [false, true]) await t.test(`answer on B=${answerOnB}`, async t => {+ let saved = null, current = "account-1";+ const statuses = new Map([["account-1", "opted_in"], ["account-2", "declined"]]), sent = [];+ const held = Promise.withResolvers();+ t.after(() => held.resolve());+ const client = {+ state: () => ({ status: "connected", account: { id: current, email: "[email protected]" } }),+ async updatesConsent() {+ sent.push({ method: "GET", account: current });+ return { cloudContractVersion: 1, consent: { status: statuses.get(current), textVersion: UPDATES_CONSENT_VERSION } };+ },+ async recordUpdatesConsent(status) {+ const account = current;+ sent.push({ method: "POST", account, status });+ if (account === "account-1" && status === "withdrawn") await held.promise;+ statuses.set(account, status);+ },+ };+ const prefs = createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });+ const consent = createUpdatesConsent({ prefs, account: () => client, available: () => true });+ await consent.choose({ status: "opted_in" });+ const withdrawing = consent.choose({ status: "withdrawn" });+ await until(() => sent.length === 2);+ current = "account-2";+ const changing = answerOnB ? consent.choose({ status: "opted_in" }) : null;+ if (changing) await until(() => saved.updatesConsent.account === current);+ held.resolve();+ await Promise.all([withdrawing, changing]);+ statuses.set("account-1", "opted_in");+ current = "account-1";+ const first = sent.length;+ await consent.sync();+ assert.equal(statuses.get("account-1"), "opted_in");+ assert.deepEqual(sent.slice(first), [{ method: "GET", account: "account-1" }]);+ });+});