From 6ffb2ce775edcd5548bce27975528f4e024f37b3 Mon Sep 17 00:00:00 2001 From: "helpcode.ai" Date: Tue, 17 Nov 2026 20:50:37 +0100 Subject: [PATCH 1/2] Switch the workspace on at once after a payment from the reactivation page --- .../src/license/license-unclaimed.spec.ts | 74 +++++++++++ .../backend/src/license/license-unclaimed.ts | 8 ++ .../backend/src/license/license.service.ts | 116 ++++++++++++++---- .../license/reactivation.controller.spec.ts | 48 ++++++++ .../src/license/reactivation.controller.ts | 32 ++++- .../src/app/reactivate/[token]/copy.ts | 37 +++--- .../src/app/reactivate/[token]/page.tsx | 112 +++++++++++------ packages/frontend/src/lib/api.ts | 9 ++ .../tests/e2e/reactivate-link.spec.ts | 93 +++++++++++++- 9 files changed, 447 insertions(+), 82 deletions(-) diff --git a/packages/backend/src/license/license-unclaimed.spec.ts b/packages/backend/src/license/license-unclaimed.spec.ts index 857bdba2b..51b4374c0 100644 --- a/packages/backend/src/license/license-unclaimed.spec.ts +++ b/packages/backend/src/license/license-unclaimed.spec.ts @@ -341,4 +341,78 @@ describe('LicenseService — paid licences that never reached their workspace', expect(post).not.toHaveBeenCalled(); expect(setKey).not.toHaveBeenCalled(); }); + describe('claimPaidLicenceFor: the purchase a workspace just made', () => { + it("asks the licence site for that workspace only and binds its fresh licence", async () => { + const { svc, setKey } = make({ orgs: ['org-b'] }); + // Sold 10 seconds ago: the sweep would leave it for two minutes. + const post = siteLists([ + { key: KEY_B, email: 'bob@example.org', plan: 'starter', organizationId: 'org-b', createdAt: new Date(NOW.getTime() - 10_000).toISOString() }, + ]); + + await expect(svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(true); + + expect(post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/license\/unclaimed$/), + { organizationId: 'org-b' }, + expect.objectContaining({ headers: { 'x-amcp-service-token': 'svc-token-0123456789abcdef' } }), + ); + expect(setKey).toHaveBeenCalledWith(KEY_B, 'org-b'); + }); + + it('binds nothing from the general list of an older licence site', async () => { + const { svc, setKey } = make({ + orgs: ['org-b', 'org-c'], + users: [{ email: 'ann@example.com', role: 'ADMIN', organizationId: 'org-b', emailVerified: true }], + }); + siteLists([ + { key: KEY_A, email: 'ann@example.com', plan: 'starter' }, + { key: KEY_B, email: 'carl@example.org', plan: 'team', organizationId: 'org-c' }, + ]); + + await expect(svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false); + expect(setKey).not.toHaveBeenCalled(); + }); + + it('leaves a workspace that already pays alone', async () => { + const { svc, setKey } = make({ + orgs: ['org-b'], + locals: [{ licenseKey: 'AMCP-0000-1111-2222-3333', organizationId: 'org-b', plan: 'starter', status: 'active', expiresAt: null }], + }); + siteLists([{ key: KEY_B, email: 'bob@example.org', plan: 'starter', organizationId: 'org-b' }]); + + await expect(svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false); + expect(setKey).not.toHaveBeenCalled(); + }); + + it('asks the site once per workspace in five seconds, whatever the page does', async () => { + const { svc } = make({ orgs: ['org-b', 'org-c'] }); + const post = siteLists([]); + + await svc.claimPaidLicenceFor('org-b', NOW); + await svc.claimPaidLicenceFor('org-b', new Date(NOW.getTime() + 4_000)); + expect(post).toHaveBeenCalledTimes(1); + await svc.claimPaidLicenceFor('org-c', new Date(NOW.getTime() + 4_000)); + expect(post).toHaveBeenCalledTimes(2); + await svc.claimPaidLicenceFor('org-b', new Date(NOW.getTime() + 5_000)); + expect(post).toHaveBeenCalledTimes(3); + }); + + it('does nothing off Cloud, without the service token, or when the site fails', async () => { + const selfHosted = make({ orgs: ['org-b'], isCloud: false }); + const post = siteLists([{ key: KEY_B, email: 'bob@example.org', plan: 'starter', organizationId: 'org-b' }]); + await expect(selfHosted.svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false); + expect(post).not.toHaveBeenCalled(); + + delete process.env.LICENSE_SERVICE_TOKEN; + const noToken = make({ orgs: ['org-b'] }); + await expect(noToken.svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false); + expect(post).not.toHaveBeenCalled(); + + process.env.LICENSE_SERVICE_TOKEN = 'svc-token-0123456789abcdef'; + const down = make({ orgs: ['org-b'] }); + jest.spyOn(axios, 'post').mockRejectedValue(new Error('timeout')); + await expect(down.svc.claimPaidLicenceFor('org-b', NOW)).resolves.toBe(false); + expect(down.setKey).not.toHaveBeenCalled(); + }); + }); }); diff --git a/packages/backend/src/license/license-unclaimed.ts b/packages/backend/src/license/license-unclaimed.ts index 95f5c6247..a6dc47e70 100644 --- a/packages/backend/src/license/license-unclaimed.ts +++ b/packages/backend/src/license/license-unclaimed.ts @@ -33,6 +33,14 @@ export const UNCLAIMED_SWEEP_MS = 60 * 1000; */ export const UNCLAIMED_SETTLE_MS = 2 * 60 * 1000; +/** + * The shortest time between two requests to the licence site for one + * workspace's own purchase (LicenseService.claimPaidLicenceFor). The + * reactivation page asks every few seconds after a payment; the site sees + * one request per workspace in this time. + */ +export const WORKSPACE_CLAIM_MIN_INTERVAL_MS = 5 * 1000; + /** One entry of the licence site's answer. */ export interface UnclaimedLicence { key: string; diff --git a/packages/backend/src/license/license.service.ts b/packages/backend/src/license/license.service.ts index bb041e3a7..327ce1c3f 100644 --- a/packages/backend/src/license/license.service.ts +++ b/packages/backend/src/license/license.service.ts @@ -12,6 +12,7 @@ import { isSettled, parseUnclaimedLicences, UNCLAIMED_SWEEP_MS, + WORKSPACE_CLAIM_MIN_INTERVAL_MS, type UnclaimedLicence, type UnclaimedSkipReason, } from './license-unclaimed'; @@ -983,32 +984,12 @@ export class LicenseService implements OnModuleInit, OnModuleDestroy { // Too fresh: the buyer's browser may still be on its way back. if (!isSettled(licence, now)) continue; out.listed++; - const tail = licence.key.slice(-4); - try { - const target = await this.unclaimedLicenceTarget(licence, now); - if ('skip' in target) { - out.skipped++; - skipReasons.set(target.skip, (skipReasons.get(target.skip) ?? 0) + 1); - const log = `Unclaimed licence …${tail} (${maskEmail(licence.email)}) left unbound: ${target.skip}.`; - if (target.skip === 'already_paid' || target.skip === 'bound_elsewhere') warn(log); - else this.logger.debug(log); - continue; - } - if (target.retryActivation) { - if (!(await this.activateLicense(licence.key, target.organizationId))) { - out.failed++; - continue; - } - } else { - await this.setLicenseKey(licence.key, target.organizationId); - } - out.bound++; - this.logger.log( - `Bound paid licence …${tail} (${licence.plan}, ${maskEmail(licence.email)}) to workspace ${target.organizationId}.`, - ); - } catch (err: any) { - out.failed++; - this.logger.warn(`Could not bind unclaimed licence …${tail}: ${err?.message ?? err}`); + const result = await this.bindListedLicence(licence, now, warn); + if (result === 'bound') out.bound++; + else if (result === 'failed') out.failed++; + else { + out.skipped++; + skipReasons.set(result.skip, (skipReasons.get(result.skip) ?? 0) + 1); } await new Promise((resolve) => setTimeout(resolve, 250)); } @@ -1023,6 +1004,89 @@ export class LicenseService implements OnModuleInit, OnModuleDestroy { return out; } + /** Binds one listed licence to its workspace; says why when it is left alone. */ + private async bindListedLicence( + licence: UnclaimedLicence, + now: Date, + warn: (msg: string) => void, + ): Promise<'bound' | 'failed' | { skip: UnclaimedSkipReason }> { + const tail = licence.key.slice(-4); + try { + const target = await this.unclaimedLicenceTarget(licence, now); + if ('skip' in target) { + const log = `Unclaimed licence …${tail} (${maskEmail(licence.email)}) left unbound: ${target.skip}.`; + if (target.skip === 'already_paid' || target.skip === 'bound_elsewhere') warn(log); + else this.logger.debug(log); + return { skip: target.skip }; + } + if (target.retryActivation) { + if (!(await this.activateLicense(licence.key, target.organizationId))) return 'failed'; + } else { + await this.setLicenseKey(licence.key, target.organizationId); + } + this.logger.log( + `Bound paid licence …${tail} (${licence.plan}, ${maskEmail(licence.email)}) to workspace ${target.organizationId}.`, + ); + return 'bound'; + } catch (err: any) { + this.logger.warn(`Could not bind unclaimed licence …${tail}: ${err?.message ?? err}`); + return 'failed'; + } + } + + /** When each workspace last asked the licence site for its own purchase. */ + private readonly workspaceClaims = new Map(); + + /** + * Binds the paid licence a workspace just bought, without the two-minute + * wait of the sweep (bindUnclaimedPaidLicences). + * + * That wait gives the buyer's browser time to come back signed in and bind + * the licence itself. A checkout opened from the no-login reactivation page + * never does: its buyer comes back to that page, which calls this. Until + * 17 Nov 2026 they waited for the sweep, a median of 145 seconds and never + * under two minutes, while a purchase from the app's wall was active in 6: + * a buyer who went straight back to the chat was refused again. + * + * The licence site is asked for this workspace's unactivated licences only, + * and only those that name it are bound: an older site, which ignores the + * workspace and answers with its settled list, changes nothing here. One + * request per workspace every WORKSPACE_CLAIM_MIN_INTERVAL_MS, whatever the + * page does. + */ + async claimPaidLicenceFor(organizationId: string, now: Date = new Date()): Promise { + if (!this.deployment.isCloud()) return false; + const headers = this.serviceHeaders(); + if (!headers['x-amcp-service-token']) return false; + + const last = this.workspaceClaims.get(organizationId); + if (last !== undefined && now.getTime() - last < WORKSPACE_CLAIM_MIN_INTERVAL_MS) return false; + for (const [org, at] of this.workspaceClaims) { + if (now.getTime() - at >= WORKSPACE_CLAIM_MIN_INTERVAL_MS) this.workspaceClaims.delete(org); + } + this.workspaceClaims.set(organizationId, now.getTime()); + + let licences: UnclaimedLicence[] | null; + try { + const { data } = await axios.post( + `${this.apiBase}/api/license/unclaimed`, + { organizationId }, + { timeout: 10000, headers }, + ); + licences = parseUnclaimedLicences(data); + } catch (err: any) { + this.logger.debug(`Licence claim for workspace ${organizationId} failed: ${err?.message ?? err}`); + return false; + } + let bound = false; + for (const licence of licences ?? []) { + if (licence.organizationId !== organizationId) continue; + const result = await this.bindListedLicence(licence, now, (msg) => this.logger.warn(msg)); + if (result === 'bound') bound = true; + } + return bound; + } + /** Where an unclaimed licence goes, or why it stays where it is. */ private async unclaimedLicenceTarget( licence: UnclaimedLicence, diff --git a/packages/backend/src/license/reactivation.controller.spec.ts b/packages/backend/src/license/reactivation.controller.spec.ts index edf48413f..1fb671891 100644 --- a/packages/backend/src/license/reactivation.controller.spec.ts +++ b/packages/backend/src/license/reactivation.controller.spec.ts @@ -34,6 +34,8 @@ interface MakeOpts { tokenMember?: any; firstAdmin?: any; checkout?: () => Promise; + /** What LicenseService.claimPaidLicenceFor does for the workspace. */ + claim?: (organizationId: string) => Promise; /** Adapter slugs of the workspace's connectors (null: a hand-made one). */ connectors?: Array; /** What the licence site answers for a win-back code. */ @@ -72,6 +74,7 @@ function make(opts: MakeOpts = {}) { createCheckoutIntent: jest.fn, [any]>( opts.checkout ?? (async () => ({ url: 'https://checkout.stripe.test/s1', trial: false })), ), + claimPaidLicenceFor: jest.fn, [string]>(opts.claim ?? (async () => false)), }; const licenseGuard = { getUsage: jest.fn().mockResolvedValue({ @@ -419,6 +422,51 @@ describe('ReactivationController', () => { }); }); + describe('POST /api/license/reactivate/:token/claim', () => { + it('binds the licence the workspace just bought and answers active', async () => { + const t = make({ lastInactive: license('trial', { status: 'expired', expiresAt: ended }) }); + t.licenseService.claimPaidLicenceFor.mockImplementation(async () => { + // The binding makes the paid licence the workspace's current one. + t.licenseService.getCurrentLicense.mockResolvedValue(license('starter')); + return true; + }); + await expect(t.controller.claim(token())).resolves.toEqual({ state: 'active' }); + expect(t.licenseService.claimPaidLicenceFor).toHaveBeenCalledWith('org-1'); + }); + + it('answers the unchanged state while the payment has not reached the licence site', async () => { + const t = make({ lastInactive: license('trial', { status: 'expired', expiresAt: ended }) }); + await expect(t.controller.claim(token())).resolves.toEqual({ state: 'trial-ended' }); + expect(t.licenseService.claimPaidLicenceFor).toHaveBeenCalledTimes(1); + }); + + it('asks nothing for a workspace that is already active', async () => { + const t = make({ current: license('starter') }); + await expect(t.controller.claim(token())).resolves.toEqual({ state: 'active' }); + expect(t.licenseService.claimPaidLicenceFor).not.toHaveBeenCalled(); + }); + + it('keeps answering when the claim itself fails', async () => { + const t = make({ + lastInactive: license('trial', { status: 'expired', expiresAt: ended }), + claim: async () => { + throw new Error('site down'); + }, + }); + await expect(t.controller.claim(token())).resolves.toEqual({ state: 'trial-ended' }); + }); + + it('answers 404 for an invalid token, a deleted workspace and on self-hosted', async () => { + const bad = make(); + await expect(bad.controller.claim('x'.repeat(40))).rejects.toThrow(NotFoundException); + const gone = make({ org: null }); + await expect(gone.controller.claim(token())).rejects.toThrow(NotFoundException); + const selfHosted = make({ cloud: false }); + await expect(selfHosted.controller.claim(token())).rejects.toThrow(NotFoundException); + for (const t of [bad, gone, selfHosted]) expect(t.licenseService.claimPaidLicenceFor).not.toHaveBeenCalled(); + }); + }); + describe('POST /api/license/reactivate/:token/event', () => { it("records a click as the page's paywall_action, for the token's workspace and user", async () => { const { controller, productEvents } = make(); diff --git a/packages/backend/src/license/reactivation.controller.ts b/packages/backend/src/license/reactivation.controller.ts index 47b46909a..9f85df123 100644 --- a/packages/backend/src/license/reactivation.controller.ts +++ b/packages/backend/src/license/reactivation.controller.ts @@ -119,9 +119,11 @@ const INVALID_LINK = 'This link is invalid or has expired.'; * Never an address, a user or workspace id, or a licence key. * - POST opens a pay-now Stripe Checkout for the workspace's administrator, * with the same refusals as POST /api/license/checkout-link. The paid - * licence names the workspace, so the unclaimed-licence sweep - * (license-unclaimed.ts) binds it within a few minutes even when nobody - * signs in afterwards. + * licence names the workspace. + * - POST claim is what the page calls when the buyer is back from Stripe: it + * binds that licence at once (LicenseService.claimPaidLicenceFor). When + * the buyer never comes back, the unclaimed-licence sweep + * (license-unclaimed.ts) binds it within a few minutes. * * No session: the token (reactivation-token.ts) names the workspace and is * the only credential, as with the trial extension link. @@ -273,6 +275,30 @@ export class ReactivationController { } } + @Post(':token/claim') + @HttpCode(200) + // The page asks every few seconds after a payment, for a few minutes. + @Throttle({ default: { limit: 40, ttl: 60_000 } }) + @ApiParam({ name: 'token', description: 'The reactivation link token' }) + @ApiOperation({ + summary: + 'Cloud, no sign-in: back from Stripe, switch the workspace on with the licence it just bought (404 for an invalid or expired link)', + }) + async claim(@Param('token') token: string): Promise<{ state: ReactivationState }> { + const { organizationId } = this.check(token); + const org = await this.prisma.organization.findUnique({ where: { id: organizationId }, select: { id: true } }); + if (!org) throw new NotFoundException(INVALID_LINK); + // Only a licence the site sold for this very workspace is bound, so the + // link gives its holder nothing but what was paid for. A workspace that + // is already active has nothing to claim. + let { state } = await this.stateOf(organizationId); + if (state !== 'active') { + const bound = await this.licenseService.claimPaidLicenceFor(organizationId).catch(() => false); + if (bound) ({ state } = await this.stateOf(organizationId)); + } + return { state }; + } + @Post(':token/event') @HttpCode(204) // A page load reports 'shown', a few clicks and at most one leave. diff --git a/packages/frontend/src/app/reactivate/[token]/copy.ts b/packages/frontend/src/app/reactivate/[token]/copy.ts index a690af99f..a24376038 100644 --- a/packages/frontend/src/app/reactivate/[token]/copy.ts +++ b/packages/frontend/src/app/reactivate/[token]/copy.ts @@ -43,6 +43,8 @@ export interface ReactivateCopy { opening: string; checkoutFailed: string; chips: { cancel: string; stripe: string; noSetup: string }; + /** The payment methods under the subscribe button: "Pay with" and the word for a card. */ + pay: { label: string; card: string }; stats: { workspaces: string; toolCalls: string }; badges: { claude: string; chatgpt: string; eu: string; gdpr: string; encrypted: string; openSource: string }; worksWith: string; @@ -108,6 +110,7 @@ const en: ReactivateCopy = { opening: 'Opening secure checkout…', checkoutFailed: 'The checkout could not be opened right now. Please try again in a moment.', chips: { cancel: 'Cancel any time', stripe: 'Payment by Stripe', noSetup: 'No new setup' }, + pay: { label: 'Pay with', card: 'Card' }, stats: { workspaces: 'workspaces on AnythingMCP Cloud', toolCalls: 'AI tool calls last month' }, badges: { claude: 'Listed in the Claude Directory', @@ -123,7 +126,7 @@ const en: ReactivateCopy = { payTitle: 'Pay securely with Stripe', payBody: 'Card, SEPA Direct Debit and other methods. We never see your card details.', activeTitle: 'Your workspace switches back on', - activeBody: 'Automatically, usually within two or three minutes. No sign-in, no licence key.', + activeBody: 'Automatically, usually within seconds. No sign-in, no licence key.', backTitle: 'Ask {client} again', backBody: 'Go back to your chat and repeat your request. Your connectors answer as before.', }, @@ -147,7 +150,7 @@ const en: ReactivateCopy = { activeBody: '{workspace} is active again. Go back to {client} and ask again: your connectors answer as before.', openDashboard: 'Open the dashboard', processingTitle: 'Confirming your payment…', - processingBody: 'This usually takes two or three minutes. Keep this page open, or go back to your chat in a moment.', + processingBody: 'This usually takes a few seconds. Keep this page open, or go back to your chat in a moment.', processingSlow: 'Your payment is still being confirmed. If the workspace is not active in a few minutes, sign in or write to support@anythingmcp.com.', paymentFailedTitle: "Your last payment didn't go through", @@ -186,6 +189,7 @@ const de: ReactivateCopy = { opening: 'Sicherer Checkout wird geöffnet…', checkoutFailed: 'Der Checkout konnte gerade nicht geöffnet werden. Bitte versuchen Sie es gleich noch einmal.', chips: { cancel: 'Jederzeit kündbar', stripe: 'Zahlung über Stripe', noSetup: 'Keine neue Einrichtung' }, + pay: { label: 'Zahlen mit', card: 'Karte' }, stats: { workspaces: 'Workspaces auf AnythingMCP Cloud', toolCalls: 'KI-Tool-Aufrufe im letzten Monat' }, badges: { claude: 'Gelistet im Claude Directory', @@ -201,7 +205,7 @@ const de: ReactivateCopy = { payTitle: 'Sicher mit Stripe bezahlen', payBody: 'Karte, SEPA-Lastschrift und weitere Methoden. Ihre Kartendaten sehen wir nie.', activeTitle: 'Ihr Workspace ist wieder aktiv', - activeBody: 'Automatisch, meist innerhalb von zwei bis drei Minuten. Ohne Anmeldung, ohne Lizenzschlüssel.', + activeBody: 'Automatisch, meist innerhalb weniger Sekunden. Ohne Anmeldung, ohne Lizenzschlüssel.', backTitle: 'Fragen Sie {client} erneut', backBody: 'Gehen Sie zurück in Ihren Chat und wiederholen Sie die Anfrage. Ihre Connectoren antworten wie zuvor.', }, @@ -225,7 +229,7 @@ const de: ReactivateCopy = { activeBody: '{workspace} ist wieder aktiv. Gehen Sie zurück zu {client} und fragen Sie erneut: Ihre Connectoren antworten wie zuvor.', openDashboard: 'Dashboard öffnen', processingTitle: 'Ihre Zahlung wird bestätigt…', - processingBody: 'Das dauert meist zwei bis drei Minuten. Lassen Sie diese Seite offen oder kehren Sie gleich zu Ihrem Chat zurück.', + processingBody: 'Das dauert meist nur wenige Sekunden. Lassen Sie diese Seite offen oder kehren Sie gleich zu Ihrem Chat zurück.', processingSlow: 'Ihre Zahlung wird noch bestätigt. Ist der Workspace in ein paar Minuten nicht aktiv, melden Sie sich an oder schreiben Sie an support@anythingmcp.com.', paymentFailedTitle: 'Ihre letzte Zahlung ist fehlgeschlagen', @@ -264,6 +268,7 @@ const it: ReactivateCopy = { opening: 'Apertura del checkout sicuro…', checkoutFailed: 'Non è stato possibile aprire il checkout. Riprova tra un momento.', chips: { cancel: 'Disdici quando vuoi', stripe: 'Pagamento con Stripe', noSetup: 'Nessuna nuova configurazione' }, + pay: { label: 'Paga con', card: 'Carta' }, stats: { workspaces: 'workspace su AnythingMCP Cloud', toolCalls: 'chiamate AI ai tool nell’ultimo mese' }, badges: { claude: 'Presente nella Claude Directory', @@ -279,7 +284,7 @@ const it: ReactivateCopy = { payTitle: 'Paghi in sicurezza con Stripe', payBody: 'Carta, addebito SEPA e altri metodi. Non vediamo mai i dati della tua carta.', activeTitle: 'Il workspace si riattiva', - activeBody: 'In automatico, di solito in due o tre minuti. Senza login, senza chiave di licenza.', + activeBody: 'In automatico, di solito in pochi secondi. Senza login, senza chiave di licenza.', backTitle: 'Chiedi di nuovo a {client}', backBody: 'Torna nella tua chat e ripeti la richiesta. I tuoi connettori rispondono come prima.', }, @@ -303,7 +308,7 @@ const it: ReactivateCopy = { activeBody: '{workspace} è di nuovo attivo. Torna su {client} e ripeti la richiesta: i tuoi connettori rispondono come prima.', openDashboard: 'Apri la dashboard', processingTitle: 'Stiamo confermando il pagamento…', - processingBody: 'Di solito ci vogliono due o tre minuti. Lascia aperta questa pagina, oppure torna alla tua chat tra un momento.', + processingBody: 'Di solito bastano pochi secondi. Lascia aperta questa pagina, oppure torna alla tua chat tra un momento.', processingSlow: 'Il pagamento è ancora in conferma. Se il workspace non è attivo tra qualche minuto, accedi o scrivi a support@anythingmcp.com.', paymentFailedTitle: "L'ultimo pagamento non è andato a buon fine", @@ -342,6 +347,7 @@ const es: ReactivateCopy = { opening: 'Abriendo el pago seguro…', checkoutFailed: 'No se pudo abrir el pago en este momento. Inténtalo de nuevo en un momento.', chips: { cancel: 'Cancela cuando quieras', stripe: 'Pago con Stripe', noSetup: 'Sin volver a configurar' }, + pay: { label: 'Paga con', card: 'Tarjeta' }, stats: { workspaces: 'workspaces en AnythingMCP Cloud', toolCalls: 'llamadas de IA a herramientas el último mes' }, badges: { claude: 'En el Claude Directory', @@ -357,7 +363,7 @@ const es: ReactivateCopy = { payTitle: 'Pagas de forma segura con Stripe', payBody: 'Tarjeta, adeudo directo SEPA y otros métodos. Nunca vemos los datos de tu tarjeta.', activeTitle: 'Tu workspace se reactiva', - activeBody: 'Automáticamente, normalmente en dos o tres minutos. Sin iniciar sesión, sin clave de licencia.', + activeBody: 'Automáticamente, normalmente en unos segundos. Sin iniciar sesión, sin clave de licencia.', backTitle: 'Vuelve a preguntar a {client}', backBody: 'Vuelve a tu chat y repite tu petición. Tus conectores responden como antes.', }, @@ -381,7 +387,7 @@ const es: ReactivateCopy = { activeBody: '{workspace} vuelve a estar activo. Vuelve a {client} y pregunta de nuevo: tus conectores responden como antes.', openDashboard: 'Abrir el panel', processingTitle: 'Confirmando tu pago…', - processingBody: 'Normalmente tarda dos o tres minutos. Deja esta página abierta o vuelve a tu chat en un momento.', + processingBody: 'Normalmente tarda unos segundos. Deja esta página abierta o vuelve a tu chat en un momento.', processingSlow: 'Tu pago aún se está confirmando. Si el workspace no está activo en unos minutos, inicia sesión o escribe a support@anythingmcp.com.', paymentFailedTitle: 'Tu último pago no se completó', @@ -419,6 +425,7 @@ const zh: ReactivateCopy = { opening: '正在打开安全结账…', checkoutFailed: '暂时无法打开结账页面,请稍后再试。', chips: { cancel: '随时取消', stripe: '由 Stripe 处理付款', noSetup: '无需重新配置' }, + pay: { label: '支付方式', card: '银行卡' }, stats: { workspaces: '个工作区在使用 AnythingMCP Cloud', toolCalls: '次 AI 工具调用(上个月)' }, badges: { claude: '已上架 Claude Directory', @@ -434,7 +441,7 @@ const zh: ReactivateCopy = { payTitle: '通过 Stripe 安全付款', payBody: '支持银行卡、SEPA 直接借记等方式。我们看不到你的卡信息。', activeTitle: '工作区自动恢复', - activeBody: '通常在两三分钟内自动完成。无需登录,无需许可证密钥。', + activeBody: '通常在几秒内自动完成。无需登录,无需许可证密钥。', backTitle: '再次询问 {client}', backBody: '回到你的对话,重复你的请求。你的连接器会像以前一样响应。', }, @@ -458,7 +465,7 @@ const zh: ReactivateCopy = { activeBody: '{workspace} 已重新激活。回到 {client} 再问一次:你的连接器会像以前一样响应。', openDashboard: '打开控制台', processingTitle: '正在确认你的付款…', - processingBody: '通常需要两三分钟。你可以保持此页面打开,或稍后回到你的对话。', + processingBody: '通常只需几秒钟。你可以保持此页面打开,或稍后回到你的对话。', processingSlow: '你的付款仍在确认中。如果几分钟后工作区仍未激活,请登录或写信至 support@anythingmcp.com。', paymentFailedTitle: '你的上一笔付款未成功', paymentFailedBody: '请登录并更新付款方式:付款成功后订阅会立即恢复。', @@ -496,6 +503,7 @@ const ja: ReactivateCopy = { opening: '安全な決済ページを開いています…', checkoutFailed: '現在、決済ページを開けませんでした。しばらくしてからもう一度お試しください。', chips: { cancel: 'いつでも解約可能', stripe: 'Stripe で決済', noSetup: '再設定不要' }, + pay: { label: 'お支払い方法', card: 'カード' }, stats: { workspaces: 'AnythingMCP Cloud のワークスペース', toolCalls: '先月の AI ツール呼び出し' }, badges: { claude: 'Claude Directory に掲載', @@ -511,7 +519,7 @@ const ja: ReactivateCopy = { payTitle: 'Stripe で安全にお支払い', payBody: 'カード、SEPA 口座引き落としなどに対応。カード情報が当社に渡ることはありません。', activeTitle: 'ワークスペースが再び有効に', - activeBody: '通常 2〜3 分以内に自動で有効になります。ログインもライセンスキーも不要です。', + activeBody: '通常は数秒で自動的に有効になります。ログインもライセンスキーも不要です。', backTitle: 'もう一度 {client} に依頼', backBody: 'チャットに戻って同じ依頼を繰り返してください。コネクタは以前と同じように応答します。', }, @@ -535,7 +543,7 @@ const ja: ReactivateCopy = { activeBody: '{workspace} は再び有効になりました。{client} に戻ってもう一度依頼してください。コネクタは以前と同じように応答します。', openDashboard: 'ダッシュボードを開く', processingTitle: 'お支払いを確認しています…', - processingBody: '通常 2〜3 分ほどかかります。このページを開いたままにするか、少ししてからチャットに戻ってください。', + processingBody: '通常は数秒で完了します。このページを開いたままにするか、少ししてからチャットに戻ってください。', processingSlow: 'お支払いはまだ確認中です。数分経ってもワークスペースが有効にならない場合は、ログインするか support@anythingmcp.com までご連絡ください。', paymentFailedTitle: '前回のお支払いが完了しませんでした', @@ -574,6 +582,7 @@ const ru: ReactivateCopy = { opening: 'Открываем безопасную оплату…', checkoutFailed: 'Не удалось открыть страницу оплаты. Попробуйте ещё раз через минуту.', chips: { cancel: 'Отмена в любой момент', stripe: 'Оплата через Stripe', noSetup: 'Без повторной настройки' }, + pay: { label: 'Способы оплаты', card: 'Карта' }, stats: { workspaces: 'workspace в AnythingMCP Cloud', toolCalls: 'вызовов инструментов ИИ за прошлый месяц' }, badges: { claude: 'В каталоге Claude Directory', @@ -589,7 +598,7 @@ const ru: ReactivateCopy = { payTitle: 'Безопасная оплата через Stripe', payBody: 'Карта, прямое списание SEPA и другие способы. Мы никогда не видим данные вашей карты.', activeTitle: 'Workspace снова включится', - activeBody: 'Автоматически, обычно в течение двух-трёх минут. Без входа и без лицензионного ключа.', + activeBody: 'Автоматически, обычно за несколько секунд. Без входа и без лицензионного ключа.', backTitle: 'Спросите {client} ещё раз', backBody: 'Вернитесь в чат и повторите запрос. Коннекторы ответят, как раньше.', }, @@ -613,7 +622,7 @@ const ru: ReactivateCopy = { activeBody: '{workspace} снова активен. Вернитесь в {client} и повторите запрос: коннекторы ответят, как раньше.', openDashboard: 'Открыть панель управления', processingTitle: 'Подтверждаем оплату…', - processingBody: 'Обычно это занимает две-три минуты. Оставьте страницу открытой или вернитесь в чат чуть позже.', + processingBody: 'Обычно это занимает несколько секунд. Оставьте страницу открытой или вернитесь в чат чуть позже.', processingSlow: 'Оплата ещё подтверждается. Если через несколько минут workspace не станет активным, войдите или напишите на support@anythingmcp.com.', paymentFailedTitle: 'Последний платёж не прошёл', diff --git a/packages/frontend/src/app/reactivate/[token]/page.tsx b/packages/frontend/src/app/reactivate/[token]/page.tsx index 3219de016..b66751dc8 100644 --- a/packages/frontend/src/app/reactivate/[token]/page.tsx +++ b/packages/frontend/src/app/reactivate/[token]/page.tsx @@ -38,8 +38,15 @@ import { } from './copy'; /** How often the page asks whether the payment reached the workspace, and for how long. */ -const PAID_POLL_MS = 4000; -const PAID_POLL_LIMIT = 90; +const PAID_POLL_MS = 3000; +const PAID_POLL_LIMIT = 120; + +/** + * What Stripe Checkout offers our buyers, by how often they pay with it + * (succeeded charges, Nov 2026: Link and cards first, then Apple Pay and + * PayPal). Brand names, so not translated; "card" is, in copy.ts. + */ +const PAY_METHODS = ['Apple Pay', 'Google Pay', 'PayPal', 'SEPA']; /** Logos of the AI clients the page can name (public/logos/clients). */ const CLIENT_LOGOS: Record = { @@ -61,7 +68,8 @@ const WORKS_WITH = [ * workspace's trial ended (A/B against the pricing page). No sign-in: the * token names the workspace, and the checkout it opens is for that workspace * alone, so the paid licence reaches it without anyone activating a key. - * Back from Stripe (`?paid=1`) it waits until the workspace is active. The + * Back from Stripe (`?paid=1`) it asks the backend to bind that licence and + * waits until the workspace is active, usually a few seconds. The * words follow the visitor's language among the website's seven (copy.ts). */ export default function ReactivatePage() { @@ -122,17 +130,26 @@ function ReactivateContent() { }; }, [token]); - // Back from Stripe: the paid licence reaches the workspace in 2-3 minutes - // (the backend binds a licence once it is two minutes old, sweeping every minute). + // Back from Stripe: ask the backend to bind the licence just bought, then + // read the state again. The payment reaches the licence site within + // seconds, so the first ask goes out at once. Without the ask the licence + // waited for the backend's sweep: two to three minutes in which a buyer who + // went back to the chat was refused again. A failed ask changes nothing: + // the sweep still binds the licence. useEffect(() => { if (!backFromStripe || !view || view.state === 'active' || pollsLeft <= 0) return; - const timer = setTimeout(() => { - reactivation - .get(token) - .then(setView) - .catch(() => {}) - .finally(() => setPollsLeft((n) => n - 1)); - }, PAID_POLL_MS); + const timer = setTimeout( + () => { + reactivation + .claim(token) + .catch(() => null) + .then(() => reactivation.get(token)) + .then(setView) + .catch(() => {}) + .finally(() => setPollsLeft((n) => n - 1)); + }, + pollsLeft === PAID_POLL_LIMIT ? 0 : PAID_POLL_MS, + ); return () => clearTimeout(timer); }, [backFromStripe, view, pollsLeft, token]); @@ -193,10 +210,16 @@ function ReactivateContent() { {c.nav.secureCheckout} + {/* Signed out, the sign-in is a quiet link: as a button it drew one + desktop visitor in ten away from the plans (Nov 2026). */} track(session ? 'open_workspace_clicked' : 'sign_in_clicked')} - className={cn(buttonVariants({ variant: 'secondary', size: 'sm' }), 'whitespace-nowrap')} + className={ + session + ? cn(buttonVariants({ variant: 'secondary', size: 'sm' }), 'whitespace-nowrap') + : 'whitespace-nowrap text-xs text-[var(--text-2)] underline-offset-2 hover:text-[var(--text)] hover:underline' + } > {session ? c.nav.openWorkspace : c.nav.signIn} @@ -295,7 +318,21 @@ function ReactivateContent() { {checkoutError}

)} -
    +

    + {c.pay.label} + {[c.pay.card, ...PAY_METHODS].map((method) => ( + + {method} + + ))} +

    +
      {[c.chips.cancel, c.chips.stripe, c.chips.noSetup].map((item) => (
    • @@ -320,6 +357,32 @@ function ReactivateContent() { } /> + {/* Under the plans, where the eye goes after the button: beside + them it competed with it (desktop visitors clicked subscribe + less often than phone visitors). Last on a phone too. */} +
      +

      {c.next.title}

      +
        + {[ + { title: c.next.payTitle, body: c.next.payBody }, + { title: c.next.activeTitle, body: c.next.activeBody }, + { title: fmt(c.next.backTitle, { client: clientName }), body: c.next.backBody }, + ].map((step, i) => ( +
      1. + + {i + 1} + +
        +

        {step.title}

        +

        {step.body}

        +
        +
      2. + ))} +
      +