From cf4f2c1618e55f623a302a151bdbcd8a59542865 Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 21:31:47 +0200 Subject: [PATCH 01/13] fix(web): stay on billing after subscription cancellation Reload the current billing page instead of navigating home after cancellation. Add regression coverage for refresh-on-success and error handling. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.test.ts | 69 +++++++++++++++++++++++++++++ web/app/pages/billing/index.vue | 2 +- 2 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 web/app/pages/billing/index.test.ts diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts new file mode 100644 index 000000000..61b9d8ea8 --- /dev/null +++ b/web/app/pages/billing/index.test.ts @@ -0,0 +1,69 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' +import { runInNewContext } from 'node:vm' +import ts from 'typescript' +import { parse } from 'vue/compiler-sfc' + +const { descriptor } = parse( + readFileSync(new URL('./index.vue', import.meta.url), 'utf8'), +) +const script = ts.createSourceFile( + 'billing.ts', + descriptor.scriptSetup!.content, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, +) +const cancelPlan = script.statements.find( + (statement) => + ts.isFunctionDeclaration(statement) && + statement.name?.text === 'cancelPlan', +)! +const { outputText } = ts.transpileModule(cancelPlan.getText(script), { + compilerOptions: { target: ts.ScriptTarget.ESNext }, +}) + +function setupCancellation(cancelSubscription: () => Promise) { + let reloads = 0 + const navigations: string[] = [] + const notifications: { message: string; type: string }[] = [] + const loading = { value: false } + const cancel = runInNewContext(`${outputText}\ncancelPlan`, { + loading, + billingStore: { cancelSubscription }, + notificationsStore: { + addNotification: (notification: { message: string; type: string }) => { + notifications.push(notification) + }, + }, + window: { location: { reload: () => reloads++ } }, + navigateTo: (path: string) => navigations.push(path), + getApiErrorMessage: (_error: unknown, fallback: string) => fallback, + }) as () => Promise + + return { cancel, loading, notifications, navigations, reloads: () => reloads } +} + +test('successful cancellation refreshes the billing page without navigating away', async () => { + const pending = setupCancellation(async () => {}) + + await pending.cancel() + + assert.equal(pending.reloads(), 1) + assert.deepEqual(pending.navigations, []) + assert.equal(pending.notifications.at(-1)?.type, 'success') +}) + +test('failed cancellation stays on the page without refreshing and displays an error', async () => { + const pending = setupCancellation(async () => { + throw new Error('Cancellation failed') + }) + + await pending.cancel() + + assert.equal(pending.reloads(), 0) + assert.deepEqual(pending.navigations, []) + assert.equal(pending.notifications.at(-1)?.type, 'error') + assert.equal(pending.loading.value, false) +}) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 1106358f2..83c455601 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -231,7 +231,7 @@ async function cancelPlan() { message: 'Subscription cancelled successfully', type: 'success', }) - navigateTo('/') + window.location.reload() } catch (error: unknown) { notificationsStore.addNotification({ message: getApiErrorMessage( From e33dda39542e6dfe87a9525f7a7d6641d133fa1e Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 21:32:57 +0200 Subject: [PATCH 02/13] fix(web): refresh cancelled subscription status in place Reload account data without reloading the browser or navigating away. Close the confirmation dialog and preserve the success notification. Report account refresh failures separately from cancellation failures. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.test.ts | 50 ++++++++++++++++++++++++++--- web/app/pages/billing/index.vue | 23 ++++++++++--- 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts index 61b9d8ea8..8d20080f2 100644 --- a/web/app/pages/billing/index.test.ts +++ b/web/app/pages/billing/index.test.ts @@ -24,13 +24,26 @@ const { outputText } = ts.transpileModule(cancelPlan.getText(script), { compilerOptions: { target: ts.ScriptTarget.ESNext }, }) -function setupCancellation(cancelSubscription: () => Promise) { +function setupCancellation( + cancelSubscription: () => Promise, + refreshError?: Error, +) { let reloads = 0 const navigations: string[] = [] const notifications: { message: string; type: string }[] = [] const loading = { value: false } + const dialog = { value: true } + const authStore = { + user: { subscription_status: 'active' }, + loadUser: async () => { + if (refreshError) throw refreshError + authStore.user = { subscription_status: 'cancelled' } + }, + } const cancel = runInNewContext(`${outputText}\ncancelPlan`, { loading, + dialog, + authStore, billingStore: { cancelSubscription }, notificationsStore: { addNotification: (notification: { message: string; type: string }) => { @@ -42,16 +55,27 @@ function setupCancellation(cancelSubscription: () => Promise) { getApiErrorMessage: (_error: unknown, fallback: string) => fallback, }) as () => Promise - return { cancel, loading, notifications, navigations, reloads: () => reloads } + return { + cancel, + loading, + dialog, + authStore, + notifications, + navigations, + reloads: () => reloads, + } } -test('successful cancellation refreshes the billing page without navigating away', async () => { +test('successful cancellation updates billing status in place without a browser reload', async () => { const pending = setupCancellation(async () => {}) await pending.cancel() - assert.equal(pending.reloads(), 1) + assert.equal(pending.reloads(), 0) assert.deepEqual(pending.navigations, []) + assert.equal(pending.authStore.user.subscription_status, 'cancelled') + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) assert.equal(pending.notifications.at(-1)?.type, 'success') }) @@ -66,4 +90,22 @@ test('failed cancellation stays on the page without refreshing and displays an e assert.deepEqual(pending.navigations, []) assert.equal(pending.notifications.at(-1)?.type, 'error') assert.equal(pending.loading.value, false) + assert.equal(pending.authStore.user.subscription_status, 'active') + assert.equal(pending.dialog.value, true) +}) + +test('a refresh failure after cancellation reports the refresh error rather than a cancellation failure', async () => { + const pending = setupCancellation( + async () => {}, + new Error('Account fetch failed'), + ) + + await pending.cancel() + + assert.equal(pending.reloads(), 0) + assert.deepEqual(pending.navigations, []) + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.at(-1)?.type, 'error') + assert.match(pending.notifications.at(-1)!.message, /cancelled.*refresh/) }) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 83c455601..bdc79cdcc 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -227,19 +227,34 @@ async function cancelPlan() { loading.value = true try { await billingStore.cancelSubscription() + } catch (error: unknown) { notificationsStore.addNotification({ - message: 'Subscription cancelled successfully', - type: 'success', + message: getApiErrorMessage( + error, + 'We could not cancel your subscription.', + ), + type: 'error', }) - window.location.reload() + loading.value = false + return + } + + dialog.value = false + notificationsStore.addNotification({ + message: 'Subscription cancelled successfully', + type: 'success', + }) + try { + await authStore.loadUser() } catch (error: unknown) { notificationsStore.addNotification({ message: getApiErrorMessage( error, - 'We could not cancel your subscription.', + 'Your subscription was cancelled, but we could not refresh your billing details.', ), type: 'error', }) + } finally { loading.value = false } } From 50cc2d96d83682a87d1256539bf759d779fabf1e Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 21:38:13 +0200 Subject: [PATCH 03/13] fix(web): handle delayed cancellation status updates Poll account data briefly while showing a cancelled pending-details card. Avoid showing stale active-plan controls while the webhook is pending. Keep cancellation success context when account refresh returns an API error. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.test.ts | 53 +++++++++++++++++++++++++---- web/app/pages/billing/index.vue | 50 +++++++++++++++++++++++---- 2 files changed, 90 insertions(+), 13 deletions(-) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts index 8d20080f2..ae12ee4e5 100644 --- a/web/app/pages/billing/index.test.ts +++ b/web/app/pages/billing/index.test.ts @@ -4,6 +4,7 @@ import { test } from 'node:test' import { runInNewContext } from 'node:vm' import ts from 'typescript' import { parse } from 'vue/compiler-sfc' +import { getApiErrorMessage } from '../../utils/api-error' const { descriptor } = parse( readFileSync(new URL('./index.vue', import.meta.url), 'utf8'), @@ -26,23 +27,30 @@ const { outputText } = ts.transpileModule(cancelPlan.getText(script), { function setupCancellation( cancelSubscription: () => Promise, - refreshError?: Error, + refreshError?: unknown, + statuses = ['cancelled'], ) { let reloads = 0 + let refreshes = 0 const navigations: string[] = [] const notifications: { message: string; type: string }[] = [] const loading = { value: false } const dialog = { value: true } + const cancellationPending = { value: false } const authStore = { user: { subscription_status: 'active' }, loadUser: async () => { if (refreshError) throw refreshError - authStore.user = { subscription_status: 'cancelled' } + authStore.user = { + subscription_status: + statuses[Math.min(refreshes++, statuses.length - 1)]!, + } }, } const cancel = runInNewContext(`${outputText}\ncancelPlan`, { loading, dialog, + cancellationPending, authStore, billingStore: { cancelSubscription }, notificationsStore: { @@ -52,17 +60,20 @@ function setupCancellation( }, window: { location: { reload: () => reloads++ } }, navigateTo: (path: string) => navigations.push(path), - getApiErrorMessage: (_error: unknown, fallback: string) => fallback, + getApiErrorMessage, + setTimeout: (callback: () => void) => callback(), }) as () => Promise return { cancel, loading, dialog, + cancellationPending, authStore, notifications, navigations, reloads: () => reloads, + refreshes: () => refreshes, } } @@ -76,6 +87,7 @@ test('successful cancellation updates billing status in place without a browser assert.equal(pending.authStore.user.subscription_status, 'cancelled') assert.equal(pending.dialog.value, false) assert.equal(pending.loading.value, false) + assert.equal(pending.cancellationPending.value, false) assert.equal(pending.notifications.at(-1)?.type, 'success') }) @@ -95,10 +107,9 @@ test('failed cancellation stays on the page without refreshing and displays an e }) test('a refresh failure after cancellation reports the refresh error rather than a cancellation failure', async () => { - const pending = setupCancellation( - async () => {}, - new Error('Account fetch failed'), - ) + const pending = setupCancellation(async () => {}, { + data: { message: 'Account fetch failed' }, + }) await pending.cancel() @@ -108,4 +119,32 @@ test('a refresh failure after cancellation reports the refresh error rather than assert.equal(pending.loading.value, false) assert.equal(pending.notifications.at(-1)?.type, 'error') assert.match(pending.notifications.at(-1)!.message, /cancelled.*refresh/) + assert.match(pending.notifications.at(-1)!.message, /Account fetch failed/) +}) + +test('cancellation waits for the webhook when the first account response is stale', async () => { + const pending = setupCancellation(async () => {}, undefined, [ + 'active', + 'cancelled', + ]) + + await pending.cancel() + + assert.equal(pending.authStore.user.subscription_status, 'cancelled') + assert.equal(pending.cancellationPending.value, false) + assert.ok(pending.refreshes() > 1) + assert.equal(pending.loading.value, false) + assert.equal(pending.reloads(), 0) +}) + +test('a delayed webhook leaves a visible pending state after bounded polling', async () => { + const pending = setupCancellation(async () => {}, undefined, ['active']) + + await pending.cancel() + + assert.equal(pending.cancellationPending.value, true) + assert.ok(pending.refreshes() > 1 && pending.refreshes() <= 20) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.at(-1)?.type, 'info') + assert.match(pending.notifications.at(-1)!.message, /cancelled.*updating/) }) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index bdc79cdcc..30732c5c3 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -39,6 +39,7 @@ const { formatDecimal, formatTimestamp } = useFilters() const loading = ref(true) const loadingSubscriptionPayments = ref(false) const dialog = ref(false) +const cancellationPending = ref(false) const subscriptionInvoiceDialog = ref(false) const payments = ref(null) const selectedPayment = ref(null) @@ -240,18 +241,35 @@ async function cancelPlan() { } dialog.value = false + cancellationPending.value = true notificationsStore.addNotification({ message: 'Subscription cancelled successfully', type: 'success', }) try { - await authStore.loadUser() + for (let attempt = 0; attempt < 10; attempt++) { + await authStore.loadUser() + if ( + authStore.user?.subscription_status === 'cancelled' || + authStore.user?.subscription_name === 'free' + ) { + cancellationPending.value = false + break + } + if (attempt < 9) { + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + } + if (cancellationPending.value) { + notificationsStore.addNotification({ + message: + 'Your subscription was cancelled. Your billing details are still updating; please check back shortly.', + type: 'info', + }) + } } catch (error: unknown) { notificationsStore.addNotification({ - message: getApiErrorMessage( - error, - 'Your subscription was cancelled, but we could not refresh your billing details.', - ), + message: `Your subscription was cancelled, but we could not refresh your billing details. ${getApiErrorMessage(error, 'Please try again later.')}`, type: 'error', }) } finally { @@ -318,7 +336,27 @@ onMounted(async () => {

Current Plan

- + +

+ Subscription cancelled +

+

+ Your billing details are still updating. +

+
+

Date: Tue, 24 Nov 2026 21:46:14 +0200 Subject: [PATCH 04/13] fix(web): keep cancellation dialog open for status refresh Limit the billing-status refresh wait to ten seconds, including slow requests. Keep the confirmation dialog open and non-dismissible while waiting. Emit one final notification rather than an initial and a follow-up toast. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.test.ts | 59 +++++++++++++++++++++++++++- web/app/pages/billing/index.vue | 60 ++++++++++++++++++----------- 2 files changed, 96 insertions(+), 23 deletions(-) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts index ae12ee4e5..956cc4693 100644 --- a/web/app/pages/billing/index.test.ts +++ b/web/app/pages/billing/index.test.ts @@ -1,6 +1,7 @@ import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' import { test } from 'node:test' +import { setImmediate } from 'node:timers/promises' import { runInNewContext } from 'node:vm' import ts from 'typescript' import { parse } from 'vue/compiler-sfc' @@ -32,6 +33,9 @@ function setupCancellation( ) { let reloads = 0 let refreshes = 0 + let elapsed = 0 + let deadlineCallback: (() => void) | undefined + const waitingStates: { dialog: boolean; notifications: number }[] = [] const navigations: string[] = [] const notifications: { message: string; type: string }[] = [] const loading = { value: false } @@ -61,7 +65,24 @@ function setupCancellation( window: { location: { reload: () => reloads++ } }, navigateTo: (path: string) => navigations.push(path), getApiErrorMessage, - setTimeout: (callback: () => void) => callback(), + Date: { now: () => elapsed }, + setTimeout: (callback: () => void, delay: number) => { + if (delay === 10000) { + deadlineCallback = callback + } else { + waitingStates.push({ + dialog: dialog.value, + notifications: notifications.length, + }) + elapsed += delay + callback() + if (elapsed >= 10000) deadlineCallback?.() + } + return 1 + }, + clearTimeout: () => { + deadlineCallback = undefined + }, }) as () => Promise return { @@ -74,6 +95,12 @@ function setupCancellation( navigations, reloads: () => reloads, refreshes: () => refreshes, + elapsed: () => elapsed, + expireDeadline: () => { + elapsed = 10000 + deadlineCallback?.() + }, + waitingStates, } } @@ -89,6 +116,7 @@ test('successful cancellation updates billing status in place without a browser assert.equal(pending.loading.value, false) assert.equal(pending.cancellationPending.value, false) assert.equal(pending.notifications.at(-1)?.type, 'success') + assert.equal(pending.notifications.length, 1) }) test('failed cancellation stays on the page without refreshing and displays an error', async () => { @@ -120,6 +148,7 @@ test('a refresh failure after cancellation reports the refresh error rather than assert.equal(pending.notifications.at(-1)?.type, 'error') assert.match(pending.notifications.at(-1)!.message, /cancelled.*refresh/) assert.match(pending.notifications.at(-1)!.message, /Account fetch failed/) + assert.equal(pending.notifications.length, 1) }) test('cancellation waits for the webhook when the first account response is stale', async () => { @@ -135,6 +164,9 @@ test('cancellation waits for the webhook when the first account response is stal assert.ok(pending.refreshes() > 1) assert.equal(pending.loading.value, false) assert.equal(pending.reloads(), 0) + assert.deepEqual(pending.waitingStates, [{ dialog: true, notifications: 0 }]) + assert.equal(pending.dialog.value, false) + assert.equal(pending.notifications.length, 1) }) test('a delayed webhook leaves a visible pending state after bounded polling', async () => { @@ -147,4 +179,29 @@ test('a delayed webhook leaves a visible pending state after bounded polling', a assert.equal(pending.loading.value, false) assert.equal(pending.notifications.at(-1)?.type, 'info') assert.match(pending.notifications.at(-1)!.message, /cancelled.*updating/) + assert.equal(pending.elapsed(), 10000) + assert.ok( + pending.waitingStates.every( + (state) => state.dialog && state.notifications === 0, + ), + ) + assert.equal(pending.dialog.value, false) + assert.equal(pending.notifications.length, 1) +}) + +test('the dialog closes at ten seconds even if the account refresh is still in flight', async () => { + const pending = setupCancellation(async () => {}) + pending.authStore.loadUser = () => new Promise(() => {}) + const cancellation = pending.cancel() + await setImmediate() + + assert.equal(pending.dialog.value, true) + assert.equal(pending.notifications.length, 0) + pending.expireDeadline() + await cancellation + + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.length, 1) + assert.equal(pending.notifications[0]?.type, 'info') }) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 30732c5c3..481e92ed7 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -240,32 +240,43 @@ async function cancelPlan() { return } - dialog.value = false cancellationPending.value = true - notificationsStore.addNotification({ - message: 'Subscription cancelled successfully', - type: 'success', - }) + const deadline = Date.now() + 10000 + let timeout: ReturnType | undefined try { - for (let attempt = 0; attempt < 10; attempt++) { - await authStore.loadUser() - if ( - authStore.user?.subscription_status === 'cancelled' || - authStore.user?.subscription_name === 'free' - ) { - cancellationPending.value = false - break - } - if (attempt < 9) { - await new Promise((resolve) => setTimeout(resolve, 1000)) - } - } + await Promise.race([ + (async () => { + while (Date.now() < deadline) { + await authStore.loadUser() + if ( + authStore.user?.subscription_status === 'cancelled' || + authStore.user?.subscription_name === 'free' + ) { + cancellationPending.value = false + return + } + const remaining = deadline - Date.now() + if (remaining <= 0) return + await new Promise((resolve) => + setTimeout(resolve, Math.min(1000, remaining)), + ) + } + })(), + new Promise((resolve) => { + timeout = setTimeout(resolve, 10000) + }), + ]) if (cancellationPending.value) { notificationsStore.addNotification({ message: 'Your subscription was cancelled. Your billing details are still updating; please check back shortly.', type: 'info', }) + } else { + notificationsStore.addNotification({ + message: 'Subscription cancelled successfully', + type: 'success', + }) } } catch (error: unknown) { notificationsStore.addNotification({ @@ -273,6 +284,8 @@ async function cancelPlan() { type: 'error', }) } finally { + clearTimeout(timeout) + dialog.value = false loading.value = false } } @@ -337,7 +350,7 @@ onMounted(async () => { { @@ -463,6 +478,7 @@ onMounted(async () => { Keep Subscription From aa308c9960d185ff0873f1aa71bd9d6006ba1b92 Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 21:48:21 +0200 Subject: [PATCH 05/13] fix(web): stop cancellation refresh after leaving billing Stop scheduling refreshes and suppress notifications when billing unmounts. Reveal the final plan card when late account data confirms cancellation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.test.ts | 39 ++++++++++++++++++++++++++++- web/app/pages/billing/index.vue | 23 +++++++++++++++-- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts index 956cc4693..2fbe0b4d0 100644 --- a/web/app/pages/billing/index.test.ts +++ b/web/app/pages/billing/index.test.ts @@ -25,6 +25,13 @@ const cancelPlan = script.statements.find( const { outputText } = ts.transpileModule(cancelPlan.getText(script), { compilerOptions: { target: ts.ScriptTarget.ESNext }, }) +const unmountHook = script.statements.find( + (statement) => + ts.isExpressionStatement(statement) && + ts.isCallExpression(statement.expression) && + statement.expression.expression.getText(script) === 'onBeforeUnmount', +) +const unmountCode = unmountHook?.getText(script) ?? '' function setupCancellation( cancelSubscription: () => Promise, @@ -35,6 +42,7 @@ function setupCancellation( let refreshes = 0 let elapsed = 0 let deadlineCallback: (() => void) | undefined + let unmount = () => {} const waitingStates: { dialog: boolean; notifications: number }[] = [] const navigations: string[] = [] const notifications: { message: string; type: string }[] = [] @@ -51,10 +59,15 @@ function setupCancellation( } }, } - const cancel = runInNewContext(`${outputText}\ncancelPlan`, { + const cancel = runInNewContext(`${unmountCode}\n${outputText}\ncancelPlan`, { loading, dialog, cancellationPending, + billingPageActive: true, + stopCancellationWait: undefined, + onBeforeUnmount: (callback: () => void) => { + unmount = callback + }, authStore, billingStore: { cancelSubscription }, notificationsStore: { @@ -101,6 +114,7 @@ function setupCancellation( deadlineCallback?.() }, waitingStates, + unmount: () => unmount(), } } @@ -205,3 +219,26 @@ test('the dialog closes at ten seconds even if the account refresh is still in f assert.equal(pending.notifications.length, 1) assert.equal(pending.notifications[0]?.type, 'info') }) + +test('leaving billing stops polling and prevents a notification on the next page', async () => { + const pending = setupCancellation(async () => {}) + let resolveRefresh!: () => void + let refreshes = 0 + pending.authStore.loadUser = async () => { + refreshes++ + await new Promise((resolve) => { + resolveRefresh = resolve + }) + } + const cancellation = pending.cancel() + await setImmediate() + + pending.unmount() + pending.expireDeadline() + await cancellation + resolveRefresh() + await setImmediate() + + assert.equal(pending.notifications.length, 0) + assert.equal(refreshes, 1) +}) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 481e92ed7..3ff2e1de4 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -40,6 +40,13 @@ const loading = ref(true) const loadingSubscriptionPayments = ref(false) const dialog = ref(false) const cancellationPending = ref(false) +let billingPageActive = true +let stopCancellationWait: (() => void) | undefined + +onBeforeUnmount(() => { + billingPageActive = false + stopCancellationWait?.() +}) const subscriptionInvoiceDialog = ref(false) const payments = ref(null) const selectedPayment = ref(null) @@ -228,7 +235,9 @@ async function cancelPlan() { loading.value = true try { await billingStore.cancelSubscription() + if (!billingPageActive) return } catch (error: unknown) { + if (!billingPageActive) return notificationsStore.addNotification({ message: getApiErrorMessage( error, @@ -246,8 +255,9 @@ async function cancelPlan() { try { await Promise.race([ (async () => { - while (Date.now() < deadline) { + while (billingPageActive && Date.now() < deadline) { await authStore.loadUser() + if (!billingPageActive) return if ( authStore.user?.subscription_status === 'cancelled' || authStore.user?.subscription_name === 'free' @@ -263,9 +273,11 @@ async function cancelPlan() { } })(), new Promise((resolve) => { + stopCancellationWait = resolve timeout = setTimeout(resolve, 10000) }), ]) + if (!billingPageActive) return if (cancellationPending.value) { notificationsStore.addNotification({ message: @@ -279,12 +291,14 @@ async function cancelPlan() { }) } } catch (error: unknown) { + if (!billingPageActive) return notificationsStore.addNotification({ message: `Your subscription was cancelled, but we could not refresh your billing details. ${getApiErrorMessage(error, 'Please try again later.')}`, type: 'error', }) } finally { clearTimeout(timeout) + stopCancellationWait = undefined dialog.value = false loading.value = false } @@ -350,7 +364,12 @@ onMounted(async () => { Date: Tue, 24 Nov 2026 22:04:00 +0200 Subject: [PATCH 06/13] fix(web): abort expired cancellation refresh requests Abort billing refreshes on timeout and unmount, and guard stale account writes. Add mounted billing-card and dialog regression coverage using Vue's renderer. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.component.test.ts | 249 ++++++++++++++++++ web/app/pages/billing/index.test.ts | 14 +- web/app/pages/billing/index.vue | 12 +- web/app/stores/auth.test.ts | 46 +++- web/app/stores/auth.ts | 16 +- 5 files changed, 328 insertions(+), 9 deletions(-) create mode 100644 web/app/pages/billing/index.component.test.ts diff --git a/web/app/pages/billing/index.component.test.ts b/web/app/pages/billing/index.component.test.ts new file mode 100644 index 000000000..b621df2b0 --- /dev/null +++ b/web/app/pages/billing/index.component.test.ts @@ -0,0 +1,249 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' +import { setImmediate } from 'node:timers/promises' +import { runInNewContext } from 'node:vm' +import ts from 'typescript' +import * as vue from 'vue' +import type { Component } from 'vue' +import { compileScript, parse } from 'vue/compiler-sfc' +import * as icons from '@mdi/js' +import * as countries from '../../utils/countries' +import * as apiError from '../../utils/api-error' +import * as blackFriday from '../../utils/black-friday' + +const { descriptor } = parse( + readFileSync(new URL('./index.vue', import.meta.url), 'utf8'), +) +const compiled = compileScript(descriptor, { + id: 'billing-component-test', + inlineTemplate: true, +}) +const { outputText } = ts.transpileModule(compiled.content, { + compilerOptions: { + target: ts.ScriptTarget.ESNext, + module: ts.ModuleKind.CommonJS, + }, +}) + +interface RenderNode { + type: string + text: string + props: Record + children: RenderNode[] + parent: RenderNode | null +} + +function node(type: string, text = ''): RenderNode { + return { type, text, props: {}, children: [], parent: null } +} + +function remove(child: RenderNode) { + if (!child.parent) return + child.parent.children.splice(child.parent.children.indexOf(child), 1) + child.parent = null +} + +const renderer = vue.createRenderer({ + createElement: (type) => node(type), + createText: (text) => node('#text', text), + createComment: (text) => node('#comment', text), + setText: (element, text) => { + element.text = text + }, + setElementText: (element, text) => { + element.text = text + element.children = [] + }, + patchProp: (element, key, _previous, value) => { + element.props[key] = value + }, + insert: (child, parent, anchor) => { + remove(child) + const index = anchor ? parent.children.indexOf(anchor) : -1 + parent.children.splice(index < 0 ? parent.children.length : index, 0, child) + child.parent = parent + }, + remove, + parentNode: (element) => element.parent, + nextSibling: (element) => { + const siblings = element.parent?.children ?? [] + return siblings[siblings.indexOf(element) + 1] ?? null + }, +}) + +function text(element: RenderNode): string { + return element.text + element.children.map(text).join('') +} + +function find( + element: RenderNode, + predicate: (element: RenderNode) => boolean, +): RenderNode[] { + return [ + ...(predicate(element) ? [element] : []), + ...element.children.flatMap((child) => find(child, predicate)), + ] +} + +function mountBilling() { + const notifications: { message: string; type: string }[] = [] + const authStore = vue.reactive({ + user: { + subscription_name: 'pro-monthly', + subscription_status: 'active', + subscription_renews_at: '2027-01-01T00:00:00Z', + subscription_ends_at: '2027-01-01T00:00:00Z', + }, + authUser: null, + loadUser: async () => {}, + }) + const billingStore = { + billingUsage: null, + billingUsageHistory: [], + loadBillingUsage: async () => {}, + loadBillingUsageHistory: async () => {}, + cancelSubscription: async () => {}, + } + const imports: Record = { + vue, + '@mdi/js': icons, + '~/utils/countries': countries, + '~/utils/api-error': apiError, + '~/utils/black-friday': blackFriday, + } + const component = runInNewContext(`${outputText}\nexports.default`, { + exports: {}, + require: (name: string) => { + assert.ok(name in imports, `Unexpected import: ${name}`) + return imports[name] + }, + ref: vue.ref, + computed: vue.computed, + onMounted: vue.onMounted, + onBeforeUnmount: vue.onBeforeUnmount, + definePageMeta: () => {}, + useHead: () => {}, + useRuntimeConfig: () => ({ + public: { + checkoutUrl: 'https://checkout.example.test', + enterpriseCheckoutUrl: 'https://checkout.example.test/enterprise', + }, + }), + useVDisplay: () => ({ lgAndUp: false }), + useAuthStore: () => authStore, + useBillingStore: () => billingStore, + useBlackFridayStore: () => ({ active: false, now: 0 }), + useNotificationsStore: () => ({ + addNotification: (notification: { message: string; type: string }) => + notifications.push(notification), + }), + useFilters: () => ({ + formatDecimal: String, + formatTimestamp: String, + }), + Date, + setTimeout, + clearTimeout, + AbortController, + URL, + }) as Component + const app = renderer.createApp(component) + const names = new Set( + [...descriptor.template!.content.matchAll(/<([A-Z]\w*)/g)].map( + (match) => match[1]!, + ), + ) + names.delete('VDialog') + names.add('v-code') + for (const name of names) { + app.component( + name, + vue.defineComponent({ + inheritAttrs: false, + setup: + (_props, { attrs, slots }) => + () => + vue.h(name, attrs, slots.default?.()), + }), + ) + } + app.component( + 'VDialog', + vue.defineComponent({ + props: { modelValue: Boolean, persistent: Boolean }, + emits: ['update:modelValue'], + setup: + (props, { slots, emit }) => + () => + vue.h('VDialog', { ...props }, [ + slots.activator?.({ + props: { onClick: () => emit('update:modelValue', true) }, + }), + props.modelValue ? slots.default?.() : null, + ]), + }), + ) + const root = node('root') + app.mount(root) + return { app, root, authStore, notifications } +} + +function buttons(root: RenderNode, label: string) { + return find( + root, + (element) => element.type === 'VBtn' && text(element).trim() === label, + ) +} + +async function click(button: RenderNode) { + const handler = button.props.onClick + assert.equal(typeof handler, 'function') + if (typeof handler === 'function') return handler() +} + +test('the mounted billing page keeps the dialog persistent, then renders pending and confirmed plan cards', async (context) => { + context.mock.timers.enable({ apis: ['Date', 'setTimeout'], now: 0 }) + const { app, root, authStore, notifications } = mountBilling() + try { + await setImmediate() + await click(buttons(root, 'Cancel Plan')[0]!) + await vue.nextTick() + const cancellation = click(buttons(root, 'Cancel Plan').at(-1)!) + await setImmediate() + + const dialog = find( + root, + (element) => + element.type === 'VDialog' && element.props.modelValue === true, + )[0]! + assert.equal(dialog.props.persistent, true) + assert.equal(buttons(root, 'Keep Subscription')[0]?.props.disabled, true) + assert.equal(notifications.length, 0) + + context.mock.timers.tick(10000) + await cancellation + await vue.nextTick() + + assert.match(text(root), /Subscription cancelled.*still updating/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + assert.equal(buttons(root, 'Update Plan').length, 0) + assert.equal(notifications.length, 1) + + authStore.user.subscription_status = 'cancelled' + await vue.nextTick() + assert.doesNotMatch(text(root), /still updating/) + assert.match(text(root), /You will be downgraded/) + assert.ok(buttons(root, 'Upgrade Plan').length > 0) + + authStore.user.subscription_name = 'free' + authStore.user.subscription_status = 'expired' + await vue.nextTick() + assert.doesNotMatch(text(root), /still updating|Your next bill/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + assert.ok(buttons(root, 'Upgrade Plan').length > 0) + } finally { + app.unmount() + context.mock.timers.reset() + } +}) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts index 2fbe0b4d0..0f81ad68c 100644 --- a/web/app/pages/billing/index.test.ts +++ b/web/app/pages/billing/index.test.ts @@ -43,6 +43,7 @@ function setupCancellation( let elapsed = 0 let deadlineCallback: (() => void) | undefined let unmount = () => {} + let refreshSignal: AbortSignal | undefined const waitingStates: { dialog: boolean; notifications: number }[] = [] const navigations: string[] = [] const notifications: { message: string; type: string }[] = [] @@ -51,7 +52,8 @@ function setupCancellation( const cancellationPending = { value: false } const authStore = { user: { subscription_status: 'active' }, - loadUser: async () => { + loadUser: async (signal?: AbortSignal) => { + refreshSignal = signal if (refreshError) throw refreshError authStore.user = { subscription_status: @@ -65,6 +67,8 @@ function setupCancellation( cancellationPending, billingPageActive: true, stopCancellationWait: undefined, + cancellationRefresh: undefined, + AbortController, onBeforeUnmount: (callback: () => void) => { unmount = callback }, @@ -108,6 +112,7 @@ function setupCancellation( navigations, reloads: () => reloads, refreshes: () => refreshes, + refreshSignal: () => refreshSignal, elapsed: () => elapsed, expireDeadline: () => { elapsed = 10000 @@ -205,7 +210,11 @@ test('a delayed webhook leaves a visible pending state after bounded polling', a test('the dialog closes at ten seconds even if the account refresh is still in flight', async () => { const pending = setupCancellation(async () => {}) - pending.authStore.loadUser = () => new Promise(() => {}) + let signal: AbortSignal | undefined + pending.authStore.loadUser = (refreshSignal) => { + signal = refreshSignal + return new Promise(() => {}) + } const cancellation = pending.cancel() await setImmediate() @@ -218,6 +227,7 @@ test('the dialog closes at ten seconds even if the account refresh is still in f assert.equal(pending.loading.value, false) assert.equal(pending.notifications.length, 1) assert.equal(pending.notifications[0]?.type, 'info') + assert.equal(signal?.aborted, true) }) test('leaving billing stops polling and prevents a notification on the next page', async () => { diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 3ff2e1de4..3b3c4eee2 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -42,9 +42,11 @@ const dialog = ref(false) const cancellationPending = ref(false) let billingPageActive = true let stopCancellationWait: (() => void) | undefined +let cancellationRefresh: AbortController | undefined onBeforeUnmount(() => { billingPageActive = false + cancellationRefresh?.abort() stopCancellationWait?.() }) const subscriptionInvoiceDialog = ref(false) @@ -250,14 +252,16 @@ async function cancelPlan() { } cancellationPending.value = true + cancellationRefresh = new AbortController() + const signal = cancellationRefresh.signal const deadline = Date.now() + 10000 let timeout: ReturnType | undefined try { await Promise.race([ (async () => { - while (billingPageActive && Date.now() < deadline) { - await authStore.loadUser() - if (!billingPageActive) return + while (billingPageActive && !signal.aborted && Date.now() < deadline) { + await authStore.loadUser(signal) + if (!billingPageActive || signal.aborted) return if ( authStore.user?.subscription_status === 'cancelled' || authStore.user?.subscription_name === 'free' @@ -298,6 +302,8 @@ async function cancelPlan() { }) } finally { clearTimeout(timeout) + cancellationRefresh.abort() + cancellationRefresh = undefined stopCancellationWait = undefined dialog.value = false loading.value = false diff --git a/web/app/stores/auth.test.ts b/web/app/stores/auth.test.ts index 0016b41bb..0e89483d5 100644 --- a/web/app/stores/auth.test.ts +++ b/web/app/stores/auth.test.ts @@ -7,7 +7,7 @@ import { useApi, setAuthHeader, setApiKey } from '../composables/useApi' import { useAuthStore } from './auth' interface UserResponse { - data: { id: string; api_key: string } + data: { id: string; api_key: string; subscription_status?: string } } function deferred() { @@ -87,6 +87,50 @@ test('loading a user sends its API key alongside bearer auth on shared requests' assert.equal(calls.at(-1)?.get('x-api-key'), 'new-key-a') }) +test('an older account refresh cannot overwrite newer subscription state or API keys', async () => { + const { store, calls, respondWith } = setupStore() + const stale = deferred() + respondWith(stale.promise) + const oldLoad = store.loadUser() + respondWith( + Promise.resolve({ + data: { + id: 'account-a', + api_key: 'new-key', + subscription_status: 'cancelled', + }, + }), + ) + await store.loadUser() + stale.resolve({ + data: { + id: 'account-a', + api_key: 'old-key', + subscription_status: 'active', + }, + }) + await oldLoad + await useApi().apiFetch('/v1/messages') + + assert.equal(store.user?.subscription_status, 'cancelled') + assert.equal(calls.at(-1)?.get('x-api-key'), 'new-key') +}) + +test('an aborted account refresh cannot publish its response even if the request completes', async () => { + const { store, calls, respondWith } = setupStore() + const controller = new AbortController() + const stale = deferred() + respondWith(stale.promise) + const oldLoad = store.loadUser(controller.signal) + controller.abort() + stale.resolve({ data: { id: 'account-a', api_key: 'old-key' } }) + await oldLoad + await useApi().apiFetch('/v1/messages') + + assert.equal(store.user, null) + assert.equal(calls.at(-1)?.has('x-api-key'), false) +}) + for (const logout of ['reset', 'auth callback', 'token callback'] as const) { test(`a pending user load cannot restore credentials after ${logout}`, async () => { const { store, calls, respondWith } = setupStore() diff --git a/web/app/stores/auth.ts b/web/app/stores/auth.ts index 9ae9ca7b7..bed1cb180 100644 --- a/web/app/stores/auth.ts +++ b/web/app/stores/auth.ts @@ -15,6 +15,7 @@ export const useAuthStore = defineStore('auth', () => { const user = ref(null) const { apiFetch } = useApi() let sessionVersion = 0 + let userLoadVersion = 0 function clearCredentials() { sessionVersion++ @@ -53,10 +54,19 @@ export const useAuthStore = defineStore('auth', () => { await onAuthStateChanged(firebaseUser) } - async function loadUser() { + async function loadUser(signal?: AbortSignal) { const session = sessionVersion - const response = await apiFetch<{ data: EntitiesUser }>('/v1/users/me') - if (session !== sessionVersion) return + const version = ++userLoadVersion + const response = await apiFetch<{ data: EntitiesUser }>('/v1/users/me', { + signal, + }) + if ( + signal?.aborted || + session !== sessionVersion || + version !== userLoadVersion + ) { + return + } setApiKey(response.data.api_key) user.value = response.data } From da264c44a0422a69a1fcf86f7b0112917f0b1a89 Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 22:10:51 +0200 Subject: [PATCH 07/13] fix(web): preserve successful overlapping account loads Only discard older responses when a newer account load has published data. Keep valid initialization results if a replacement refresh fails or aborts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/stores/auth.test.ts | 36 ++++++++++++++++++++++++++++++++++++ web/app/stores/auth.ts | 4 +++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/web/app/stores/auth.test.ts b/web/app/stores/auth.test.ts index 0e89483d5..4af449967 100644 --- a/web/app/stores/auth.test.ts +++ b/web/app/stores/auth.test.ts @@ -131,6 +131,42 @@ test('an aborted account refresh cannot publish its response even if the request assert.equal(calls.at(-1)?.has('x-api-key'), false) }) +for (const replacement of ['aborted', 'failed'] as const) { + test(`a successful account load still publishes when its newer replacement is ${replacement}`, async () => { + const { store, calls, respondWith } = setupStore() + const original = deferred() + respondWith(original.promise) + const originalLoad = store.loadUser() + + if (replacement === 'aborted') { + const controller = new AbortController() + const newer = deferred() + respondWith(newer.promise) + const newerLoad = store.loadUser(controller.signal) + controller.abort() + newer.resolve({ data: { id: 'account-a', api_key: 'aborted-key' } }) + await newerLoad + } else { + const error = new Error('Account fetch failed') + respondWith(Promise.reject(error)) + await assert.rejects( + () => store.loadUser(), + (caught) => caught === error, + ) + } + + original.resolve({ data: { id: 'account-a', api_key: 'original-key' } }) + await originalLoad + respondWith( + Promise.resolve({ data: { id: 'account-a', api_key: 'original-key' } }), + ) + await useApi().apiFetch('/v1/messages') + + assert.equal(store.user?.id, 'account-a') + assert.equal(calls.at(-1)?.get('x-api-key'), 'original-key') + }) +} + for (const logout of ['reset', 'auth callback', 'token callback'] as const) { test(`a pending user load cannot restore credentials after ${logout}`, async () => { const { store, calls, respondWith } = setupStore() diff --git a/web/app/stores/auth.ts b/web/app/stores/auth.ts index bed1cb180..60fe47a39 100644 --- a/web/app/stores/auth.ts +++ b/web/app/stores/auth.ts @@ -16,6 +16,7 @@ export const useAuthStore = defineStore('auth', () => { const { apiFetch } = useApi() let sessionVersion = 0 let userLoadVersion = 0 + let publishedUserLoadVersion = 0 function clearCredentials() { sessionVersion++ @@ -63,10 +64,11 @@ export const useAuthStore = defineStore('auth', () => { if ( signal?.aborted || session !== sessionVersion || - version !== userLoadVersion + version < publishedUserLoadVersion ) { return } + publishedUserLoadVersion = version setApiKey(response.data.api_key) user.value = response.data } From 9b094f3f8ba06c728b3b13d7b51f62786a6508fc Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 22:18:34 +0200 Subject: [PATCH 08/13] fix(web): scope cancellation locking and guard account mutations Lock the dialog only during cancellation, not unrelated billing loading. Invalidate older refresh results when user updates or API-key rotation finish. Add mounted-dialog and refresh-versus-mutation regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.component.test.ts | 25 +++++++++++++++++-- web/app/pages/billing/index.test.ts | 1 + web/app/pages/billing/index.vue | 8 ++++-- web/app/stores/auth.test.ts | 24 ++++++++++++++++++ web/app/stores/auth.ts | 2 ++ 5 files changed, 56 insertions(+), 4 deletions(-) diff --git a/web/app/pages/billing/index.component.test.ts b/web/app/pages/billing/index.component.test.ts index b621df2b0..4d5809eaf 100644 --- a/web/app/pages/billing/index.component.test.ts +++ b/web/app/pages/billing/index.component.test.ts @@ -86,7 +86,7 @@ function find( ] } -function mountBilling() { +function mountBilling(holdInitialLoad = false) { const notifications: { message: string; type: string }[] = [] const authStore = vue.reactive({ user: { @@ -101,7 +101,9 @@ function mountBilling() { const billingStore = { billingUsage: null, billingUsageHistory: [], - loadBillingUsage: async () => {}, + loadBillingUsage: async () => { + if (holdInitialLoad) await new Promise(() => {}) + }, loadBillingUsageHistory: async () => {}, cancelSubscription: async () => {}, } @@ -247,3 +249,22 @@ test('the mounted billing page keeps the dialog persistent, then renders pending context.mock.timers.reset() } }) + +test('unrelated billing loading does not lock the cancellation dialog', async () => { + const { app, root } = mountBilling(true) + try { + await setImmediate() + await click(buttons(root, 'Cancel Plan')[0]!) + await vue.nextTick() + + const dialog = find( + root, + (element) => + element.type === 'VDialog' && element.props.modelValue === true, + )[0]! + assert.equal(dialog.props.persistent, false) + assert.equal(buttons(root, 'Keep Subscription')[0]?.props.disabled, false) + } finally { + app.unmount() + } +}) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts index 0f81ad68c..6f934fa20 100644 --- a/web/app/pages/billing/index.test.ts +++ b/web/app/pages/billing/index.test.ts @@ -65,6 +65,7 @@ function setupCancellation( loading, dialog, cancellationPending, + cancellingSubscription: { value: false }, billingPageActive: true, stopCancellationWait: undefined, cancellationRefresh: undefined, diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 3b3c4eee2..2f517f397 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -40,6 +40,7 @@ const loading = ref(true) const loadingSubscriptionPayments = ref(false) const dialog = ref(false) const cancellationPending = ref(false) +const cancellingSubscription = ref(false) let billingPageActive = true let stopCancellationWait: (() => void) | undefined let cancellationRefresh: AbortController | undefined @@ -235,6 +236,7 @@ async function updateDetails() { async function cancelPlan() { loading.value = true + cancellingSubscription.value = true try { await billingStore.cancelSubscription() if (!billingPageActive) return @@ -248,6 +250,7 @@ async function cancelPlan() { type: 'error', }) loading.value = false + cancellingSubscription.value = false return } @@ -307,6 +310,7 @@ async function cancelPlan() { stopCancellationWait = undefined dialog.value = false loading.value = false + cancellingSubscription.value = false } } @@ -471,7 +475,7 @@ onMounted(async () => { !isOnLifetimePlan) " v-model="dialog" - :persistent="loading" + :persistent="cancellingSubscription" max-width="590" opacity="0.9" > @@ -503,7 +507,7 @@ onMounted(async () => { Keep Subscription diff --git a/web/app/stores/auth.test.ts b/web/app/stores/auth.test.ts index 4af449967..4fa070c4a 100644 --- a/web/app/stores/auth.test.ts +++ b/web/app/stores/auth.test.ts @@ -167,6 +167,30 @@ for (const replacement of ['aborted', 'failed'] as const) { }) } +for (const mutation of ['update', 'rotate'] as const) { + test(`an earlier account refresh cannot restore an old API key after ${mutation}`, async () => { + const { store, calls, respondWith } = setupStore() + const stale = deferred() + respondWith(stale.promise) + const refresh = store.loadUser() + respondWith( + Promise.resolve({ data: { id: 'account-a', api_key: 'new-key' } }), + ) + + if (mutation === 'update') { + await store.updateUser({ timezone: 'UTC' }) + } else { + await store.rotateApiKey('account-a') + } + stale.resolve({ data: { id: 'account-a', api_key: 'old-key' } }) + await refresh + await useApi().apiFetch('/v1/messages') + + assert.equal(store.user?.api_key, 'new-key') + assert.equal(calls.at(-1)?.get('x-api-key'), 'new-key') + }) +} + for (const logout of ['reset', 'auth callback', 'token callback'] as const) { test(`a pending user load cannot restore credentials after ${logout}`, async () => { const { store, calls, respondWith } = setupStore() diff --git a/web/app/stores/auth.ts b/web/app/stores/auth.ts index 60fe47a39..73e92f1c9 100644 --- a/web/app/stores/auth.ts +++ b/web/app/stores/auth.ts @@ -92,6 +92,7 @@ export const useAuthStore = defineStore('auth', () => { }) if (session !== sessionVersion) return + publishedUserLoadVersion = ++userLoadVersion setApiKey(response.data.api_key) user.value = response.data } @@ -112,6 +113,7 @@ export const useAuthStore = defineStore('auth', () => { }, ) if (session === sessionVersion) { + publishedUserLoadVersion = ++userLoadVersion user.value = response.data setApiKey(response.data.api_key) } From 6fb2769085cffb9e4f0197dc91bd8b65ec7eca28 Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 22:27:28 +0200 Subject: [PATCH 09/13] fix(web): retain fresh billing data across delayed mutations Track account-read freshness separately from mutation credential freshness. Preserve newer billing reads without restoring credentials from older requests. Cover both reply orderings for account updates and API-key rotation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/stores/auth.test.ts | 48 +++++++++++++++++++++++++++++++ web/app/stores/auth.ts | 56 ++++++++++++++++++++++++++----------- 2 files changed, 87 insertions(+), 17 deletions(-) diff --git a/web/app/stores/auth.test.ts b/web/app/stores/auth.test.ts index 4fa070c4a..15a9ea583 100644 --- a/web/app/stores/auth.test.ts +++ b/web/app/stores/auth.test.ts @@ -191,6 +191,54 @@ for (const mutation of ['update', 'rotate'] as const) { }) } +for (const mutation of ['update', 'rotate'] as const) { + for (const responseOrder of ['mutation first', 'refresh first'] as const) { + test(`a delayed ${mutation} preserves newer billing data with ${responseOrder}`, async () => { + const { store, calls, respondWith } = setupStore() + const mutationResponse = deferred() + respondWith(mutationResponse.promise) + const change = + mutation === 'update' + ? store.updateUser({ timezone: 'UTC' }) + : store.rotateApiKey('account-a') + const refreshResponse = deferred() + respondWith(refreshResponse.promise) + const refresh = store.loadUser() + const updated = { + data: { + id: 'account-a', + api_key: 'new-key', + subscription_status: 'active', + }, + } + const latest = { + data: { + id: 'account-a', + api_key: 'old-key', + subscription_status: 'cancelled', + }, + } + + if (responseOrder === 'mutation first') { + mutationResponse.resolve(updated) + await change + refreshResponse.resolve(latest) + await refresh + } else { + refreshResponse.resolve(latest) + await refresh + mutationResponse.resolve(updated) + await change + } + await useApi().apiFetch('/v1/messages') + + assert.equal(store.user?.subscription_status, 'cancelled') + assert.equal(store.user?.api_key, 'new-key') + assert.equal(calls.at(-1)?.get('x-api-key'), 'new-key') + }) + } +} + for (const logout of ['reset', 'auth callback', 'token callback'] as const) { test(`a pending user load cannot restore credentials after ${logout}`, async () => { const { store, calls, respondWith } = setupStore() diff --git a/web/app/stores/auth.ts b/web/app/stores/auth.ts index 73e92f1c9..a066dbc2a 100644 --- a/web/app/stores/auth.ts +++ b/web/app/stores/auth.ts @@ -15,8 +15,37 @@ export const useAuthStore = defineStore('auth', () => { const user = ref(null) const { apiFetch } = useApi() let sessionVersion = 0 - let userLoadVersion = 0 - let publishedUserLoadVersion = 0 + let userRequestVersion = 0 + let publishedUserVersion = 0 + let publishedMutationVersion = 0 + + function publishLoadedUser( + loadedUser: EntitiesUser, + version: number, + mutationVersion: number, + ) { + if (version < publishedUserVersion) return + publishedUserVersion = version + const nextUser = + mutationVersion !== publishedMutationVersion && user.value + ? { ...loadedUser, api_key: user.value.api_key } + : loadedUser + setApiKey(nextUser.api_key) + user.value = nextUser + } + + function publishMutatedUser(updatedUser: EntitiesUser, version: number) { + if (version < publishedMutationVersion) return + publishedMutationVersion = version + // Preserve later billing reads while applying the mutation's API key. + const nextUser = + version < publishedUserVersion && user.value + ? { ...user.value, api_key: updatedUser.api_key } + : updatedUser + publishedUserVersion = Math.max(publishedUserVersion, version) + setApiKey(nextUser.api_key) + user.value = nextUser + } function clearCredentials() { sessionVersion++ @@ -57,20 +86,15 @@ export const useAuthStore = defineStore('auth', () => { async function loadUser(signal?: AbortSignal) { const session = sessionVersion - const version = ++userLoadVersion + const version = ++userRequestVersion + const mutationVersion = publishedMutationVersion const response = await apiFetch<{ data: EntitiesUser }>('/v1/users/me', { signal, }) - if ( - signal?.aborted || - session !== sessionVersion || - version < publishedUserLoadVersion - ) { + if (signal?.aborted || session !== sessionVersion) { return } - publishedUserLoadVersion = version - setApiKey(response.data.api_key) - user.value = response.data + publishLoadedUser(response.data, version, mutationVersion) } async function updateUser(payload: { owner?: string; timezone?: string }) { @@ -83,6 +107,7 @@ export const useAuthStore = defineStore('auth', () => { const activePhone = phonesStore.activePhone if (!activePhone) return + const version = ++userRequestVersion const response = await apiFetch<{ data: EntitiesUser }>('/v1/users/me', { method: 'PUT', body: { @@ -92,9 +117,7 @@ export const useAuthStore = defineStore('auth', () => { }) if (session !== sessionVersion) return - publishedUserLoadVersion = ++userLoadVersion - setApiKey(response.data.api_key) - user.value = response.data + publishMutatedUser(response.data, version) } async function deleteUserAccount(): Promise { @@ -106,6 +129,7 @@ export const useAuthStore = defineStore('auth', () => { async function rotateApiKey(userId: string): Promise { const session = sessionVersion + const version = ++userRequestVersion const response = await apiFetch<{ data: EntitiesUser }>( `/v1/users/${userId}/api-keys`, { @@ -113,9 +137,7 @@ export const useAuthStore = defineStore('auth', () => { }, ) if (session === sessionVersion) { - publishedUserLoadVersion = ++userLoadVersion - user.value = response.data - setApiKey(response.data.api_key) + publishMutatedUser(response.data, version) } return response.data } From 4445761abebd2fb617825f201284264de2ebba6e Mon Sep 17 00:00:00 2001 From: Acho Arnold Ewin Date: Tue, 24 Nov 2026 22:38:44 +0200 Subject: [PATCH 10/13] fix(web): confine subscription cancellation refresh to billing Remove all shared auth-store coordination changes from this PR. Keep refreshed billing data local to the page without updating credentials. Cap the entire cancellation flow at ten seconds with one progress notification. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ed7b2928-caae-4667-8285-9b3c3f31bca4 --- web/app/pages/billing/index.component.test.ts | 45 ++++- web/app/pages/billing/index.test.ts | 77 +++++++-- web/app/pages/billing/index.vue | 70 ++++---- web/app/stores/auth.test.ts | 154 +----------------- web/app/stores/auth.ts | 54 +----- 5 files changed, 151 insertions(+), 249 deletions(-) diff --git a/web/app/pages/billing/index.component.test.ts b/web/app/pages/billing/index.component.test.ts index 4d5809eaf..07764db81 100644 --- a/web/app/pages/billing/index.component.test.ts +++ b/web/app/pages/billing/index.component.test.ts @@ -88,10 +88,12 @@ function find( function mountBilling(holdInitialLoad = false) { const notifications: { message: string; type: string }[] = [] + let responseStatus = 'active' const authStore = vue.reactive({ user: { subscription_name: 'pro-monthly', subscription_status: 'active', + api_key: 'original-key', subscription_renews_at: '2027-01-01T00:00:00Z', subscription_ends_at: '2027-01-01T00:00:00Z', }, @@ -135,6 +137,15 @@ function mountBilling(holdInitialLoad = false) { useVDisplay: () => ({ lgAndUp: false }), useAuthStore: () => authStore, useBillingStore: () => billingStore, + useApi: () => ({ + apiFetch: async () => ({ + data: { + ...authStore.user, + subscription_status: responseStatus, + api_key: 'response-key', + }, + }), + }), useBlackFridayStore: () => ({ active: false, now: 0 }), useNotificationsStore: () => ({ addNotification: (notification: { message: string; type: string }) => @@ -188,7 +199,15 @@ function mountBilling(holdInitialLoad = false) { ) const root = node('root') app.mount(root) - return { app, root, authStore, notifications } + return { + app, + root, + authStore, + notifications, + confirmCancellation: () => { + responseStatus = 'cancelled' + }, + } } function buttons(root: RenderNode, label: string) { @@ -227,7 +246,7 @@ test('the mounted billing page keeps the dialog persistent, then renders pending await cancellation await vue.nextTick() - assert.match(text(root), /Subscription cancelled.*still updating/) + assert.match(text(root), /Cancellation in progress.*still updating/) assert.equal(buttons(root, 'Cancel Plan').length, 0) assert.equal(buttons(root, 'Update Plan').length, 0) assert.equal(notifications.length, 1) @@ -268,3 +287,25 @@ test('unrelated billing loading does not lock the cancellation dialog', async () app.unmount() } }) + +test('confirmed cancellation updates the mounted billing card without modifying auth state', async () => { + const { app, root, authStore, notifications, confirmCancellation } = + mountBilling() + try { + await setImmediate() + await click(buttons(root, 'Cancel Plan')[0]!) + await vue.nextTick() + confirmCancellation() + await click(buttons(root, 'Cancel Plan').at(-1)!) + await vue.nextTick() + + assert.match(text(root), /You will be downgraded/) + assert.equal(buttons(root, 'Cancel Plan').length, 0) + assert.equal(authStore.user.subscription_status, 'active') + assert.equal(authStore.user.api_key, 'original-key') + assert.equal(notifications.length, 1) + assert.equal(notifications[0]?.type, 'success') + } finally { + app.unmount() + } +}) diff --git a/web/app/pages/billing/index.test.ts b/web/app/pages/billing/index.test.ts index 6f934fa20..795f7e68f 100644 --- a/web/app/pages/billing/index.test.ts +++ b/web/app/pages/billing/index.test.ts @@ -50,14 +50,22 @@ function setupCancellation( const loading = { value: false } const dialog = { value: true } const cancellationPending = { value: false } + const billingUser: { + value: { subscription_status: string; api_key: string } | null + } = { value: null } const authStore = { - user: { subscription_status: 'active' }, - loadUser: async (signal?: AbortSignal) => { - refreshSignal = signal + user: { subscription_status: 'active', api_key: 'original-key' }, + } + const api = { + apiFetch: async (_path: string, options: { signal?: AbortSignal }) => { + refreshSignal = options.signal if (refreshError) throw refreshError - authStore.user = { - subscription_status: - statuses[Math.min(refreshes++, statuses.length - 1)]!, + return { + data: { + subscription_status: + statuses[Math.min(refreshes++, statuses.length - 1)]!, + api_key: 'response-key', + }, } }, } @@ -74,6 +82,9 @@ function setupCancellation( unmount = callback }, authStore, + billingUser, + apiFetch: (path: string, options: { signal?: AbortSignal }) => + api.apiFetch(path, options), billingStore: { cancelSubscription }, notificationsStore: { addNotification: (notification: { message: string; type: string }) => { @@ -109,6 +120,8 @@ function setupCancellation( dialog, cancellationPending, authStore, + billingUser, + api, notifications, navigations, reloads: () => reloads, @@ -131,7 +144,9 @@ test('successful cancellation updates billing status in place without a browser assert.equal(pending.reloads(), 0) assert.deepEqual(pending.navigations, []) - assert.equal(pending.authStore.user.subscription_status, 'cancelled') + assert.equal(pending.billingUser.value?.subscription_status, 'cancelled') + assert.equal(pending.authStore.user.subscription_status, 'active') + assert.equal(pending.authStore.user.api_key, 'original-key') assert.equal(pending.dialog.value, false) assert.equal(pending.loading.value, false) assert.equal(pending.cancellationPending.value, false) @@ -151,7 +166,7 @@ test('failed cancellation stays on the page without refreshing and displays an e assert.equal(pending.notifications.at(-1)?.type, 'error') assert.equal(pending.loading.value, false) assert.equal(pending.authStore.user.subscription_status, 'active') - assert.equal(pending.dialog.value, true) + assert.equal(pending.dialog.value, false) }) test('a refresh failure after cancellation reports the refresh error rather than a cancellation failure', async () => { @@ -179,7 +194,7 @@ test('cancellation waits for the webhook when the first account response is stal await pending.cancel() - assert.equal(pending.authStore.user.subscription_status, 'cancelled') + assert.equal(pending.billingUser.value?.subscription_status, 'cancelled') assert.equal(pending.cancellationPending.value, false) assert.ok(pending.refreshes() > 1) assert.equal(pending.loading.value, false) @@ -198,7 +213,7 @@ test('a delayed webhook leaves a visible pending state after bounded polling', a assert.ok(pending.refreshes() > 1 && pending.refreshes() <= 20) assert.equal(pending.loading.value, false) assert.equal(pending.notifications.at(-1)?.type, 'info') - assert.match(pending.notifications.at(-1)!.message, /cancelled.*updating/) + assert.match(pending.notifications.at(-1)!.message, /cancellation.*progress/i) assert.equal(pending.elapsed(), 10000) assert.ok( pending.waitingStates.every( @@ -212,9 +227,9 @@ test('a delayed webhook leaves a visible pending state after bounded polling', a test('the dialog closes at ten seconds even if the account refresh is still in flight', async () => { const pending = setupCancellation(async () => {}) let signal: AbortSignal | undefined - pending.authStore.loadUser = (refreshSignal) => { - signal = refreshSignal - return new Promise(() => {}) + pending.api.apiFetch = (_path, options) => { + signal = options.signal + return new Promise(() => {}) } const cancellation = pending.cancel() await setImmediate() @@ -235,11 +250,15 @@ test('leaving billing stops polling and prevents a notification on the next page const pending = setupCancellation(async () => {}) let resolveRefresh!: () => void let refreshes = 0 - pending.authStore.loadUser = async () => { + pending.api.apiFetch = async () => { refreshes++ await new Promise((resolve) => { resolveRefresh = resolve }) + + return { + data: { subscription_status: 'cancelled', api_key: 'response-key' }, + } } const cancellation = pending.cancel() await setImmediate() @@ -252,4 +271,34 @@ test('leaving billing stops polling and prevents a notification on the next page assert.equal(pending.notifications.length, 0) assert.equal(refreshes, 1) + assert.equal(pending.billingUser.value, null) + assert.equal(pending.authStore.user.api_key, 'original-key') +}) + +test('the total deadline includes a cancellation request that is still in progress', async () => { + let resolveCancellation!: () => void + const pending = setupCancellation( + () => + new Promise((resolve) => { + resolveCancellation = resolve + }), + ) + const cancellation = pending.cancel() + await setImmediate() + + assert.equal(pending.dialog.value, true) + assert.equal(pending.loading.value, true) + assert.equal(pending.notifications.length, 0) + pending.expireDeadline() + await cancellation + + assert.equal(pending.dialog.value, false) + assert.equal(pending.loading.value, false) + assert.equal(pending.notifications.length, 1) + assert.match(pending.notifications[0]!.message, /cancellation.*progress/i) + resolveCancellation() + await setImmediate() + assert.equal(pending.billingUser.value, null) + assert.equal(pending.refreshes(), 0) + assert.equal(pending.notifications.length, 1) }) diff --git a/web/app/pages/billing/index.vue b/web/app/pages/billing/index.vue index 2f517f397..9c1e5e4b2 100644 --- a/web/app/pages/billing/index.vue +++ b/web/app/pages/billing/index.vue @@ -9,6 +9,7 @@ import { mdiInvoice, } from '@mdi/js' import type { + EntitiesUser, RequestsUserPaymentInvoice, ResponsesUserSubscriptionPaymentsResponse, } from '~~/shared/types/api' @@ -31,6 +32,9 @@ useHead({ const config = useRuntimeConfig() const { lgAndUp } = useVDisplay() const authStore = useAuthStore() +const { apiFetch } = useApi() +const billingUser = ref(null) +const billingAccount = computed(() => billingUser.value ?? authStore.user) const promotion = useBlackFridayStore() const billingStore = useBillingStore() const notificationsStore = useNotificationsStore() @@ -135,17 +139,17 @@ const plans: PaymentPlan[] = [ const plan = computed(() => { return (plans.find( - (x) => x.id === (authStore.user?.subscription_name || 'free'), + (x) => x.id === (billingAccount.value?.subscription_name || 'free'), ) ?? plans[0])! }) const isOnFreePlan = computed(() => plan.value.id === 'free') const blackFridayDiscountAvailable = computed( - () => authStore.user?.subscription_name === 'free' && promotion.active, + () => billingAccount.value?.subscription_name === 'free' && promotion.active, ) const isOnLifetimePlan = computed(() => plan.value.id === 'pro-lifetime') const subscriptionIsCancelled = computed( - () => authStore.user?.subscription_status === 'cancelled', + () => billingAccount.value?.subscription_status === 'cancelled', ) const invoiceStateOptions = computed(() => @@ -174,7 +178,7 @@ const checkoutURL = computed(() => { } return getBlackFridayCheckoutUrl( url, - authStore.user?.subscription_name, + billingAccount.value?.subscription_name, promotion.now, ) }) @@ -193,7 +197,7 @@ const enterpriseCheckoutURL = computed(() => { } return getBlackFridayCheckoutUrl( url, - authStore.user?.subscription_name, + billingAccount.value?.subscription_name, promotion.now, ) }) @@ -209,7 +213,7 @@ async function loadData() { } async function loadSubscriptionInvoices() { - if (!authStore.user?.subscription_id) return + if (!billingAccount.value?.subscription_id) return loadingSubscriptionPayments.value = true try { payments.value = await billingStore.indexSubscriptionPayments() @@ -237,38 +241,31 @@ async function updateDetails() { async function cancelPlan() { loading.value = true cancellingSubscription.value = true - try { - await billingStore.cancelSubscription() - if (!billingPageActive) return - } catch (error: unknown) { - if (!billingPageActive) return - notificationsStore.addNotification({ - message: getApiErrorMessage( - error, - 'We could not cancel your subscription.', - ), - type: 'error', - }) - loading.value = false - cancellingSubscription.value = false - return - } - cancellationPending.value = true cancellationRefresh = new AbortController() const signal = cancellationRefresh.signal const deadline = Date.now() + 10000 let timeout: ReturnType | undefined + let cancellationRequested = false try { await Promise.race([ (async () => { + await billingStore.cancelSubscription() + if (!billingPageActive || signal.aborted) return + cancellationRequested = true while (billingPageActive && !signal.aborted && Date.now() < deadline) { - await authStore.loadUser(signal) + const response = await apiFetch<{ data: EntitiesUser }>( + '/v1/users/me', + { + signal, + }, + ) if (!billingPageActive || signal.aborted) return if ( - authStore.user?.subscription_status === 'cancelled' || - authStore.user?.subscription_name === 'free' + response.data.subscription_status === 'cancelled' || + response.data.subscription_name === 'free' ) { + billingUser.value = response.data cancellationPending.value = false return } @@ -288,7 +285,7 @@ async function cancelPlan() { if (cancellationPending.value) { notificationsStore.addNotification({ message: - 'Your subscription was cancelled. Your billing details are still updating; please check back shortly.', + 'Cancellation is in progress. Please check your billing status shortly.', type: 'info', }) } else { @@ -299,8 +296,11 @@ async function cancelPlan() { } } catch (error: unknown) { if (!billingPageActive) return + if (!cancellationRequested) cancellationPending.value = false notificationsStore.addNotification({ - message: `Your subscription was cancelled, but we could not refresh your billing details. ${getApiErrorMessage(error, 'Please try again later.')}`, + message: cancellationRequested + ? `Your subscription was cancelled, but we could not refresh your billing details. ${getApiErrorMessage(error, 'Please try again later.')}` + : getApiErrorMessage(error, 'We could not cancel your subscription.'), type: 'error', }) } finally { @@ -371,7 +371,7 @@ onMounted(async () => {

Current Plan

- + - Subscription cancelled + Cancellation in progress

Your billing details are still updating. @@ -420,7 +420,7 @@ onMounted(async () => { Your next bill is for ${{ plan.price }} on {{ new Date( - authStore.user.subscription_renews_at!, + billingAccount.subscription_renews_at!, ).toLocaleDateString() }}

@@ -435,7 +435,7 @@ onMounted(async () => { You will be downgraded to the FREE plan on {{ new Date( - authStore.user.subscription_ends_at!, + billingAccount.subscription_ends_at!, ).toLocaleDateString() }}

@@ -498,7 +498,7 @@ onMounted(async () => { of the current billing period on {{ new Date( - authStore.user.subscription_renews_at!, + billingAccount.subscription_renews_at!, ).toLocaleDateString() }}

@@ -516,7 +516,7 @@ onMounted(async () => { @@ -638,7 +638,7 @@ onMounted(async () => { -