Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6540: retry stale seat purchase quotes (#7401)

Multica Evefbbe69757853
diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.json
index 1cb8c2bc0f..b96368942d 100644
--- a/packages/views/locales/en/billing.json
+++ b/packages/views/locales/en/billing.json
@@ -236,6 +236,7 @@
"preview_loading": "Updating estimate...",
"preview_unreadable": "The estimate could not be read. Change the seat count or retry.",
"preview_failed": "The estimate is temporarily unavailable. Retry in a moment.",
+ "capacity_out_of_sync": "The seat count in Stripe does not match the billing record. Contact support before retrying this purchase.",
"in_progress": "Another seat purchase is being processed. Wait for it to finish; contact support if it remains here.",
"purchase_unreadable": "The purchase response could not be read. Retry this quote; the same purchase request will be reused.",
"purchase_failed": "Seats could not be added. Retry with the same quote, or refresh if it has expired.",
diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.json
index a291d51b7c..0d7b22eb71 100644
--- a/packages/views/locales/ja/billing.json
+++ b/packages/views/locales/ja/billing.json
@@ -232,6 +232,7 @@
"preview_loading": "見積もりを更新中...",
"preview_unreadable": "見積もりを読み取れませんでした。席数を変更するか、再試行してください。",
"preview_failed": "見積もりは一時的に利用できません。しばらくしてから再試行してください。",
+ "capacity_out_of_sync": "Stripe の席数が請求記録と一致していません。再度購入する前にサポートへお問い合わせください。",
"in_progress": "別の席購入を処理中です。完了をお待ちください。長時間完了しない場合はサポートにお問い合わせください。",
"purchase_unreadable": "購入レスポンスを読み取れませんでした。この見積もりを再試行すると、同じ購入リクエストが再利用されます。",
"purchase_failed": "席を追加できませんでした。同じ見積もりで再試行するか、期限切れの場合は更新してください。",
diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.json
index 763b75c3ed..db4b2f4479 100644
--- a/packages/views/locales/ko/billing.json
+++ b/packages/views/locales/ko/billing.json
@@ -232,6 +232,7 @@
"preview_loading": "예상 금액 업데이트 중...",
"preview_unreadable": "예상 금액을 읽지 못했습니다. 좌석 수를 변경하거나 다시 시도하세요.",
"preview_failed": "예상 금액을 일시적으로 불러올 수 없습니다. 잠시 후 다시 시도하세요.",
+ "capacity_out_of_sync": "Stripe 좌석 수가 결제 기록과 일치하지 않습니다. 구매를 다시 시도하기 전에 지원팀에 문의하세요.",
"in_progress": "다른 좌석 구매가 처리 중입니다. 완료될 때까지 기다리세요. 오래 지속되면 지원팀에 문의하세요.",
"purchase_unreadable": "구매 응답을 읽지 못했습니다. 이 견적을 다시 시도하면 같은 구매 요청이 재사용됩니다.",
"purchase_failed": "좌석을 추가하지 못했습니다. 같은 견적으로 다시 시도하거나 만료된 경우 새로고침하세요.",
diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.json
index 7af3cba6b3..5d58397d7e 100644
--- a/packages/views/locales/zh-Hans/billing.json
+++ b/packages/views/locales/zh-Hans/billing.json
@@ -232,6 +232,7 @@
"preview_loading": "正在更新估算金额...",
"preview_unreadable": "无法读取估算结果。请修改席位数或重试。",
"preview_failed": "暂时无法获取估算金额,请稍后重试。",
+ "capacity_out_of_sync": "Stripe 席位数与计费记录不一致。再次购买前,请联系支持人员。",
"in_progress": "另一笔席位购买正在处理中。请等待其完成;若长时间未完成,请联系支持人员。",
"purchase_unreadable": "无法读取购买响应。请重试当前报价;系统会复用同一购买请求。",
"purchase_failed": "无法添加席位。可使用同一报价重试;报价过期时请刷新。",
diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsx
index eeda4822e1..143a00233f 100644
--- a/packages/views/settings/components/billing-tab.test.tsx
+++ b/packages/views/settings/components/billing-tab.test.tsx
@@ -285,6 +285,7 @@ describe("BillingTab", () => {
actualSeats: 3,
action: "none",
});
+ mocks.refetchSummary.mockResolvedValue({ data: mocks.summary });
mocks.previewSeats.mockResolvedValue({
currentSeats: 5,
additionalSeats: 1,
@@ -798,6 +799,198 @@ describe("BillingTab", () => {
await waitFor(() => expect(mocks.refetchSummary).toHaveBeenCalled());
});
+ it("refreshes and retries a preview after Stripe seat capacity changes", async () => {
+ const user = userEvent.setup();
+ let resolveSummaryRefresh!: (value: { data: typeof mocks.summary }) => void;
+ Object.assign(mocks.entitlements, {
+ plan: "pro",
+ status: "active",
+ issueWindow: null,
+ autopilotRuns: null,
+ });
+ Object.assign(mocks.summary, {
+ actualSeats: 4,
+ usedSeats: 4,
+ billedSeats: 5,
+ reservedSeats: 0,
+ purchaseVersion: 9,
+ hasStripeCustomer: true,
+ });
+ mocks.refetchSummary.mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveSummaryRefresh = resolve;
+ }),
+ );
+ mocks.previewSeats
+ .mockRejectedValueOnce(
+ new ApiError("conflict", 409, "Conflict", {
+ code: "seat_capacity_changed",
+ }),
+ )
+ .mockResolvedValueOnce({
+ currentSeats: 4,
+ additionalSeats: 1,
+ resultingSeats: 5,
+ purchaseVersion: 10,
+ currency: "usd",
+ prorationAmount: 250,
+ nextInvoiceAmount: 5000,
+ quotedAt: "2030-01-01T00:00:00Z",
+ });
+
+ renderWithI18n(<BillingTab />);
+ await user.click(screen.getByRole("button", { name: "Add seats" }));
+
+ await waitFor(() => expect(mocks.refetchSummary).toHaveBeenCalledTimes(1));
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "Updating estimate...",
+ );
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+
+ await act(async () => {
+ Object.assign(mocks.summary, {
+ billedSeats: 4,
+ purchaseVersion: 10,
+ });
+ resolveSummaryRefresh({ data: mocks.summary });
+ });
+
+ await waitFor(
+ () => expect(mocks.previewSeats).toHaveBeenCalledTimes(2),
+ { timeout: 3_000 },
+ );
+ expect(await screen.findByText("$2.50")).toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ "The estimate is temporarily unavailable. Retry in a moment.",
+ ),
+ ).not.toBeInTheDocument();
+ });
+
+ it("does not retry when the refreshed seat summary is unchanged", async () => {
+ const user = userEvent.setup();
+ Object.assign(mocks.entitlements, {
+ plan: "pro",
+ status: "active",
+ issueWindow: null,
+ autopilotRuns: null,
+ });
+ Object.assign(mocks.summary, {
+ actualSeats: 4,
+ usedSeats: 4,
+ billedSeats: 5,
+ reservedSeats: 0,
+ purchaseVersion: 9,
+ hasStripeCustomer: true,
+ });
+ mocks.previewSeats.mockRejectedValueOnce(
+ new ApiError("conflict", 409, "Conflict", {
+ code: "seat_capacity_changed",
+ }),
+ );
+
+ renderWithI18n(<BillingTab />);
+ await user.click(screen.getByRole("button", { name: "Add seats" }));
+
+ expect(
+ await screen.findByText(
+ "The seat count in Stripe does not match the billing record. Contact support before retrying this purchase.",
+ {},
+ { timeout: 3_000 },
+ ),
+ ).toBeInTheDocument();
+ expect(mocks.previewSeats).toHaveBeenCalledTimes(1);
+ expect(mocks.refetchSummary).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps a summary refresh failure distinct from a seat mismatch", async () => {
+ const user = userEvent.setup();
+ Object.assign(mocks.entitlements, {
+ plan: "pro",
+ status: "active",
+ issueWindow: null,
+ autopilotRuns: null,
+ });
+ Object.assign(mocks.summary, {
+ actualSeats: 4,
+ usedSeats: 4,
+ billedSeats: 5,
+ reservedSeats: 0,
+ purchaseVersion: 9,
+ hasStripeCustomer: true,
+ });
+ mocks.refetchSummary.mockResolvedValueOnce({
+ data: mocks.summary,
+ isError: true,
+ });
+ mocks.previewSeats.mockRejectedValueOnce(
+ new ApiError("conflict", 409, "Conflict", {
+ code: "seat_capacity_changed",
+ }),
+ );
+
+ renderWithI18n(<BillingTab />);
+ await user.click(screen.getByRole("button", { name: "Add seats" }));
+
+ expect(
+ await screen.findByText(
+ "The estimate is temporarily unavailable. Retry in a moment.",
+ {},
+ { timeout: 3_000 },
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(
+ "The seat count in Stripe does not match the billing record. Contact support before retrying this purchase.",
+ ),
+ ).not.toBeInTheDocument();
+ expect(mocks.previewSeats).toHaveBeenCalledTimes(1);
+ expect(mocks.refetchSummary).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not refresh again when the retried preview still conflicts", async () => {
+ const user = userEvent.setup();
+ Object.assign(mocks.entitlements, {
+ plan: "pro",
+ status: "active",
+ issueWindow: null,
+ autopilotRuns: null,
+ });
+ Object.assign(mocks.summary, {
+ actualSeats: 4,
+ usedSeats: 4,
+ billedSeats: 5,
+ reservedSeats: 0,
+ purchaseVersion: 9,
+ hasStripeCustomer: true,
+ });
+ mocks.refetchSummary.mockImplementationOnce(async () => {
+ Object.assign(mocks.summary, {
+ billedSeats: 4,
+ purchaseVersion: 10,
+ });
+ return { data: mocks.summary };
+ });
+ mocks.previewSeats.mockRejectedValue(
+ new ApiError("conflict", 409, "Conflict", {
+ code: "seat_capacity_changed",
+ }),
+ );
+
+ renderWithI18n(<BillingTab />);
+ await user.click(screen.getByRole("button", { name: "Add seats" }));
+
+ expect(
+ await screen.findByText(
+ "The seat count in Stripe does not match the billing record. Contact support before retrying this purchase.",
+ {},
+ { timeout: 3_000 },
+ ),
+ ).toBeInTheDocument();
+ expect(mocks.previewSeats).toHaveBeenCalledTimes(2);
+ expect(mocks.refetchSummary).toHaveBeenCalledTimes(1);
+ });
+
it.each([
[
"seat_quote_changed",
diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsx
index a0da05a4b3..a7b866e397 100644
--- a/packages/views/settings/components/billing-tab.tsx
+++ b/packages/views/settings/components/billing-tab.tsx
@@ -273,6 +273,7 @@ function BillingTabContent() {
const [seatPreview, setSeatPreview] =
useState<WorkspaceSeatPurchasePreview | null>(null);
const [seatPreviewRevision, setSeatPreviewRevision] = useState(0);
+ const [seatPreviewRefreshing, setSeatPreviewRefreshing] = useState(false);
const [seatPurchaseError, setSeatPurchaseError] = useState<string | null>(
null,
);
@@ -298,6 +299,10 @@ function BillingTabContent() {
request: PurchaseWorkspaceSeatsRequest;
} | null>(null);
const seatPreviewInputRef = useRef("");
+ const seatPreviewCapacityRetryRef = useRef<{
+ inputKey: string;
+ attempts: number;
+ } | null>(null);
const consumedCallbackKeyRef = useRef<string | null>(null);
useEffect(() => {
@@ -305,9 +310,11 @@ function BillingTabContent() {
portalIntentKeyRef.current = null;
seatPurchaseIntentRef.current = null;
seatPreviewInputRef.current = "";
+ seatPreviewCapacityRetryRef.current = null;
setSeatPurchaseOpen(false);
setSeatPreview(null);
setSeatPreviewRevision(0);
+ setSeatPreviewRefreshing(false);
setSeatPurchaseError(null);
setSeatPurchasePollingTimedOut(false);
setPortalUnavailable(false);
@@ -419,7 +426,14 @@ function BillingTabContent() {
const additionalSeats = /^\d+$/.test(value) ? Number(value) : 0;
const currentSeats = summaryQuery.data?.billedSeats ?? null;
const purchaseVersion = summaryQuery.data?.purchaseVersion ?? null;
- const requestKey = `${wsId}:${value}:${currentSeats ?? ""}:${purchaseVersion ?? ""}:${seatPreviewRevision}`;
+ const retryInputKey = `${wsId}:${value}`;
+ if (seatPreviewCapacityRetryRef.current?.inputKey !== retryInputKey) {
+ seatPreviewCapacityRetryRef.current = {
+ inputKey: retryInputKey,
+ attempts: 0,
+ };
+ }
+ const requestKey = `${retryInputKey}:${currentSeats ?? ""}:${purchaseVersion ?? ""}:${seatPreviewRevision}`;
seatPreviewInputRef.current = requestKey;
const intent = seatPurchaseIntentRef.current;
if (
@@ -429,6 +443,7 @@ function BillingTabContent() {
intent.request.expectedPurchaseVersion === purchaseVersion
) {
setSeatPreview(intent.preview);
+ setSeatPreviewRefreshing(false);
setSeatPurchaseError(null);
return;
}
@@ -441,6 +456,15 @@ function BillingTabContent() {
purchaseVersion === null ||
currentSeats + additionalSeats > 10_000
) {
+ if (
+ seatPreviewCapacityRetryRef.current?.inputKey === retryInputKey &&
+ seatPreviewCapacityRetryRef.current.attempts > 0
+ ) {
+ setSeatPurchaseError(
+ t(($) => $.workspace.seat_purchase.preview_failed),
+ );
+ }
+ setSeatPreviewRefreshing(false);
return;
}
@@ -455,20 +479,73 @@ function BillingTabContent() {
preview.purchaseVersion !== purchaseVersion ||
preview.resultingSeats !== currentSeats + additionalSeats
) {
+ setSeatPreviewRefreshing(false);
setSeatPurchaseError(
t(($) => $.workspace.seat_purchase.preview_unreadable),
);
return;
}
+ setSeatPreviewRefreshing(false);
setSeatPreview(preview);
setSeatPurchaseError(null);
})
- .catch((error: unknown) => {
+ .catch(async (error: unknown) => {
if (seatPreviewInputRef.current !== requestKey) return;
+ const previewErrorCode =
+ error instanceof ApiError && error.status === 409
+ ? errorCode(error)
+ : null;
+ if (previewErrorCode === "seat_capacity_changed") {
+ const retry = seatPreviewCapacityRetryRef.current;
+ if (retry?.inputKey !== retryInputKey || retry.attempts >= 1) {
+ setSeatPreviewRefreshing(false);
+ setSeatPurchaseError(
+ t(($) => $.workspace.seat_purchase.capacity_out_of_sync),
+ );
+ return;
+ }
+ retry.attempts += 1;
+ setSeatPreviewRefreshing(true);
+ setSeatPurchaseError(null);
+ try {
+ const refreshed = await refetchSummary();
+ if (seatPreviewInputRef.current !== requestKey) return;
+ if (refreshed.isError === true) {
+ setSeatPreviewRefreshing(false);
+ setSeatPurchaseError(
+ t(($) => $.workspace.seat_purchase.preview_failed),
+ );
+ return;
+ }
+ const refreshedSeats = refreshed.data?.billedSeats ?? null;
+ const refreshedVersion =
+ refreshed.data?.purchaseVersion ?? null;
+ if (
+ refreshedSeats === currentSeats &&
+ refreshedVersion === purchaseVersion
+ ) {
+ setSeatPreviewRefreshing(false);
+ setSeatPurchaseError(
+ t(($) => $.workspace.seat_purchase.capacity_out_of_sync),
+ );
+ return;
+ }
+ } catch {
+ if (seatPreviewInputRef.current === requestKey) {
+ setSeatPreviewRefreshing(false);
+ setSeatPurchaseError(
+ t(($) => $.workspace.seat_purchase.preview_failed),
+ );
+ }
+ return;
+ }
+ if (seatPreviewInputRef.current !== requestKey) return;
+ setSeatPreviewRevision((revision) => revision + 1);
+ return;
+ }
+ setSeatPreviewRefreshing(false);
setSeatPurchaseError(
- error instanceof ApiError &&
- error.status === 409 &&
- errorCode(error) === "seat_purchase_in_progress"
+ previewErrorCode === "seat_purchase_in_progress"
? t(($) => $.workspace.seat_purchase.in_progress)
: t(($) => $.workspace.seat_purchase.preview_failed),
);
@@ -478,6 +555,7 @@ function BillingTabContent() {
}, [
additionalSeatsInput,
previewSeatPurchase,
+ refetchSummary,
seatPurchaseOpen,
seatPreviewRevision,
summaryQuery.data?.billedSeats,
@@ -742,7 +820,12 @@ function BillingTabContent() {
const handleSeatPurchaseOpenChange = (open: boolean) => {
if (!open && purchaseSeatsMutation.isPending) return;
setSeatPurchaseOpen(open);
- if (!open) return;
+ seatPreviewCapacityRetryRef.current = null;
+ setSeatPreviewRefreshing(false);
+ if (!open) {
+ seatPreviewInputRef.current = "";
+ return;
+ }
setSeatPurchaseError(null);
const intent = seatPurchaseIntentRef.current;
if (intent?.wsId === wsId) {
@@ -1613,6 +1696,8 @@ function BillingTabContent() {
value={additionalSeatsInput}
disabled={purchaseSeatsMutation.isPending}
onChange={(event) => {
+ seatPreviewCapacityRetryRef.current = null;
+ setSeatPreviewRefreshing(false);
setAdditionalSeatsInput(event.currentTarget.value);
setSeatPurchaseError(null);
}}
@@ -1621,7 +1706,8 @@ function BillingTabContent() {
{t(($) => $.workspace.seat_purchase.additional_hint)}
</p>
</div>
- {previewSeatPurchaseMutation.isPending ? (
+ {previewSeatPurchaseMutation.isPending ||
+ seatPreviewRefreshing ? (
<div
className="flex items-center gap-2 text-body text-muted-foreground"
role="status"
@@ -1693,6 +1779,7 @@ function BillingTabContent() {
formattedSeatProration === null ||
formattedNextSeatInvoice === null ||
previewSeatPurchaseMutation.isPending ||
+ seatPreviewRefreshing ||
purchaseSeatsMutation.isPending
}
onClick={() => void handleSeatPurchase()}