Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(billing): add cancellation UI and organization feedback (#3037)

Mandad04d8c27fdbc
diff --git a/apps/api/README.md b/apps/api/README.md
index 33d709a37..4ad9ac6ae 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -1755,3 +1755,17 @@ Dashboard owns its normalized telemetry display types, independently of the remo
The nullable physical `user.keyPair` column remains for older API instances and rollback; the current entity no longer maps it.
No user-key data migration runs in this release. `User.publicKeys` and historical audit action identifiers remain unchanged.
+
+## Organization cancellation feedback
+
+The Console uses `PUT /api/organizations/:organizationId/cancellation-feedback` after confirming cancellation through the existing billing API. The endpoint accepts `{ "reasons": ["other"], "intent": null, "note": "My project ended" }` and returns 204 only after updating the organization's nullable `cancellationFeedback` JSONB field.
+
+Reasons are stable IDs; intent is optional, and custom text is limited to 1,000 characters and requires `other`. Unknown fields and empty answers are rejected. The server supplies `submittedBy` and `submittedAt` and stores the last accepted write, replacing the previous object.
+
+JWT authentication, organization access and a current OWNER membership are required, including for administrator accounts. API keys cannot submit feedback. Ordinary entity queries omit the field (`select: false`), and OrganizationDto does not expose it.
+
+Feedback is not a cancellation receipt or subscription history. Writing it never changes a subscription, and a save failure must not reverse a completed cancellation. Authorized database operators can inspect the field using existing restricted database access.
+
+Deploy the additive pre-deploy migration and API before the updated Console. Billing requires no deployment for this feature. Reverting the schema migration drops saved feedback, so retain the column during an application rollback if data must be preserved.
+
+Run `make test:apps:api TEST_FILES=cancellation-feedback` with `CANCELLATION_TEST_DATABASE_URL` pointing at a disposable loopback PostgreSQL database. The integration suite creates an isolated schema and exercises real JWT verification, organization guards, validation and latest-value replacement. It verifies independent reads and persistence after restarting the API and its database connection.
diff --git a/apps/api/src/migrations/pre-deploy/1795449600000-add-cancellation-feedback-migration.ts b/apps/api/src/migrations/pre-deploy/1795449600000-add-cancellation-feedback-migration.ts
new file mode 100644
index 000000000..c01c3e7b2
--- /dev/null
+++ b/apps/api/src/migrations/pre-deploy/1795449600000-add-cancellation-feedback-migration.ts
@@ -0,0 +1,12 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { MigrationInterface, QueryRunner } from 'typeorm'
+
+export class AddCancellationFeedback1795449600000 implements MigrationInterface {
+ async up(runner: QueryRunner): Promise<void> {
+ await runner.query('ALTER TABLE organization ADD COLUMN "cancellationFeedback" jsonb NULL')
+ }
+
+ async down(runner: QueryRunner): Promise<void> {
+ await runner.query('ALTER TABLE organization DROP COLUMN "cancellationFeedback"')
+ }
+}
diff --git a/apps/api/src/organization/controllers/cancellation-feedback.controller.ts b/apps/api/src/organization/controllers/cancellation-feedback.controller.ts
new file mode 100644
index 000000000..db51dff44
--- /dev/null
+++ b/apps/api/src/organization/controllers/cancellation-feedback.controller.ts
@@ -0,0 +1,37 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { BadRequestException, Body, Controller, ForbiddenException, HttpCode, Put, UseGuards } from '@nestjs/common'
+import { AuthGuard } from '@nestjs/passport'
+import { ApiExcludeController } from '@nestjs/swagger'
+import { AuthContext } from '../../common/decorators/auth-context.decorator'
+import { AuthenticatedRateLimitGuard } from '../../common/guards/authenticated-rate-limit.guard'
+import { OrganizationAuthContext } from '../../common/interfaces/auth-context.interface'
+import { RequiredOrganizationMemberRole } from '../decorators/required-organization-member-role.decorator'
+import { cancellationFeedbackInput } from '../dto/cancellation-feedback'
+import { OrganizationMemberRole } from '../enums/organization-member-role.enum'
+import { OrganizationActionGuard } from '../guards/organization-action.guard'
+import { CancellationFeedbackService } from '../services/cancellation-feedback.service'
+import { OrganizationUserService } from '../services/organization-user.service'
+
+@ApiExcludeController()
+@Controller('organizations/:organizationId/cancellation-feedback')
+@UseGuards(AuthGuard('jwt'), AuthenticatedRateLimitGuard, OrganizationActionGuard)
+@RequiredOrganizationMemberRole(OrganizationMemberRole.OWNER)
+export class CancellationFeedbackController {
+ constructor(
+ private readonly feedback: CancellationFeedbackService,
+ private readonly memberships: OrganizationUserService,
+ ) {}
+
+ @Put()
+ @HttpCode(204)
+ async save(@AuthContext() actor: OrganizationAuthContext, @Body() body: unknown): Promise<void> {
+ if (!actor.userId || actor.apiKey) throw new ForbiddenException('Organization owner required')
+ const organizationId = actor.organization.id
+ // Recheck current ownership: the shared guard caches membership and exempts administrators.
+ const member = await this.memberships.findOne(organizationId, actor.userId)
+ if (member?.role !== OrganizationMemberRole.OWNER) throw new ForbiddenException('Organization owner required')
+ const input = cancellationFeedbackInput.safeParse(body)
+ if (!input.success) throw new BadRequestException('Expected valid cancellation reasons, intent and optional note')
+ await this.feedback.save(organizationId, actor.userId, input.data)
+ }
+}
diff --git a/apps/api/src/organization/controllers/cancellation-feedback.integration.spec.ts b/apps/api/src/organization/controllers/cancellation-feedback.integration.spec.ts
new file mode 100644
index 000000000..db8091cf0
--- /dev/null
+++ b/apps/api/src/organization/controllers/cancellation-feedback.integration.spec.ts
@@ -0,0 +1,241 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { randomUUID } from 'node:crypto'
+import { createServer, Server } from 'node:http'
+import { AddressInfo } from 'node:net'
+import { INestApplication } from '@nestjs/common'
+import { Test } from '@nestjs/testing'
+import { getRedisConnectionToken } from '@nestjs-modules/ioredis'
+import axios from 'axios'
+import { exportJWK, generateKeyPair, SignJWT } from 'jose'
+import { DataSource } from 'typeorm'
+import { JwtStrategy } from '../../auth/jwt.strategy'
+import { AuthenticatedRateLimitGuard } from '../../common/guards/authenticated-rate-limit.guard'
+import { AllExceptionsFilter } from '../../filters/all-exceptions.filter'
+import { SystemRole } from '../../user/enums/system-role.enum'
+import { OrganizationMemberRole } from '../enums/organization-member-role.enum'
+import { CancellationFeedbackService } from '../services/cancellation-feedback.service'
+import { OrganizationService } from '../services/organization.service'
+import { OrganizationUserService } from '../services/organization-user.service'
+import { CancellationFeedbackController } from './cancellation-feedback.controller'
+import { AddCancellationFeedback1795449600000 } from '../../migrations/pre-deploy/1795449600000-add-cancellation-feedback-migration'
+import { OrganizationDto } from '../dto/organization.dto'
+
+const ciDatabase = process.env.CI && process.env.DB_HOST === 'localhost' && process.env.DB_DATABASE === 'boxlite'
+const databaseUrl =
+ process.env.CANCELLATION_TEST_DATABASE_URL ??
+ (ciDatabase ? 'postgres://postgres:postgres@localhost:5432/boxlite' : undefined)
+const integration = databaseUrl ? describe : describe.skip
+integration('organization cancellation feedback (Postgres and authenticated HTTP)', () => {
+ const schema = `cancellation_${randomUUID().replaceAll('-', '')}`
+ const organizationId = randomUUID()
+ const otherOrganizationId = randomUUID()
+ const feedback = { reasons: ['other', 'pricing', 'other'], intent: 'one_off', note: ' Custom reason ' }
+ let db: DataSource
+ let app: INestApplication
+ let server: Server
+ let endpoint: string
+ let jwt: JwtStrategy
+ const roles = new Map<string, OrganizationMemberRole>()
+ const cache = new Map<string, string>()
+ const tokens: Record<string, string> = {}
+ const options = () => ({
+ type: 'postgres' as const,
+ url: databaseUrl,
+ entities: [],
+ extra: { options: `-c search_path=${schema}` },
+ })
+
+ beforeAll(async () => {
+ if (!['localhost', '127.0.0.1', '[::1]'].includes(new URL(databaseUrl!).hostname))
+ throw new Error('Local disposable database required')
+ const setup = await new DataSource({ type: 'postgres', url: databaseUrl, entities: [] }).initialize()
+ try {
+ await setup.query(`CREATE SCHEMA "${schema}"`)
+ } finally {
+ await setup.destroy()
+ }
+ db = await new DataSource(options()).initialize()
+ await db.query('CREATE TABLE organization (id uuid PRIMARY KEY, "updatedAt" timestamptz DEFAULT now())')
+ await db.query('INSERT INTO organization (id) VALUES ($1), ($2)', [organizationId, otherOrganizationId])
+ const runner = db.createQueryRunner()
+ try {
+ await new AddCancellationFeedback1795449600000().up(runner)
+ } finally {
+ await runner.release()
+ }
+ const { privateKey, publicKey } = await generateKeyPair('RS256')
+ const jwks = { keys: [{ ...(await exportJWK(publicKey)), kid: 'feedback', alg: 'RS256' }] }
+ server = createServer((_req, res) => {
+ res.setHeader('content-type', 'application/json')
+ res.end(JSON.stringify(jwks))
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const issuer = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
+ const users = {
+ findOne: (id: string) => ({ id, role: id === 'admin' ? SystemRole.ADMIN : SystemRole.USER, emailVerified: true }),
+ }
+ jwt = new JwtStrategy(
+ { issuer, audience: 'dashboard', jwksUri: `${issuer}/jwks` },
+ users as never,
+ { get: () => undefined } as never,
+ { recordFirstUse: jest.fn() } as never,
+ )
+ for (const userId of ['owner', 'member', 'outsider', 'admin']) {
+ tokens[userId] = await new SignJWT({})
+ .setProtectedHeader({ alg: 'RS256', kid: 'feedback' })
+ .setIssuer(issuer)
+ .setAudience('dashboard')
+ .setSubject(userId)
+ .setExpirationTime('1h')
+ .sign(privateKey)
+ }
+ await startApp()
+ })
+ async function startApp() {
+ const membership = {
+ findOne: (org: string, user: string) =>
+ org === organizationId && roles.has(user) ? { role: roles.get(user) } : null,
+ }
+ const module = await Test.createTestingModule({
+ controllers: [CancellationFeedbackController],
+ providers: [
+ CancellationFeedbackService,
+ { provide: DataSource, useValue: db },
+ { provide: JwtStrategy, useValue: jwt },
+ {
+ provide: OrganizationService,
+ useValue: {
+ findOne: async (id: string) => (await db.query('SELECT id FROM organization WHERE id=$1', [id]))[0] ?? null,
+ },
+ },
+ { provide: OrganizationUserService, useValue: membership },
+ { provide: getRedisConnectionToken(), useValue: cache },
+ ],
+ })
+ .overrideGuard(AuthenticatedRateLimitGuard)
+ .useValue({ canActivate: () => true })
+ .compile()
+ app = module.createNestApplication()
+ app.setGlobalPrefix('api')
+ app.useGlobalFilters(new AllExceptionsFilter({ incrementFailedAuth: jest.fn() } as never))
+ await app.listen(0, '127.0.0.1')
+ endpoint = await app.getUrl()
+ }
+
+ beforeEach(async () => {
+ cache.clear()
+ roles.clear()
+ roles.set('owner', OrganizationMemberRole.OWNER)
+ roles.set('member', OrganizationMemberRole.MEMBER)
+ await db.query('UPDATE organization SET "cancellationFeedback"=NULL')
+ })
+ afterAll(async () => {
+ await app?.close()
+ if (server?.listening) await new Promise<void>((resolve) => server.close(() => resolve()))
+ if (db?.isInitialized) {
+ await db.query(`DROP SCHEMA "${schema}" CASCADE`)
+ await db.destroy()
+ }
+ })
+ function put(body: unknown = feedback, token: string | null = tokens.owner, org = organizationId) {
+ return axios.put(`${endpoint}/api/organizations/${org}/cancellation-feedback`, body, {
+ headers: token ? { authorization: `Bearer ${token}` } : {},
+ validateStatus: () => true,
+ proxy: false,
+ })
+ }
+ async function stored(org = organizationId) {
+ return (await db.query('SELECT "cancellationFeedback" FROM organization WHERE id=$1', [org]))[0]
+ .cancellationFeedback
+ }
+ it('adds nullable storage, commits normalized answers, and persists across database reconnection', async () => {
+ expect(await stored()).toBeNull()
+ const before = Date.now()
+ const response = await put()
+ expect(response.status).toBe(204)
+ expect(response.data).toBe('')
+ const observer = await new DataSource(options()).initialize()
+ try {
+ const [row] = await observer.query('SELECT "cancellationFeedback" FROM organization WHERE id=$1', [
+ organizationId,
+ ])
+ expect(row.cancellationFeedback).toEqual({
+ reasons: ['other', 'pricing'],
+ intent: 'one_off',
+ note: 'Custom reason',
+ submittedBy: 'owner',
+ submittedAt: expect.any(String),
+ })
+ expect(Date.parse(row.cancellationFeedback.submittedAt)).toBeGreaterThanOrEqual(before)
+ } finally {
+ await observer.destroy()
+ }
+ expect(await stored(otherOrganizationId)).toBeNull()
+ })
+ it('replaces the latest feedback without adding rows and does not expose it in the organization DTO', async () => {
+ expect((await put()).status).toBe(204)
+ const next = { reasons: ['completed'], intent: null, note: '' }
+ expect((await put(next)).status).toBe(204)
+ expect((await put(next)).status).toBe(204)
+ expect(await stored()).toMatchObject(next)
+ expect(Number((await db.query('SELECT count(*) FROM organization'))[0].count)).toBe(2)
+ const dto = OrganizationDto.fromOrganization({ id: organizationId, cancellationFeedback: await stored() } as never)
+ expect(dto).not.toHaveProperty('cancellationFeedback')
+ })
+ it.each(['member', 'outsider', 'admin'])('denies %s without modifying feedback', async (user) => {
+ expect((await put(feedback, tokens[user])).status).toBe(403)
+ expect(await stored()).toBeNull()
+ })
+ it('denies unauthenticated, invalid-token and foreign-organization requests', async () => {
+ expect((await put(feedback, null)).status).toBe(401)
+ expect((await put(feedback, 'api-key-not-a-jwt')).status).toBe(401)
+ expect((await put(feedback, tokens.owner, otherOrganizationId)).status).toBe(403)
+ expect(await stored(otherOrganizationId)).toBeNull()
+ })
+ it('checks current ownership even when the access guard cached an owner', async () => {
+ expect((await put()).status).toBe(204)
+ roles.set('owner', OrganizationMemberRole.MEMBER)
+ expect((await put({ reasons: ['completed'] })).status).toBe(403)
+ expect((await stored()).reasons).toEqual(['other', 'pricing'])
+ })
+ it.each([
+ { reasons: [] },
+ { reasons: ['invalid'] },
+ { reasons: 'pricing' },
+ { reasons: Array(12).fill('other') },
+ { reasons: ['other'], note: 'x'.repeat(1001) },
+ { reasons: ['pricing'], note: 'private text' },
+ { reasons: ['pricing'], intent: 'invalid' },
+ { reasons: ['pricing'], submittedBy: 'forged' },
+ { reasons: ['pricing'], submittedAt: '2026-01-01' },
+ ])('rejects invalid feedback without echoing answers: %p', async (body) => {
+ const response = await put(body)
+ expect(response.status).toBe(400)
+ expect(response.data.message).toBe('Expected valid cancellation reasons, intent and optional note')
+ expect(await stored()).toBeNull()
+ })
+ it('accepts the text boundary and treats SQL-looking text only as data', async () => {
+ expect((await put({ reasons: ['other'], note: 'x'.repeat(1000) })).status).toBe(204)
+ expect((await stored()).note).toHaveLength(1000)
+ const note = "'); DROP TABLE organization; --"
+ expect((await put({ reasons: ['other'], note })).status).toBe(204)
+ expect((await stored()).note).toBe(note)
+ })
+ it('does not return saved when the organization was removed before its UPDATE', async () => {
+ const service = new CancellationFeedbackService(db)
+ await expect(service.save(randomUUID(), 'owner', { reasons: ['pricing'], intent: null, note: '' })).rejects.toThrow(
+ 'Organization not found',
+ )
+ })
+ it('retains accepted feedback after stopping and restarting the API and its database connection', async () => {
+ expect((await put()).status).toBe(204)
+ const previous = await stored()
+ await app.close()
+ await db.destroy()
+ db = await new DataSource(options()).initialize()
+ await startApp()
+ expect(await stored()).toEqual(previous)
+ expect((await put({ reasons: ['completed'] })).status).toBe(204)
+ expect((await stored()).reasons).toEqual(['completed'])
+ })
+})
diff --git a/apps/api/src/organization/dto/cancellation-feedback.ts b/apps/api/src/organization/dto/cancellation-feedback.ts
new file mode 100644
index 000000000..01f39c3f1
--- /dev/null
+++ b/apps/api/src/organization/dto/cancellation-feedback.ts
@@ -0,0 +1,31 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { z } from 'zod'
+
+export const cancellationFeedbackInput = z
+ .strictObject({
+ reasons: z
+ .array(
+ z.enum([
+ 'not_tried',
+ 'no_workload',
+ 'setup',
+ 'missing_features',
+ 'reliability',
+ 'performance',
+ 'pricing',
+ 'limits',
+ 'alternative',
+ 'completed',
+ 'other',
+ ]),
+ )
+ .max(11)
+ .transform((values) => [...new Set(values)]),
+ intent: z.enum(['evaluate', 'one_off', 'ongoing', 'explore', 'unsure']).nullable().default(null),
+ note: z.string().max(1000).trim().default(''),
+ })
+ .refine((value) => !value.note || value.reasons.includes('other'))
+ .refine((value) => value.reasons.length > 0 || value.intent !== null || value.note.length > 0)
+
+export type CancellationFeedbackInput = z.output<typeof cancellationFeedbackInput>
+export type CancellationFeedback = CancellationFeedbackInput & { submittedBy: string; submittedAt: string }
diff --git a/apps/api/src/organization/entities/organization.entity.ts b/apps/api/src/organization/entities/organization.entity.ts
index 014b2c04a..242881e8c 100644
--- a/apps/api/src/organization/entities/organization.entity.ts
+++ b/apps/api/src/organization/entities/organization.entity.ts
@@ -6,6 +6,7 @@
import { Column, CreateDateColumn, Entity, OneToMany, PrimaryGeneratedColumn, Unique, UpdateDateColumn } from 'typeorm'
import type { OnboardingDto } from '../dto/onboarding.dto'
+import type { CancellationFeedback } from '../dto/cancellation-feedback'
import { OrganizationUser } from './organization-user.entity'
import { OrganizationRole } from './organization-role.entity'
import { OrganizationInvitation } from './organization-invitation.entity'
@@ -22,6 +23,9 @@ export class Organization {
@Column({ type: 'jsonb', nullable: true })
onboarding: OnboardingDto | null
+ @Column({ type: 'jsonb', nullable: true, select: false })
+ cancellationFeedback: CancellationFeedback | null
+
@Column()
name: string
diff --git a/apps/api/src/organization/organization.module.ts b/apps/api/src/organization/organization.module.ts
index 2b7b76d87..5ae49f3f8 100644
--- a/apps/api/src/organization/organization.module.ts
+++ b/apps/api/src/organization/organization.module.ts
@@ -5,6 +5,8 @@
*/
import { OnboardingController } from './controllers/onboarding.controller'
+import { CancellationFeedbackController } from './controllers/cancellation-feedback.controller'
+import { CancellationFeedbackService } from './services/cancellation-feedback.service'
import { CouponClaimsController } from './controllers/coupon-claims.controller'
import { CouponClaimsService } from './services/coupon-claims.service'
import { OnboardingService } from './services/onboarding.service'
@@ -56,6 +58,7 @@ import { UsageController } from '../usage/controllers/usage.controller'
UsageModule,
],
controllers: [
+ CancellationFeedbackController,
CouponClaimsController,
OnboardingController,
OrganizationController,
@@ -66,6 +69,7 @@ import { UsageController } from '../usage/controllers/usage.controller'
UsageController,
],
providers: [
+ CancellationFeedbackService,
CouponClaimsService,
OnboardingService,
OrganizationBoxLimitsService,
diff --git a/apps/api/src/organization/services/cancellation-feedback.service.spec.ts b/apps/api/src/organization/services/cancellation-feedback.service.spec.ts
new file mode 100644
index 000000000..52239d23a
--- /dev/null
+++ b/apps/api/src/organization/services/cancellation-feedback.service.spec.ts
@@ -0,0 +1,27 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { InternalServerErrorException } from '@nestjs/common'
+import { DataSource } from 'typeorm'
+import { CancellationFeedbackService } from './cancellation-feedback.service'
+import { CancellationFeedbackController } from '../controllers/cancellation-feedback.controller'
+
+it('sanitizes persistence failures instead of leaking SQL parameters', async () => {
+ const service = new CancellationFeedbackService({
+ query: jest.fn().mockRejectedValue(new Error('query: private answer')),
+ } as unknown as DataSource)
+ await expect(
+ service.save('org', 'owner', { reasons: ['other'], intent: null, note: 'private answer' }),
+ ).rejects.toEqual(new InternalServerErrorException('Unable to save cancellation feedback. Please retry.'))
+})
+
+it('rejects machine credentials before membership lookup or feedback persistence', async () => {
+ const save = jest.fn()
+ const findOne = jest.fn()
+ const controller = new CancellationFeedbackController({ save } as never, { findOne } as never)
+ for (const actor of [{ userId: 'owner', apiKey: {} }, { userId: '' }]) {
+ await expect(controller.save(actor as never, { reasons: ['pricing'] })).rejects.toThrow(
+ 'Organization owner required',
+ )
+ }
+ expect(findOne).not.toHaveBeenCalled()
+ expect(save).not.toHaveBeenCalled()
+})
diff --git a/apps/api/src/organization/services/cancellation-feedback.service.ts b/apps/api/src/organization/services/cancellation-feedback.service.ts
new file mode 100644
index 000000000..84c80def0
--- /dev/null
+++ b/apps/api/src/organization/services/cancellation-feedback.service.ts
@@ -0,0 +1,24 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { Injectable, InternalServerErrorException, NotFoundException } from '@nestjs/common'
+import { DataSource } from 'typeorm'
+import type { CancellationFeedbackInput } from '../dto/cancellation-feedback'
+
+@Injectable()
+export class CancellationFeedbackService {
+ constructor(private readonly db: DataSource) {}
+
+ async save(organizationId: string, userId: string, input: CancellationFeedbackInput): Promise<void> {
+ const value = { ...input, submittedBy: userId, submittedAt: new Date().toISOString() }
+ let rows: { id: string }[]
+ try {
+ ;[rows] = await this.db.query(
+ 'UPDATE organization SET "cancellationFeedback" = $2::jsonb, "updatedAt" = now() WHERE id = $1 RETURNING id',
+ [organizationId, JSON.stringify(value)],
+ )
+ } catch {
+ // Query errors can include the customer's free-text answers in SQL parameters.
+ throw new InternalServerErrorException('Unable to save cancellation feedback. Please retry.')
+ }
+ if (!rows.length) throw new NotFoundException('Organization not found')
+ }
+}
diff --git a/apps/dashboard/README.md b/apps/dashboard/README.md
index a8871f3d2..f8ef7beb9 100644
--- a/apps/dashboard/README.md
+++ b/apps/dashboard/README.md
@@ -1588,3 +1588,7 @@ For mock layout review, open `/dashboard/boxes/mock-box-stopped` and its
`/terminal` route. Compare desktop, ultrawide, narrow and zoom-equivalent CSS
viewports with expanded and collapsed navigation. Mock fixtures verify layout
and action wiring, not guest connectivity.
+
+## Subscription cancellation
+
+Owners can cancel from Billing Overview or the Plans current-plan card using one shared dialog with optional feedback. See [subscription cancellation](docs/subscription-cancellation.md) for the request contract, retry behavior, release dependency and local mock review instructions.
diff --git a/apps/dashboard/docs/assets/subscription-cancellation-feedback.png b/apps/dashboard/docs/assets/subscription-cancellation-feedback.png
new file mode 100644
index 000000000..fe90858ec
Binary files /dev/null and b/apps/dashboard/docs/assets/subscription-cancellation-feedback.png differ
diff --git a/apps/dashboard/docs/assets/subscription-cancellation-mobile.png b/apps/dashboard/docs/assets/subscription-cancellation-mobile.png
new file mode 100644
index 000000000..7386d18c2
Binary files /dev/null and b/apps/dashboard/docs/assets/subscription-cancellation-mobile.png differ
diff --git a/apps/dashboard/docs/subscription-cancellation.md b/apps/dashboard/docs/subscription-cancellation.md
new file mode 100644
index 000000000..10566b843
--- /dev/null
+++ b/apps/dashboard/docs/subscription-cancellation.md
@@ -0,0 +1,96 @@
+# Subscription cancellation
+
+## Customer flow
+
+Organization owners can cancel from Billing Overview's Active Plan panel or the current plan in Plans. Both entries open the same FormDialog.
+
+Confirmation states the current organization, plan and server-provided cycle end. Paid quota remains available until that boundary.
+
+Trial cancellation before conversion prevents conversion; a payment already processing must be reconciled by the billing service. Trial cancellation cannot be undone.
+
+Paid scheduled cancellation retains the existing Keep action.
+
+
+Share feedback is always expanded and optional. Reasons allow multiple selections; original intent allows one selection or none.
+
+Other — tell us more reveals Your reason, an optional 1,000-character text field. Closing an unsubmitted dialog makes no API request.
+
+The fixed footer remains reachable while the body scrolls, using the shared FormDialog, Button, Checkbox, RadioGroup and Textarea.
+
+
+## Persistence and failure handling
+
+The Console calls the existing `POST /api/billing/organization/:organizationId/plan/downgrade` with `{ "planId": null }`. The current plan requires no subscription identifier extension, and the billing service needs no changes.
+
+Before sending, the Console reads the plan and compares its plan ID, cycle end and trial conversion state with the dialog. Changed terms require another explicit confirmation. This read does not atomically condition the subsequent POST: another tab can change the plan between them.
+
+Only refreshed cancellation state confirms cancellation. A lost response or failed/empty refresh keeps the answers and offers Check status; this button only reads state. An active plan then requires explicit confirmation again, with the refreshed terms.
+
+Cancellation and status requests have finite deadlines. Confirmation is shown before waiting for optional feedback, so feedback failure does not delay the cancellation result.
+
+The optional answers go to `PUT /api/organizations/:organizationId/cancellation-feedback` in the main API. Its successful 204 response means the organization row update completed. The nullable JSONB field `cancellationFeedback` stores reasons, nullable intent, note, and server-owned submittedBy/submittedAt.
+
+This is the latest accepted feedback, not a cancellation receipt or history. A new submission replaces the previous value; no answers means no write. Separate tabs use database write order, not click time.
+
+A feedback failure keeps one draft in the shared Billing controller for Retry feedback. This retry only writes the organization field, without another cancellation request. A later confirmed cancellation supersedes the old unsaved draft, including when no new answers were supplied.
+
+Changing organization, leaving Billing or reloading discards unaccepted drafts. Late responses from an old controller cannot submit further requests or change the new organization's UI. No feedback text is placed in URL parameters, analytics or application logs.
+
+The feedback endpoint requires an authenticated current organization owner and rejects API keys. The field is excluded from ordinary organization queries and responses. See [API persistence and rollout](../../api/README.md#organization-cancellation-feedback).
+
+## Local UI review
+
+Run from the repository root:
+
+```sh
+NX_DAEMON=false NX_ISOLATE_PLUGINS=false node apps/scripts/start-dashboard.mjs --target=mock --host 127.0.0.1 --port 43134
+```
+
+Open `http://127.0.0.1:43134/dashboard/billing?preview=subscription-cancel&tab=plans`.
+
+The dedicated MSW handlers use the production client endpoints. They model `scenario=paid` (default), `trial`, `scheduled`, `none` and `readonly`; `failure=cancel` or `failure=feedback` fails the first matching request.
+
+Mock state resets on reload. This review mode makes no production billing calls and is not evidence of database durability.
+
+Real PostgreSQL and authenticated HTTP tests validate organization persistence separately from this in-memory UI preview.
+
+
+## Verification
+
+`make build:apps:dashboard` validates the production bundle and types. `make test:apps:dashboard` covers the client contract and shared dialog along with the existing dashboard suite.
+
+Request-mapping and rendered UI tests cover the new cancellation and organization-feedback contract. Cases include no answers, custom text, status-only checks, changed terms, feedback-only retry, superseded drafts and organization switching. Trial recovery is an existing-behavior fix: its regression assertion fails against the complete base checkout (Keep Pro instead of null), then passes with the fix.
+
+
+The design reuses [WAI dialog guidance](https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal/) through the existing Radix/FormDialog primitives. Browser review verifies actual Console entry placement, fixed footer, custom text, success state and feedback retry.
+
+## Shared state and requests
+
+```mermaid
+sequenceDiagram
+ participant Owner
+ participant Console
+ participant Billing as Existing billing API
+ participant API as Organization API
+ participant DB as PostgreSQL
+ Owner->>Console: Confirm with optional feedback
+ Console->>Billing: Read latest plan
+ Console->>Billing: downgradePlan(org, null)
+ Console->>Billing: Refresh cancellation state
+ Console-->>Owner: Confirmed result or Check status
+ opt Cancellation confirmed and answers provided
+ Console->>API: PUT cancellation-feedback
+ API->>DB: UPDATE organization JSONB
+ DB-->>API: Committed
+ API-->>Console: 204 or separate save failure
+ end
+ Note over Console,API: Retry feedback never repeats cancellation
+```
+
+## UI review examples
+
+The previous Billing surface exposed scheduled-change recovery without a direct cancellation entry. The new current-plan action opens the shared confirmation flow shown below using mock organization data.
+
+![Custom cancellation reason in the shared Console dialog](assets/subscription-cancellation-feedback.png)
+
+![Narrow-screen cancellation dialog with a fixed confirmation footer](assets/subscription-cancellation-mobile.png)
diff --git a/apps/dashboard/src/api/apiClient.test.ts b/apps/dashboard/src/api/apiClient.test.ts
index 8aedf2a3c..2364f952b 100644
--- a/apps/dashboard/src/api/apiClient.test.ts
+++ b/apps/dashboard/src/api/apiClient.test.ts
@@ -757,3 +757,23 @@ describe('tunnel request boundaries', () => {
expect(requests).toHaveLength(1)
})
})
+
+it('saves cancellation feedback on the selected organization with a bounded PUT', async () => {
+ const requests: any[] = []
+ const api = await makeClient(vi.fn(), 204, undefined, requests)
+ const feedback = { reasons: ['other'], intent: null, note: 'A custom reason' }
+ await api.saveCancellationFeedback('org/one', feedback)
+ expect(requests[0]).toMatchObject({
+ method: 'put',
+ url: '/organizations/org%2Fone/cancellation-feedback',
+ timeout: 10_000,
+ })
+ expect(JSON.parse(requests[0].data)).toEqual(feedback)
+})
+
+it('does not treat an unexpected feedback response as saved', async () => {
+ const api = await makeClient(vi.fn(), 200, '<html>not an API response</html>')
+ await expect(api.saveCancellationFeedback('org', { reasons: ['pricing'], intent: null, note: '' })).rejects.toThrow(
+ 'not confirmed',
+ )
+})
diff --git a/apps/dashboard/src/api/apiClient.ts b/apps/dashboard/src/api/apiClient.ts
index cb9c5e994..52752890f 100644
--- a/apps/dashboard/src/api/apiClient.ts
+++ b/apps/dashboard/src/api/apiClient.ts
@@ -86,6 +86,12 @@ function clearReauthAttempted(): void {
// Prefer bash when the image has it; every image has sh.
const LOGIN_SHELL = 'if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi'
+export interface CancellationFeedbackInput {
+ reasons: string[]
+ intent: string | null
+ note: string
+}
+
export interface OrganizationOnboarding {
useCase: FirstRunUseCase
note: string
@@ -123,6 +129,14 @@ export class ApiClient {
return receipt.data
}
+ public async saveCancellationFeedback(org: string, feedback: CancellationFeedbackInput): Promise<void> {
+ const response = await this.http.put(`/organizations/${encodeURIComponent(org)}/cancellation-feedback`, feedback, {
+ ...this.v1Config(),
+ timeout: 10_000,
+ })
+ if (response.status !== 204) throw new BoxliteError('Feedback save was not confirmed')
+ }
+
public async register(turnstileToken: string): Promise<User> {
return (await this.http.post<User>('/auth/register', { turnstileToken }, { ...this.v1Config(), timeout: 30_000 }))
.data
diff --git a/apps/dashboard/src/billing-api/billingApiClient.test.ts b/apps/dashboard/src/billing-api/billingApiClient.test.ts
index bf3dca7cd..40b21faf9 100644
--- a/apps/dashboard/src/billing-api/billingApiClient.test.ts
+++ b/apps/dashboard/src/billing-api/billingApiClient.test.ts
@@ -9,13 +9,21 @@ let requestedUrl = ''
let requestedUrls: string[] = []
let requestedMethod = ''
let requestedData: unknown
+let requestedTimeout: number | undefined
function serve(data: unknown | ((url: string) => unknown)): BillingApiClient {
requestedUrls = []
- axios.defaults.adapter = (async (cfg: { url?: string; baseURL?: string; method?: string; data?: unknown }) => {
+ axios.defaults.adapter = (async (cfg: {
+ url?: string
+ baseURL?: string
+ method?: string
+ data?: unknown
+ timeout?: number
+ }) => {
requestedUrl = `${cfg.baseURL ?? ''}${cfg.url ?? ''}`
requestedUrls.push(requestedUrl)
requestedMethod = cfg.method ?? ''
requestedData = cfg.data
+ requestedTimeout = cfg.timeout
const responseData = typeof data === 'function' ? data(requestedUrl) : data
return { data: responseData, status: 200, statusText: 'OK', headers: {}, config: cfg }
}) as never
@@ -395,3 +403,28 @@ describe('saved card actions', () => {
expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/payment-methods/card-2')
})
})
+
+describe('subscription cancellation API', () => {
+ it.each([undefined, 10_000])('preserves plan reads with timeout %s', async (timeout) => {
+ const api = serve({})
+ expect(await api.getOrganizationPlan('org-1', timeout)).toBeNull()
+ expect(requestedMethod).toBe('get')
+ expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/plan')
+ expect(requestedTimeout).toBe(timeout ?? 0)
+ })
+ it('preserves the existing downgrade request when no timeout is supplied', async () => {
+ const api = serve(undefined)
+ await api.downgradePlan('org-1', 'go')
+ expect(requestedMethod).toBe('post')
+ expect(JSON.parse(requestedData as string)).toEqual({ planId: 'go' })
+ expect(requestedTimeout).toBe(0)
+ })
+ it('reuses downgrade with a null plan and bounds the cancellation request', async () => {
+ const api = serve(undefined)
+ await api.downgradePlan('org-1', null, 15_000)
+ expect(requestedUrl).toBe('http://billing.test/api/billing/organization/org-1/plan/downgrade')
+ expect(requestedMethod).toBe('post')
+ expect(JSON.parse(requestedData as string)).toEqual({ planId: null })
+ expect(requestedTimeout).toBe(15_000)
+ })
+})
diff --git a/apps/dashboard/src/billing-api/billingApiClient.ts b/apps/dashboard/src/billing-api/billingApiClient.ts
index c0e37373d..3964ce969 100644
--- a/apps/dashboard/src/billing-api/billingApiClient.ts
+++ b/apps/dashboard/src/billing-api/billingApiClient.ts
@@ -94,8 +94,11 @@ export class BillingApiClient {
return response.data?.message || 'Coupon redeemed successfully'
}
- public async getOrganizationPlan(organizationId: string): Promise<OrganizationPlan | null> {
- const response = await this.axiosInstance.get(`/organization/${organizationId}/plan`)
+ public async getOrganizationPlan(organizationId: string, timeout?: number): Promise<OrganizationPlan | null> {
+ const response = await this.axiosInstance.get(
+ `/organization/${organizationId}/plan`,
+ timeout ? { timeout } : undefined,
+ )
// {} (no `plan` key) means no live plan — the server never sends a bare null.
const plan = response.data?.plan
if (!plan) {
@@ -140,8 +143,12 @@ export class BillingApiClient {
return response.data?.url
}
- public async downgradePlan(organizationId: string, planId: string | null): Promise<void> {
- await this.axiosInstance.post(`/organization/${organizationId}/plan/downgrade`, { planId })
+ public async downgradePlan(organizationId: string, planId: string | null, timeout?: number): Promise<void> {
+ await this.axiosInstance.post(
+ `/organization/${organizationId}/plan/downgrade`,
+ { planId },
+ timeout ? { timeout } : undefined,
+ )
}
public async withdrawPendingPlan(organizationId: string): Promise<void> {
diff --git a/apps/dashboard/src/components/billing/CycleOverview.tsx b/apps/dashboard/src/components/billing/CycleOverview.tsx
index f99587f2a..dab217710 100644
--- a/apps/dashboard/src/components/billing/CycleOverview.tsx
+++ b/apps/dashboard/src/components/billing/CycleOverview.tsx
@@ -14,6 +14,7 @@ import { handleApiError } from '@/lib/error-handling'
import { formatAmount, formatWholeDollars } from '@/lib/utils'
import { differenceInCalendarDays } from 'date-fns'
import { toast } from 'sonner'
+import { SubscriptionCancellationAction } from './SubscriptionCancellation'
/**
* How this organization is being billed right now, and the figures that follow
@@ -133,6 +134,9 @@ export function CycleOverview({
{scheduled && organizationPlan && (
<ScheduledChangeNote scheduled={scheduled} organizationId={organizationId} planId={organizationPlan.planId} />
)}
+ {organizationPlan && organizationId && (
+ <SubscriptionCancellationAction plan={organizationPlan} organizationId={organizationId} />
+ )}
</Panel>
</section>
)
@@ -179,7 +183,7 @@ function ScheduledChangeNote({
return (
<div className="flex flex-wrap items-center justify-between gap-3 border-t border-border px-[22px] py-4">
<PanelNote>{scheduled.text}</PanelNote>
- {organizationId && (
+ {organizationId && scheduled.keepLabel && (
<AsciiButton
disabled={keepPlan.isPending}
onClick={handleKeep}
diff --git a/apps/dashboard/src/components/billing/PlanComparison.tsx b/apps/dashboard/src/components/billing/PlanComparison.tsx
index ff901f542..4e2d0f68a 100644
--- a/apps/dashboard/src/components/billing/PlanComparison.tsx
+++ b/apps/dashboard/src/components/billing/PlanComparison.tsx
@@ -67,12 +67,14 @@ export function PlanComparison({
plans,
organizationPlan,
canManage = true,
+ subscriptionAction,
trialOffers,
checkingTrials = false,
}: {
plans: Plan[]
organizationPlan?: OrganizationPlan | null
canManage?: boolean
+ subscriptionAction?: ReactNode
trialOffers?: PlanTrialEligibility[]
checkingTrials?: boolean
}) {
@@ -198,6 +200,7 @@ export function PlanComparison({
</span>
)}
</div>
+ {canManage && plan.id === currentId && subscriptionAction}
</div>
</th>
)
diff --git a/apps/dashboard/src/components/billing/PlanSection.tsx b/apps/dashboard/src/components/billing/PlanSection.tsx
index 1d906b257..9d05170ba 100644
--- a/apps/dashboard/src/components/billing/PlanSection.tsx
+++ b/apps/dashboard/src/components/billing/PlanSection.tsx
@@ -41,6 +41,11 @@ export function PlanSection({ onViewPlans }: { onViewPlans?: () => void }) {
return (
<div className="flex flex-col gap-8">
+ {authenticatedUserOrganizationMember && !isOwner && (
+ <p className="text-body text-muted-foreground">
+ Only an organization owner can view billing details or manage the subscription.
+ </p>
+ )}
{isError ? (
<Panel className="flex flex-col items-center gap-3 px-[22px] py-10">
<span className="font-sans text-body text-foreground">Oops, something went wrong</span>
diff --git a/apps/dashboard/src/components/billing/PlansSection.tsx b/apps/dashboard/src/components/billing/PlansSection.tsx
index e628aff3b..e9a08a457 100644
--- a/apps/dashboard/src/components/billing/PlansSection.tsx
+++ b/apps/dashboard/src/components/billing/PlansSection.tsx
@@ -1,5 +1,6 @@
/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
import { PlanComparison } from './PlanComparison'
+import { SubscriptionCancellationAction } from './SubscriptionCancellation'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { useOwnerPlanQuery, useOwnerTrialEligibilityQuery } from '@/hooks/queries/billingQueries'
@@ -87,6 +88,15 @@ export function PlansSection() {
canManage={canManage}
trialOffers={trialOffers}
checkingTrials={checkingTrials}
+ subscriptionAction={
+ canManage && subscription.data && selectedOrganization ? (
+ <SubscriptionCancellationAction
+ plan={subscription.data}
+ organizationId={selectedOrganization.id}
+ compact
+ />
+ ) : undefined
+ }
/>
)}
</section>
diff --git a/apps/dashboard/src/components/billing/SubscriptionCancellation.spec.tsx b/apps/dashboard/src/components/billing/SubscriptionCancellation.spec.tsx
new file mode 100644
index 000000000..8a8f46b4f
--- /dev/null
+++ b/apps/dashboard/src/components/billing/SubscriptionCancellation.spec.tsx
@@ -0,0 +1,396 @@
+// @vitest-environment jsdom
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { OrganizationPlan } from '@/billing-api'
+import { SubscriptionCancellationProvider, SubscriptionCancellationAction } from './SubscriptionCancellation'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+
+const mocks = vi.hoisted(() => ({
+ cancel: vi.fn(),
+ save: vi.fn(),
+ read: vi.fn(),
+ keep: vi.fn(),
+ org: 'review-org',
+ role: 'owner',
+}))
+vi.mock('@/hooks/useApi', () => ({
+ useApi: () => ({
+ saveCancellationFeedback: mocks.save,
+ billingApi: { downgradePlan: mocks.cancel, getOrganizationPlan: mocks.read },
+ }),
+}))
+vi.mock('@/hooks/useSelectedOrganization', () => ({
+ useSelectedOrganization: () => ({
+ selectedOrganization: { id: mocks.org, name: 'Review Org' },
+ authenticatedUserOrganizationMember: { role: mocks.role },
+ }),
+}))
+vi.mock('@/hooks/mutations/useKeepPlanMutation', () => ({
+ useKeepPlanMutation: () => ({ mutateAsync: mocks.keep, isPending: false }),
+}))
+let root: Root
+let client: QueryClient
+const plan: OrganizationPlan = {
+ planId: 'pro',
+ planName: 'Pro',
+ status: 'active',
+ cycleFrom: new Date('2026-11-23'),
+ cycleTo: new Date('2026-12-23'),
+ includedQuotaCents: 25000,
+ quotaConsumedCents: 6250,
+ quotaRemainingCents: 18750,
+}
+let current: OrganizationPlan | null
+function button(text: string) {
+ const match = [...document.querySelectorAll('button')].find((node) => node.textContent === text)
+ if (!match) throw new Error(`Missing button: ${text}`)
+ return match
+}
+async function click(text: string) {
+ await act(async () => {
+ button(text).click()
+ })
+}
+async function chooseReason() {
+ await act(async () => {
+ document.querySelector<HTMLButtonElement>('[role=checkbox]')!.click()
+ })
+}
+function render(value = plan, compact = false) {
+ act(() =>
+ root.render(
+ <QueryClientProvider client={client}>
+ <SubscriptionCancellationProvider>
+ <SubscriptionCancellationAction organizationId={mocks.org} plan={value} compact={compact} />
+ </SubscriptionCancellationProvider>
+ </QueryClientProvider>,
+ ),
+ )
+}
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ mocks.org = 'review-org'
+ mocks.role = 'owner'
+ current = { ...plan }
+ mocks.read.mockReset().mockImplementation(async () => current)
+ mocks.cancel.mockReset().mockImplementation(async () => {
+ current = { ...plan, cancelAtPeriodEnd: true }
+ })
+ mocks.save.mockReset().mockResolvedValue(undefined)
+ mocks.keep.mockReset().mockResolvedValue(undefined)
+ const host = document.createElement('div')
+ document.body.append(host)
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ root = createRoot(host)
+ render()
+})
+afterEach(() => {
+ act(() => root.unmount())
+ document.body.innerHTML = ''
+})
+describe('subscription cancellation contract', () => {
+ it('dismisses the review dialog with Escape without changing renewal', async () => {
+ await click('Cancel subscription')
+ await act(async () => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })))
+ expect(document.querySelector('[role=dialog]')).toBeNull()
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ })
+ it('follows the billing redirect when restoring renewal requires checkout', async () => {
+ render({ ...plan, cancelAtPeriodEnd: true }, true)
+ const destination = `${window.location.href.split('#')[0]}#restore-checkout`
+ mocks.keep.mockResolvedValue(destination)
+ await click('Keep subscription')
+ expect(window.location.href).toBe(destination)
+ window.history.replaceState(null, '', window.location.pathname)
+ })
+ it('shows the trial end date in the overview cancellation entry', () => {
+ render({
+ ...plan,
+ trial: {
+ startedAt: plan.cycleFrom,
+ endsAt: plan.cycleTo,
+ conversionAmountCents: 14900,
+ currency: 'USD',
+ conversionState: 'not_attempted',
+ },
+ })
+ expect(document.body.textContent).toContain('Trial ends Dec 23, 2026')
+ })
+ it.each(['preflight', 'confirmation'] as const)(
+ 'ignores a late %s read after an organization switch',
+ async (stage) => {
+ let resolve!: (value: OrganizationPlan) => void
+ const response = new Promise<OrganizationPlan>((done) => {
+ resolve = done
+ })
+ if (stage === 'confirmation') mocks.read.mockResolvedValueOnce(plan)
+ mocks.read.mockImplementationOnce(() => response)
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ mocks.org = 'other-org'
+ render()
+ await act(async () => resolve({ ...plan, cancelAtPeriodEnd: true }))
+ expect(mocks.cancel).toHaveBeenCalledTimes(stage === 'preflight' ? 0 : 1)
+ expect(mocks.save).not.toHaveBeenCalled()
+ expect(document.body.textContent).not.toContain('Cancellation confirmed')
+ },
+ )
+ it.each([false, true])(
+ 'does not expose late feedback results in another organization (reject: %s)',
+ async (reject) => {
+ let finish!: () => void
+ mocks.save.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve, fail) => {
+ finish = () => (reject ? fail(new Error('offline')) : resolve())
+ }),
+ )
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ expect(document.body.textContent).toContain('Cancellation confirmed')
+ mocks.org = 'other-org'
+ render()
+ await act(async () => finish())
+ expect(document.body.textContent).not.toContain('feedback has been saved')
+ expect(document.body.textContent).not.toContain('Retry feedback')
+ },
+ )
+ it('restores paid renewal from the current plan card and allows retry after failure', async () => {
+ render({ ...plan, cancelAtPeriodEnd: true }, true)
+ expect(document.body.textContent).toContain('Ends on Dec 23, 2026')
+ mocks.keep.mockRejectedValueOnce(new Error('unavailable'))
+ await click('Keep subscription')
+ expect(document.querySelector('[role=alert]')?.textContent).toContain('Couldn’t restore renewal')
+ await click('Keep subscription')
+ expect(mocks.keep).toHaveBeenLastCalledWith({ organizationId: 'review-org', planId: 'pro', kind: 'cancel' })
+ expect(document.querySelector('[role=alert]')).toBeNull()
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ })
+ it.each(['not_attempted', 'pending'] as const)(
+ 'explains trial cancellation in state %s without offering unsupported restoration',
+ async (conversionState) => {
+ const trialPlan = {
+ ...plan,
+ pendingPlanId: 'team',
+ trial: {
+ startedAt: plan.cycleFrom,
+ endsAt: plan.cycleTo,
+ conversionAmountCents: 14900,
+ currency: 'USD',
+ conversionState,
+ },
+ } satisfies OrganizationPlan
+ render(trialPlan, true)
+ await click('Cancel subscription')
+ expect(document.body.textContent).toContain(
+ conversionState === 'not_attempted'
+ ? 'Your trial will not convert to a paid subscription.'
+ : 'Trial conversion is already in progress.',
+ )
+ expect(document.body.textContent).toContain('This replaces your scheduled plan change.')
+ await click('Keep subscription')
+ render({ ...trialPlan, cancelAtPeriodEnd: true }, true)
+ expect(document.body.textContent).toContain('Ends on')
+ expect(document.body.textContent).not.toContain('Keep subscription')
+ },
+ )
+ it('recovers a preflight failure without issuing cancellation prematurely', async () => {
+ mocks.read.mockRejectedValueOnce(new Error('offline'))
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ expect(document.body.textContent).toContain('Your answers are kept')
+ await click('Confirm cancellation')
+ expect(mocks.save).toHaveBeenCalledWith('review-org', { reasons: ['not_tried'], intent: null, note: '' })
+ })
+ it('reopens an unresolved cancellation and confirms refreshed canceled status without another POST', async () => {
+ mocks.cancel.mockResolvedValue(undefined)
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ await click('Close')
+ await click('Check cancellation')
+ expect(document.querySelector('[role=checkbox]')?.getAttribute('aria-checked')).toBe('true')
+ await click('Close')
+ await click('Cancel subscription')
+ current = { ...plan, status: 'canceled' }
+ await click('Check status')
+ expect(mocks.cancel).toHaveBeenCalledTimes(1)
+ expect(mocks.save).toHaveBeenCalledTimes(1)
+ expect(document.querySelector('[role=dialog]')).toBeNull()
+ render(current, true)
+ expect(document.body.textContent).not.toContain('Cancel subscription')
+ })
+ it('keeps feedback after another save failure and retries only the feedback', async () => {
+ mocks.save.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('still offline'))
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ await click('Retry feedback')
+ expect(document.body.textContent).toContain('Your feedback wasn’t saved')
+ await click('Retry feedback')
+ expect(document.body.textContent).toContain('Your cancellation feedback has been saved')
+ expect(mocks.save).toHaveBeenCalledTimes(3)
+ expect(mocks.cancel).toHaveBeenCalledTimes(1)
+ })
+ it('saves an optional intent alone and respects clearing optional answers', async () => {
+ await click('Cancel subscription')
+ await chooseReason()
+ await chooseReason()
+ await act(async () => document.querySelector<HTMLButtonElement>('[role=radio]')!.click())
+ await click('Clear selection')
+ expect(document.querySelector('[role=radio]')?.getAttribute('aria-checked')).toBe('false')
+ await act(async () => document.querySelector<HTMLButtonElement>('[role=radio]')!.click())
+ await click('Confirm cancellation')
+ expect(mocks.save).toHaveBeenCalledWith('review-org', { reasons: [], intent: 'evaluate', note: '' })
+ })
+ it('opens and closes without cancellation or feedback writes', async () => {
+ await click('Cancel subscription')
+ expect(document.querySelector('[role=dialog]')?.textContent).toContain('Review Org')
+ await click('Keep subscription')
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ expect(mocks.save).not.toHaveBeenCalled()
+ })
+ it('uses existing cancellation without subscription ID or optional feedback', async () => {
+ await click('Cancel subscription')
+ await click('Confirm cancellation')
+ expect(mocks.cancel).toHaveBeenCalledExactlyOnceWith('review-org', null, 15_000)
+ expect(mocks.save).not.toHaveBeenCalled()
+ expect(document.querySelector('[role=dialog]')).toBeNull()
+ expect(document.body.textContent).toContain('Cancellation confirmed')
+ })
+ it('keeps answers and checks status without replaying an uncertain cancellation', async () => {
+ mocks.cancel.mockRejectedValueOnce(new Error('failed'))
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ expect(document.querySelector('[role=alert]')?.textContent).toContain('Your answers are kept')
+ expect(document.querySelector('[role=checkbox]')?.getAttribute('aria-checked')).toBe('true')
+ expect(mocks.save).not.toHaveBeenCalled()
+ await click('Check status')
+ expect(mocks.cancel).toHaveBeenCalledTimes(1)
+ expect(document.body.textContent).toContain('Renewal is still on')
+ await click('Confirm cancellation')
+ expect(mocks.cancel).toHaveBeenCalledTimes(2)
+ expect(mocks.save).toHaveBeenCalledTimes(1)
+ })
+ it('confirms a lost response through refreshed state and saves feedback', async () => {
+ mocks.cancel.mockImplementationOnce(async () => {
+ current = { ...plan, cancelAtPeriodEnd: true }
+ throw new Error('response lost')
+ })
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ expect(mocks.cancel).toHaveBeenCalledTimes(1)
+ expect(mocks.save).toHaveBeenCalledWith('review-org', { reasons: ['not_tried'], intent: null, note: '' })
+ expect(document.querySelector('[role=dialog]')).toBeNull()
+ })
+ it('does not equate HTTP success or an empty plan with confirmed cancellation', async () => {
+ mocks.cancel.mockResolvedValue(undefined)
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ expect(document.body.textContent).toContain('could not be confirmed')
+ current = null
+ await click('Check status')
+ expect(mocks.save).not.toHaveBeenCalled()
+ expect(mocks.cancel).toHaveBeenCalledTimes(1)
+ expect(document.querySelector('[role=dialog]')).not.toBeNull()
+ })
+ it('requires another confirmation after plan terms change', async () => {
+ await click('Cancel subscription')
+ current = { ...plan, cycleTo: new Date('2027-01-23') }
+ await click('Confirm cancellation')
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ expect(document.body.textContent).toContain('Your plan changed')
+ expect(document.body.textContent).toContain('Jan 23, 2027')
+ })
+ it('does not claim the preflight read atomically protects a later plan change', async () => {
+ mocks.cancel.mockImplementationOnce(async () => {
+ current = { ...plan, cycleTo: new Date('2027-01-23'), cancelAtPeriodEnd: true }
+ })
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ expect(mocks.save).not.toHaveBeenCalled()
+ expect(document.body.textContent).toContain('could not be confirmed')
+ await click('Check status')
+ expect(mocks.cancel).toHaveBeenCalledTimes(1)
+ expect(document.body.textContent).toContain('Your plan changed')
+ })
+ it('retries feedback independently after the plan is canceled', async () => {
+ mocks.save.mockRejectedValueOnce(new Error('feedback failed'))
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ render({ ...plan, cancelAtPeriodEnd: true })
+ expect(document.body.textContent).toContain('Cancellation confirmed. Your feedback wasn’t saved.')
+ await click('Retry feedback')
+ expect(mocks.cancel).toHaveBeenCalledTimes(1)
+ expect(mocks.save).toHaveBeenCalledTimes(2)
+ expect(mocks.save.mock.calls[1]).toEqual(mocks.save.mock.calls[0])
+ })
+ it('discards older unsaved feedback after another cancellation without answers', async () => {
+ mocks.save.mockRejectedValueOnce(new Error('feedback failed'))
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ current = { ...plan }
+ render(plan)
+ await click('Cancel subscription')
+ await click('Confirm cancellation')
+ expect(mocks.cancel).toHaveBeenCalledTimes(2)
+ expect(mocks.save).toHaveBeenCalledTimes(1)
+ expect(document.body.textContent).not.toContain('Retry feedback')
+ })
+ it('offers a custom reason without collapsing feedback', async () => {
+ await click('Cancel subscription')
+ expect(document.querySelector('details')).toBeNull()
+ const label = [...document.querySelectorAll('label')].find((node) =>
+ node.textContent?.includes('Other — tell us more'),
+ )!
+ await act(async () => label.querySelector<HTMLButtonElement>('[role=checkbox]')!.click())
+ const area = document.querySelector('textarea')!
+ expect(area.maxLength).toBe(1000)
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(area, ' 自定义原因 ')
+ area.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await click('Confirm cancellation')
+ expect(mocks.save).toHaveBeenCalledWith('review-org', { reasons: ['other'], intent: null, note: '自定义原因' })
+ })
+ it('ignores late cancellation results after organization switch', async () => {
+ let resolve!: () => void
+ mocks.cancel.mockImplementationOnce(
+ () =>
+ new Promise<void>((done) => {
+ resolve = done
+ }),
+ )
+ await click('Cancel subscription')
+ await chooseReason()
+ await click('Confirm cancellation')
+ mocks.org = 'other-org'
+ render()
+ await act(async () => {
+ current = { ...plan, cancelAtPeriodEnd: true }
+ resolve()
+ })
+ expect(mocks.save).not.toHaveBeenCalled()
+ expect(document.body.textContent).not.toContain('Cancellation confirmed')
+ expect(mocks.read).toHaveBeenCalledTimes(1)
+ })
+ it('hides the action for members and scheduled cancellation', () => {
+ render({ ...plan, cancelAtPeriodEnd: true })
+ expect(document.body.textContent).not.toContain('Cancel subscription')
+ mocks.role = 'member'
+ render(plan)
+ expect(document.body.textContent).not.toContain('Cancel subscription')
+ })
+})
diff --git a/apps/dashboard/src/components/billing/SubscriptionCancellation.tsx b/apps/dashboard/src/components/billing/SubscriptionCancellation.tsx
new file mode 100644
index 000000000..ea129fe69
--- /dev/null
+++ b/apps/dashboard/src/components/billing/SubscriptionCancellation.tsx
@@ -0,0 +1,425 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { createContext, useContext, useEffect, useRef, useState, type ReactNode } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
+import { useApi } from '@/hooks/useApi'
+import { queryKeys } from '@/hooks/queries/queryKeys'
+import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'
+import { format } from 'date-fns'
+import type { OrganizationPlan } from '@/billing-api'
+import type { CancellationFeedbackInput } from '@/api/apiClient'
+import { Button } from '@/components/ui/button'
+import { Checkbox } from '@/components/ui/checkbox'
+import { Dialog, DialogDescription, DialogTitle } from '@/components/ui/dialog'
+import { FormDialogBody, FormDialogContent, FormDialogFooter, FormDialogHeader } from '@/components/ui/form-dialog'
+import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
+import { Textarea } from '@/components/ui/textarea'
+import { Spinner } from '@/components/ui/spinner'
+import { useKeepPlanMutation } from '@/hooks/mutations/useKeepPlanMutation'
+import { useSelectedOrganization } from '@/hooks/useSelectedOrganization'
+
+const reasons = [
+ ['not_tried', 'I haven’t had time to try it'],
+ ['no_workload', 'No workloads to run right now'],
+ ['setup', 'Getting started was too difficult'],
+ ['missing_features', 'Missing features I need'],
+ ['reliability', 'Reliability or data concerns'],
+ ['performance', 'Performance or resources don’t fit'],
+ ['pricing', 'Pricing or billing doesn’t fit'],
+ ['limits', 'Plan limits got in the way'],
+ ['alternative', 'Using another service or self-hosting'],
+ ['completed', 'My project is complete'],
+ ['other', 'Other — tell us more'],
+]
+const intents = [
+ ['evaluate', 'Evaluate for a future project'],
+ ['one_off', 'Complete a one-time task or project'],
+ ['ongoing', 'Run ongoing apps, CI, or other workloads'],
+ ['explore', 'Explore without a specific task'],
+ ['unsure', 'Other / not sure'],
+]
+
+const CancellationContext = createContext<((plan: OrganizationPlan) => void) | null>(null)
+
+/** One controller survives tab switches and the current plan disappearing after cancellation. */
+export function SubscriptionCancellationProvider({ children }: { children: ReactNode }) {
+ const { selectedOrganization, authenticatedUserOrganizationMember } = useSelectedOrganization()
+ const owner = authenticatedUserOrganizationMember?.role === OrganizationUserRoleEnum.OWNER
+ if (!selectedOrganization || !owner) return <>{children}</>
+ return (
+ <CancellationController key={selectedOrganization.id} organizationId={selectedOrganization.id}>
+ {children}
+ </CancellationController>
+ )
+}
+
+function CancellationController({ organizationId, children }: { organizationId: string; children: ReactNode }) {
+ const { selectedOrganization } = useSelectedOrganization()
+ const api = useApi()
+ const { billingApi } = api
+ const queryClient = useQueryClient()
+ const [plan, setPlan] = useState<OrganizationPlan | null>(null)
+ const [open, setOpen] = useState(false)
+ const [selectedReasons, setReasons] = useState<string[]>([])
+ const [intent, setIntent] = useState('')
+ const [note, setNote] = useState('')
+ const [error, setError] = useState('')
+ const [pending, setPending] = useState(false)
+ const [unsaved, setUnsaved] = useState<CancellationFeedbackInput | null>(null)
+ const [saved, setSaved] = useState(false)
+ const mounted = useRef(true)
+ const busy = useRef(false)
+ const [attempted, setAttempted] = useState(false)
+ const [confirmation, setConfirmation] = useState('')
+ useEffect(() => {
+ mounted.current = true
+ return () => {
+ mounted.current = false
+ }
+ }, [])
+ const trial = plan?.trial?.conversionState === 'not_attempted'
+ const converting = plan?.trial && plan.trial.conversionState !== 'succeeded' && !trial
+ const ends = plan ? format(plan.cycleTo, 'MMM d, yyyy') : ''
+
+ async function refresh() {
+ const current = await billingApi.getOrganizationPlan(organizationId, 10_000)
+ queryClient.setQueryData(queryKeys.organization.plan(organizationId), current)
+ void queryClient.invalidateQueries({ queryKey: queryKeys.organization.detail(organizationId) })
+ void queryClient.invalidateQueries({ queryKey: queryKeys.organization.usage.overview(organizationId) })
+ void queryClient.invalidateQueries({ queryKey: queryKeys.billing.invoices(organizationId) })
+ return current
+ }
+ function canceled(current: OrganizationPlan) {
+ return current.cancelAtPeriodEnd || current.status === 'canceled'
+ }
+ function sameTerms(current: OrganizationPlan) {
+ return (
+ plan !== null &&
+ current.planId === plan.planId &&
+ current.cycleTo.getTime() === plan.cycleTo.getTime() &&
+ current.trial?.conversionState === plan.trial?.conversionState
+ )
+ }
+ async function complete() {
+ if (!mounted.current) return
+ const feedback = {
+ reasons: selectedReasons,
+ intent: intent || null,
+ note: selectedReasons.includes('other') ? note.trim() : '',
+ }
+ setConfirmation('Cancellation confirmed. Your plan shows the latest renewal status.')
+ setOpen(false)
+ setAttempted(false)
+ setUnsaved(null)
+ setSaved(false)
+ if (!feedback.reasons.length && !feedback.intent && !feedback.note) return
+ try {
+ await api.saveCancellationFeedback(organizationId, feedback)
+ if (mounted.current) setSaved(true)
+ } catch {
+ if (mounted.current) setUnsaved(feedback)
+ }
+ }
+ async function submit() {
+ if (busy.current || !plan) return
+ busy.current = true
+ setPending(true)
+ setError('')
+ try {
+ const current = await refresh()
+ if (!mounted.current) return
+ if (!current) throw new Error('Plan status unavailable')
+ if (!sameTerms(current)) {
+ setPlan(current)
+ setAttempted(false)
+ setError('Your plan changed. Review the updated details before confirming again.')
+ return
+ }
+ if (canceled(current)) {
+ await complete()
+ return
+ }
+ if (attempted) {
+ setAttempted(false)
+ setPlan(current)
+ setError('Renewal is still on. Review your plan and confirm again to cancel.')
+ return
+ }
+ setAttempted(true)
+ try {
+ await billingApi.downgradePlan(organizationId, null, 15_000)
+ } catch {
+ // A lost response can still mean success. Read state; never replay this POST automatically.
+ }
+ if (!mounted.current) return
+ const updated = await refresh()
+ if (!mounted.current) return
+ if (updated && sameTerms(updated) && canceled(updated)) await complete()
+ else setError('Cancellation could not be confirmed. Your answers are kept. Check status before trying again.')
+ } catch {
+ if (mounted.current)
+ setError('Cancellation could not be confirmed. Your answers are kept. Try checking the plan again.')
+ } finally {
+ busy.current = false
+ if (mounted.current) setPending(false)
+ }
+ }
+ async function retryFeedback() {
+ if (!unsaved || busy.current) return
+ busy.current = true
+ setPending(true)
+ try {
+ await api.saveCancellationFeedback(organizationId, unsaved)
+ if (mounted.current) {
+ setUnsaved(null)
+ setSaved(true)
+ }
+ } catch {
+ /* Keep the latest unaccepted feedback available for retry. */
+ } finally {
+ busy.current = false
+ if (mounted.current) setPending(false)
+ }
+ }
+ function start(current: OrganizationPlan) {
+ if (busy.current) return
+ if (attempted) {
+ setOpen(true)
+ return
+ }
+ setPlan(current)
+ setConfirmation('')
+ setReasons([])
+ setIntent('')
+ setNote('')
+ setError('')
+ setSaved(false)
+ setOpen(true)
+ }
+ return (
+ <CancellationContext.Provider value={start}>
+ {confirmation && (
+ <p role="status" className="page-container py-3 text-body">
+ {confirmation}
+ </p>
+ )}
+ {!open && attempted && (
+ <div role="alert" className="page-container py-3 text-body">
+ Cancellation has not been confirmed. Your answers are kept.{' '}
+ <Button variant="outline" onClick={() => setOpen(true)}>
+ Check cancellation
+ </Button>
+ </div>
+ )}
+ {(unsaved || saved) && (
+ <div role="status" className="page-container flex flex-wrap items-center justify-between gap-3 py-4">
+ <p className="text-body">
+ {unsaved
+ ? 'Cancellation confirmed. Your feedback wasn’t saved.'
+ : 'Your cancellation feedback has been saved.'}
+ </p>
+ {unsaved && (
+ <Button variant="outline" disabled={pending} onClick={retryFeedback}>
+ {pending && <Spinner />}Retry feedback
+ </Button>
+ )}
+ </div>
+ )}
+ {children}
+ {plan && (
+ <Dialog
+ open={open}
+ onOpenChange={(value) => {
+ if (!busy.current) setOpen(value)
+ }}
+ >
+ <FormDialogContent className="sm:max-w-[660px]" showCloseButton={!pending}>
+ <FormDialogHeader>
+ <DialogTitle>Cancel subscription?</DialogTitle>
+ <DialogDescription>Turn off automatic renewal for {selectedOrganization?.name}.</DialogDescription>
+ </FormDialogHeader>
+ <FormDialogBody className="space-y-5">
+ <dl className="space-y-3 bg-secondary px-4 py-4 text-body">
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">Current plan</dt>
+ <dd>{plan.planName}</dd>
+ </div>
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">{trial ? 'Trial access until' : 'Plan access until'}</dt>
+ <dd>{ends}</dd>
+ </div>
+ <div className="flex justify-between gap-4">
+ <dt className="text-muted-foreground">After cancellation</dt>
+ <dd>Automatic renewal off</dd>
+ </div>
+ </dl>
+ <p className="text-body">
+ {converting
+ ? 'Trial conversion is already in progress. A payment may already be processing. Canceling stops renewal; a completed conversion payment is handled by billing.'
+ : trial
+ ? `Your trial will not convert to a paid subscription. Trial access continues until ${ends}.`
+ : `Your ${plan.planName} quota and concurrency remain available until ${ends}. Your subscription will not renew.`}
+ </p>
+ {plan.pendingPlanId && (
+ <p className="text-body text-muted-foreground">This replaces your scheduled plan change.</p>
+ )}
+ <p className="text-body text-muted-foreground">
+ Usage charges are separate from subscription renewal. Canceling does not delete your workspace.
+ </p>
+ <section aria-labelledby="cancellation-feedback-heading" className="border-t border-border pt-4">
+ <h3 id="cancellation-feedback-heading" className="text-body font-medium">
+ Share feedback <span className="ml-2 font-normal text-muted-foreground">Optional</span>
+ </h3>
+ <p className="mt-3 text-body text-muted-foreground">
+ Help us understand your experience. You can cancel without answering.
+ </p>
+ <fieldset disabled={pending || attempted} className="mt-5">
+ <legend className="text-body font-medium">What made you decide to cancel?</legend>
+ <p className="mb-3 mt-1 text-meta text-muted-foreground">Optional · Select any that apply.</p>
+ <div className="grid gap-x-5 gap-y-3 sm:grid-cols-2">
+ {reasons.map(([id, label]) => (
+ <label key={id} className="flex cursor-pointer items-start gap-2 text-body">
+ <Checkbox
+ aria-label={label}
+ className="mt-0.5"
+ checked={selectedReasons.includes(id)}
+ onCheckedChange={(checked) =>
+ setReasons((previous) =>
+ checked ? [...previous, id] : previous.filter((value) => value !== id),
+ )
+ }
+ />
+ <span>{label}</span>
+ </label>
+ ))}
+ </div>
+ {selectedReasons.includes('other') && (
+ <label className="mt-4 block text-body">
+ Your reason <span className="text-muted-foreground">Optional</span>
+ <Textarea
+ className="mt-2"
+ maxLength={1000}
+ value={note}
+ onChange={(event) => setNote(event.target.value)}
+ placeholder="Tell us why you’re canceling."
+ />
+ <span className="text-meta text-muted-foreground">Up to 1,000 characters.</span>
+ </label>
+ )}
+ </fieldset>
+ <fieldset disabled={pending || attempted} className="mt-6">
+ <legend id="cancel-intent" className="text-body font-medium">
+ What did you originally plan to use BoxLite for?
+ </legend>
+ <p className="mb-3 mt-1 text-meta text-muted-foreground">Optional · Select one.</p>
+ <RadioGroup
+ aria-labelledby="cancel-intent"
+ value={intent}
+ onValueChange={setIntent}
+ disabled={pending || attempted}
+ >
+ {intents.map(([id, label]) => (
+ <label key={id} className="flex cursor-pointer items-center gap-2 text-body">
+ <RadioGroupItem value={id} aria-label={label} />
+ {label}
+ </label>
+ ))}
+ </RadioGroup>
+ <Button
+ variant="quiet"
+ size="sm"
+ className="mt-2"
+ onClick={() => setIntent('')}
+ disabled={pending || attempted}
+ >
+ Clear selection
+ </Button>
+ </fieldset>
+ </section>
+ {error && (
+ <p
+ role="alert"
+ className="border border-destructive/30 bg-destructive/5 p-3 text-body text-destructive"
+ >
+ {error}
+ </p>
+ )}
+ </FormDialogBody>
+ <FormDialogFooter className="flex-wrap">
+ <Button variant="outline" disabled={pending} onClick={() => setOpen(false)}>
+ {attempted ? 'Close' : 'Keep subscription'}
+ </Button>
+ <Button variant="destructive" disabled={pending} onClick={submit}>
+ {pending && <Spinner className="size-4" />}
+ {attempted ? 'Check status' : 'Confirm cancellation'}
+ </Button>
+ </FormDialogFooter>
+ </FormDialogContent>
+ </Dialog>
+ )}
+ </CancellationContext.Provider>
+ )
+}
+
+export function SubscriptionCancellationAction({
+ plan,
+ organizationId,
+ compact = false,
+}: {
+ plan: OrganizationPlan
+ organizationId: string
+ compact?: boolean
+}) {
+ const start = useContext(CancellationContext)
+ const keep = useKeepPlanMutation()
+ const [error, setError] = useState(false)
+ if (!start || plan.status === 'canceled') return null
+ const ends = format(plan.cycleTo, 'MMM d, yyyy')
+ const trial = plan.trial && plan.trial.conversionState !== 'succeeded'
+ if (plan.cancelAtPeriodEnd)
+ return compact ? (
+ <div className="space-y-2 text-body">
+ <p className="text-muted-foreground">Ends on {ends}</p>
+ {!trial && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={keep.isPending}
+ onClick={async () => {
+ setError(false)
+ try {
+ const url = await keep.mutateAsync({ organizationId, planId: plan.planId, kind: 'cancel' })
+ if (url) window.location.href = url
+ } catch {
+ setError(true)
+ }
+ }}
+ >
+ Keep subscription
+ </Button>
+ )}
+ {error && (
+ <p role="alert" className="text-destructive">
+ Couldn’t restore renewal. Try again.
+ </p>
+ )}
+ </div>
+ ) : null
+ return (
+ <div
+ className={
+ compact
+ ? 'text-body'
+ : 'flex flex-wrap items-center justify-between gap-3 border-t border-border px-[22px] py-4'
+ }
+ >
+ {!compact && (
+ <p className="text-body text-muted-foreground">
+ {trial ? 'Trial ends' : 'Renews'} {ends}. Manage automatic renewal here.
+ </p>
+ )}
+ <Button variant="quiet" className={compact ? 'h-auto min-h-7 px-0' : undefined} onClick={() => start(plan)}>
+ Cancel subscription
+ </Button>
+ </div>
+ )
+}
diff --git a/apps/dashboard/src/components/billing/planChange.test.ts b/apps/dashboard/src/components/billing/planChange.test.ts
index f313f60ab..869ffba6d 100644
--- a/apps/dashboard/src/components/billing/planChange.test.ts
+++ b/apps/dashboard/src/components/billing/planChange.test.ts
@@ -457,3 +457,17 @@ describe('queuedChange', () => {
expect(queuedChange({ ...LIVE_PRO, pendingPlanId: 'starter', status: 'canceled' })).toBeNull()
})
})
+
+describe('trial cancellation recovery', () => {
+ it('does not offer unsupported trial reactivation', () => {
+ const trial = {
+ startedAt: LIVE_PRO.cycleFrom,
+ endsAt: LIVE_PRO.cycleTo,
+ conversionState: 'not_attempted' as const,
+ conversionAmountCents: 14900,
+ currency: 'USD' as const,
+ }
+ const scheduled = scheduledChange({ plan: { ...LIVE_PRO, trial, cancelAtPeriodEnd: true }, catalog: CATALOG })
+ expect(scheduled?.keepLabel).toBeNull()
+ })
+})
diff --git a/apps/dashboard/src/components/billing/planChange.ts b/apps/dashboard/src/components/billing/planChange.ts
index 241e7681d..c090e584e 100644
--- a/apps/dashboard/src/components/billing/planChange.ts
+++ b/apps/dashboard/src/components/billing/planChange.ts
@@ -340,7 +340,7 @@ export interface ScheduledChange {
/** What the panel states. */
text: string
/** Label for the control that discards it — names the plan being kept. */
- keepLabel: string
+ keepLabel: string | null
/** Confirmation once it is discarded. Stated outright rather than derived from keepLabel. */
keptLabel: string
}
@@ -363,7 +363,12 @@ export function scheduledChange({
const keptLabel = `Staying on ${plan.planName}`
if (queued.kind === 'cancel') {
- return { kind: 'cancel', text: `Your subscription ends ${on} — ${keeps}`, keepLabel, keptLabel }
+ return {
+ kind: 'cancel',
+ text: `Your subscription ends ${on} — ${keeps}`,
+ keepLabel: plan.trial && plan.trial.conversionState !== 'succeeded' ? null : keepLabel,
+ keptLabel,
+ }
}
// An id is not user-facing copy. A queued plan the public catalog cannot
// name is a negotiated one; say what happens without inventing a name.
diff --git a/apps/dashboard/src/mocks/handlers.ts b/apps/dashboard/src/mocks/handlers.ts
index 7a364560c..363b19c0e 100644
--- a/apps/dashboard/src/mocks/handlers.ts
+++ b/apps/dashboard/src/mocks/handlers.ts
@@ -1,3 +1,4 @@
+import { subscriptionCancellationHandlers } from './subscription-cancellation-handlers'
/*
* Copyright 2025 Daytona Platforms Inc.
* Modified by BoxLite AI, 2025-2026
@@ -129,6 +130,7 @@ function planCatalogHandlers(catalog: () => Plan[]) {
}
export const handlers = [
+ ...subscriptionCancellationHandlers(API_URL, BILLING_API_URL),
...resourceStateHandlers(API_URL),
...ciHandlers(newUserPreview),
...sshHandlers,
diff --git a/apps/dashboard/src/mocks/subscription-cancellation-handlers.ts b/apps/dashboard/src/mocks/subscription-cancellation-handlers.ts
new file mode 100644
index 000000000..b4e9e06a3
--- /dev/null
+++ b/apps/dashboard/src/mocks/subscription-cancellation-handlers.ts
@@ -0,0 +1,84 @@
+/* Copyright 2026 BoxLite AI · SPDX-License-Identifier: AGPL-3.0 */
+import { http, HttpResponse } from 'msw'
+import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'
+import { MOCK_ORGANIZATION_MEMBER } from './fixtures'
+const parameters = new URLSearchParams(window.location.search)
+export const cancellationScenario = parameters.get('scenario') || 'paid'
+const enabled = parameters.get('preview') === 'subscription-cancel'
+let cancellationFailedOnce = false
+
+let canceled = cancellationScenario === 'scheduled'
+let feedbackFailedOnce = false
+const feedback = new Map<string, unknown>()
+
+export function subscriptionCancellationHandlers(apiUrl: string, billingUrl: string) {
+ if (!enabled) return []
+ return [
+ http.get(`${apiUrl}/organizations/:organizationId/users`, () =>
+ HttpResponse.json([
+ {
+ ...MOCK_ORGANIZATION_MEMBER,
+ role: cancellationScenario === 'readonly' ? OrganizationUserRoleEnum.MEMBER : OrganizationUserRoleEnum.OWNER,
+ },
+ ]),
+ ),
+ http.get(`${billingUrl}/organization/:organizationId/plan`, async () => {
+ if (cancellationScenario === 'none') return HttpResponse.json({})
+ const trial = cancellationScenario === 'trial'
+ const cycleTo = trial ? '2026-11-26T00:00:00Z' : '2026-12-23T00:00:00Z'
+ return HttpResponse.json({
+ plan: {
+ planId: 'pro',
+ planName: 'Pro',
+ status: 'active',
+ cycleFrom: '2026-11-23T00:00:00Z',
+ cycleTo,
+ includedQuotaCents: 25000,
+ quotaConsumedCents: 6250,
+ quotaRemainingCents: 18750,
+ ...(canceled ? { cancelAtPeriodEnd: true } : {}),
+ ...(trial
+ ? {
+ trial: {
+ startedAt: '2026-11-23T00:00:00Z',
+ endsAt: cycleTo,
+ conversionAmountCents: 14900,
+ currency: 'USD',
+ conversionState: 'not_attempted',
+ },
+ }
+ : {}),
+ },
+ })
+ }),
+ http.post(`${billingUrl}/organization/:organizationId/plan/downgrade`, async ({ request }) => {
+ if (['readonly', 'none'].includes(cancellationScenario)) return new HttpResponse(null, { status: 403 })
+ const body = (await request.json()) as { planId: string | null }
+ if (body.planId !== null) return new HttpResponse(null, { status: 400 })
+ if (parameters.get('failure') === 'cancel' && !cancellationFailedOnce) {
+ cancellationFailedOnce = true
+ return new HttpResponse(null, { status: 503 })
+ }
+ canceled = true
+ return new HttpResponse(null, { status: 204 })
+ }),
+ http.put(`${apiUrl}/organizations/:organizationId/cancellation-feedback`, async ({ request, params }) => {
+ if (cancellationScenario === 'readonly') return new HttpResponse(null, { status: 403 })
+ if (parameters.get('failure') === 'feedback' && !feedbackFailedOnce) {
+ feedbackFailedOnce = true
+ return new HttpResponse(null, { status: 503 })
+ }
+ feedback.set(String(params.organizationId), {
+ ...((await request.json()) as object),
+ submittedBy: MOCK_ORGANIZATION_MEMBER.userId,
+ submittedAt: new Date().toISOString(),
+ })
+ return new HttpResponse(null, { status: 204 })
+ }),
+ http.post(`${billingUrl}/organization/:organizationId/plan/upgrade`, async () => {
+ if (cancellationScenario === 'trial') return new HttpResponse(null, { status: 409 })
+ canceled = false
+ return new HttpResponse(null, { status: 204 })
+ }),
+ ]
+}
diff --git a/apps/dashboard/src/pages/Billing.test.tsx b/apps/dashboard/src/pages/Billing.test.tsx
index 0a16c10d2..ec904524e 100644
--- a/apps/dashboard/src/pages/Billing.test.tsx
+++ b/apps/dashboard/src/pages/Billing.test.tsx
@@ -10,6 +10,11 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import Billing from './Billing'
import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom'
+vi.mock('@/components/billing/SubscriptionCancellation', () => ({
+ SubscriptionCancellationProvider: ({ children }: { children: import('react').ReactNode }) => children,
+ SubscriptionCancellationAction: () => null,
+}))
+
vi.mock('@/hooks/useConfig', () => ({
useConfig: () => ({ billingApiUrl: 'https://billing.example.test' }),
}))
diff --git a/apps/dashboard/src/pages/Billing.trial.render.test.tsx b/apps/dashboard/src/pages/Billing.trial.render.test.tsx
index 048a0ea5d..3ea37c689 100644
--- a/apps/dashboard/src/pages/Billing.trial.render.test.tsx
+++ b/apps/dashboard/src/pages/Billing.trial.render.test.tsx
@@ -11,6 +11,11 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { OrganizationUserRoleEnum } from '@boxlite-ai/api-client'
import Billing from './Billing'
+vi.mock('@/components/billing/SubscriptionCancellation', () => ({
+ SubscriptionCancellationProvider: ({ children }: { children: import('react').ReactNode }) => children,
+ SubscriptionCancellationAction: () => null,
+}))
+
vi.mock('@/hooks/useConfig', () => ({
useConfig: () => ({ billingApiUrl: 'https://billing.example.test' }),
}))
diff --git a/apps/dashboard/src/pages/Billing.tsx b/apps/dashboard/src/pages/Billing.tsx
index efb02819b..130746695 100644
--- a/apps/dashboard/src/pages/Billing.tsx
+++ b/apps/dashboard/src/pages/Billing.tsx
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: AGPL-3.0
*/
+import { SubscriptionCancellationProvider } from '@/components/billing/SubscriptionCancellation'
import { TabIcon } from '@/components/ui/TabIcon'
import { BalanceLowBanner } from '@/components/billing/BalanceLowBanner'
import { BillingAlerts } from '@/components/billing/BillingAlerts'
@@ -110,75 +111,77 @@ function Billing() {
}
return (
- <Tabs value={tab} onValueChange={setTab} className="w-full gap-0">
- <div className="page-container">
- <div className="pt-6">
- <h1 className="resource-title">Billing</h1>
- <p className="mt-2 text-body leading-relaxed text-muted-foreground">
- Track resource usage, manage your plan, and top up your balance.
- </p>
- <div className="mt-4 w-full empty:hidden">
- <BalanceLowBanner onGoToWallet={() => setTab('wallet')} />
- </div>
- <div className="mt-5 flex items-center gap-3">
- <TabsList variant="underline" aria-label="Billing views" className="min-w-0 flex-1 gap-3 sm:gap-6">
- <TabsTrigger value="overview">
- <TabIcon name="overview" />
- Overview
- </TabsTrigger>
- <TabsTrigger value="plans">
- <TabIcon name="list" />
- Plans
- </TabsTrigger>
- <TabsTrigger value="usage">
- <TabIcon name="chart" />
- Usage
- </TabsTrigger>
- <TabsTrigger value="wallet">
- <TabIcon name="wallet" />
- Wallet
- </TabsTrigger>
- </TabsList>
- </div>
- </div>
- <TabsContent value="overview">
- <div className={TAB_PANE}>
- <div className="mb-8 flex flex-col gap-4 empty:hidden">
- <BillingAlerts />
+ <SubscriptionCancellationProvider>
+ <Tabs value={tab} onValueChange={setTab} className="w-full gap-0">
+ <div className="page-container">
+ <div className="pt-6">
+ <h1 className="resource-title">Billing</h1>
+ <p className="mt-2 text-body leading-relaxed text-muted-foreground">
+ Track resource usage, manage your plan, and top up your balance.
+ </p>
+ <div className="mt-4 w-full empty:hidden">
+ <BalanceLowBanner onGoToWallet={() => setTab('wallet')} />
+ </div>
+ <div className="mt-5 flex items-center gap-3">
+ <TabsList variant="underline" aria-label="Billing views" className="min-w-0 flex-1 gap-3 sm:gap-6">
+ <TabsTrigger value="overview">
+ <TabIcon name="overview" />
+ Overview
+ </TabsTrigger>
+ <TabsTrigger value="plans">
+ <TabIcon name="list" />
+ Plans
+ </TabsTrigger>
+ <TabsTrigger value="usage">
+ <TabIcon name="chart" />
+ Usage
+ </TabsTrigger>
+ <TabsTrigger value="wallet">
+ <TabIcon name="wallet" />
+ Wallet
+ </TabsTrigger>
+ </TabsList>
</div>
- <PlanSection onViewPlans={() => setTab('plans')} />
- </div>
- </TabsContent>
- <TabsContent value="plans">
- <div className={TAB_PANE}>
- <PlansSection />
- </div>
- </TabsContent>
- <TabsContent value="usage">
- <div className={TAB_PANE}>
- <UsageSection />
- </div>
- </TabsContent>
- <TabsContent value="wallet">
- <div className={TAB_PANE}>
- <WalletSection
- linkCouponCode={searchParams.get('code') ?? undefined}
- onCouponClaimAccepted={() =>
- // An accepted claim no longer needs its code in the URL.
- setSearchParams(
- (previous) => {
- const next = new URLSearchParams(previous)
- next.delete('code')
- return next
- },
- { replace: true },
- )
- }
- />
</div>
- </TabsContent>
- </div>
- </Tabs>
+ <TabsContent value="overview">
+ <div className={TAB_PANE}>
+ <div className="mb-8 flex flex-col gap-4 empty:hidden">
+ <BillingAlerts />
+ </div>
+ <PlanSection onViewPlans={() => setTab('plans')} />
+ </div>
+ </TabsContent>
+ <TabsContent value="plans">
+ <div className={TAB_PANE}>
+ <PlansSection />
+ </div>
+ </TabsContent>
+ <TabsContent value="usage">
+ <div className={TAB_PANE}>
+ <UsageSection />
+ </div>
+ </TabsContent>
+ <TabsContent value="wallet">
+ <div className={TAB_PANE}>
+ <WalletSection
+ linkCouponCode={searchParams.get('code') ?? undefined}
+ onCouponClaimAccepted={() =>
+ // An accepted claim no longer needs its code in the URL.
+ setSearchParams(
+ (previous) => {
+ const next = new URLSearchParams(previous)
+ next.delete('code')
+ return next
+ },
+ { replace: true },
+ )
+ }
+ />
+ </div>
+ </TabsContent>
+ </div>
+ </Tabs>
+ </SubscriptionCancellationProvider>
)
}