Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9418 refactor(billing): remove the issue count limit and the billing test page (#10808)
Multica Eve1ed474c9716e
diff --git a/apps/web/app/[workspaceSlug]/(dashboard)/billing/page.tsx b/apps/web/app/[workspaceSlug]/(dashboard)/billing/page.tsxdeleted file mode 100644index 6978bd042a..0000000000--- a/apps/web/app/[workspaceSlug]/(dashboard)/billing/page.tsx+++ /dev/null@@ -1,10 +0,0 @@-import { BillingTestPage } from "@multica/views/billing";--// Account-level test page for the cloud-billing API surface. Despite-// living under [workspaceSlug] — that's where the dashboard layout-// requires every page to sit — none of the data here is workspace--// scoped. The slug just keeps the route inside the authenticated-// shell.-export default function BillingRoute() {- return <BillingTestPage />;-}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex c7dce0c8c2..425794853e 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -263,7 +263,6 @@ import type {BillingCheckoutSessionStatus,CreateBillingPortalSessionResponse,WorkspaceSubscriptionSummary,- IssueLimitUsage,WorkspaceSubscriptionPrices,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,@@ -419,7 +418,6 @@ import {BillingCheckoutSessionStatusSchema,CreateBillingPortalSessionResponseSchema,WorkspaceSubscriptionSummarySchema,- IssueLimitUsageSchema,BatchUpdateIssuesResponseSchema,UNCONFIRMED_BATCH_UPDATE,WorkspaceSubscriptionPricesSchema,@@ -1816,17 +1814,6 @@ export class ApiClient {);}- async getIssueLimitUsage(): Promise<IssueLimitUsage | null> {- const raw = await this.fetch<unknown>("/api/issues/limit-usage");- if (raw == null) return null;- return parseWithFallback<IssueLimitUsage | null>(- raw,- IssueLimitUsageSchema,- null,- { endpoint: "GET /api/issues/limit-usage" },- );- }-async deleteIssue(id: string): Promise<void> {await this.fetch(`/api/issues/${id}`, { method: "DELETE" });}diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex 6e9b57777d..af6d609498 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -1553,6 +1553,7 @@ describe("workspace subscription contract", () => {status: "active",seats: 3,limits: {+ // Retired limit Cloud may still send; the client ignores it.issue_count: { mode: "unlimited" },autopilot_runs: { mode: "unlimited" },},@@ -1561,28 +1562,6 @@ describe("workspace subscription contract", () => {version: 7,};- it("maps limited issue usage and accepts a no-content unlimited response", async () => {- stubFetchJson({- used: 11,- limit: 17,- });- const client = new ApiClient("https://api.example.test");-- await expect(client.getIssueLimitUsage()).resolves.toEqual({- used: 11,- limit: 17,- });-- stubFetchJson({ used: 11 });- await expect(client.getIssueLimitUsage()).resolves.toBeNull();-- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue(new Response(null, { status: 204 })),- );- await expect(client.getIssueLimitUsage()).resolves.toBeNull();- });-it("maps a full summary to camelCase without inventing values", async () => {stubFetchJson({entitlement,diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex fa0f0c939e..0948b4273f 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -37,7 +37,6 @@ import type {CreateBillingPortalSessionResponse,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,- IssueLimitUsage,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPrices,CreateWorkspaceSubscriptionCheckoutResponse,@@ -3589,7 +3588,7 @@ const WorkspaceEntitlementLimitSchema = zz.object({ mode: z.literal("unlimited") }).loose(),]).transform(- (value): WorkspaceSubscriptionEntitlements["limits"]["issueCount"] =>+ (value): WorkspaceSubscriptionEntitlements["limits"]["autopilotRuns"] =>value.mode === "limited"? { mode: "limited", limit: value.limit }: { mode: "unlimited", limit: null },@@ -3606,7 +3605,6 @@ export const WorkspaceSubscriptionEntitlementsSchema = zseats: z.number().int().nonnegative(),limits: z.object({- issue_count: WorkspaceEntitlementLimitSchema,autopilot_runs: WorkspaceEntitlementLimitSchema,}).loose(),@@ -3622,7 +3620,6 @@ export const WorkspaceSubscriptionEntitlementsSchema = zstatus: value.status,seats: value.seats,limits: {- issueCount: value.limits.issue_count,autopilotRuns: value.limits.autopilot_runs,},currentPeriodEnd: value.current_period_end ?? null,@@ -3754,19 +3751,6 @@ export const BatchUpdateIssuesResponseSchema = z/** A batch response that failed validation: whatever was written is unknown. */export const UNCONFIRMED_BATCH_UPDATE: BatchUpdateIssuesResponse = { updated: 0, unconfirmed: true };-export const IssueLimitUsageSchema = z- .object({- used: z.number().int().nonnegative(),- limit: z.number().int().positive(),- })- .loose()- .transform(- (value): IssueLimitUsage => ({- used: value.used,- limit: value.limit,- }),- );-const WorkspaceSubscriptionPriceSchema = (expected: "month" | "year",) =>diff --git a/packages/core/billing/workspace-subscription-queries.ts b/packages/core/billing/workspace-subscription-queries.tsindex 15e4a8d4f1..de4ed3efd6 100644--- a/packages/core/billing/workspace-subscription-queries.ts+++ b/packages/core/billing/workspace-subscription-queries.ts@@ -19,8 +19,6 @@ export const workspaceSubscriptionKeys = {[...workspaceSubscriptionKeys.all(wsId), "summary"] as const,prices: (wsId: string) =>[...workspaceSubscriptionKeys.all(wsId), "prices"] as const,- issueLimitUsage: (wsId: string) =>- [...workspaceSubscriptionKeys.all(wsId), "issue-limit-usage"] as const,};/**@@ -39,16 +37,6 @@ export function workspaceSubscriptionSummaryOptions(wsId: string) {});}-export function issueLimitUsageOptions(wsId: string) {- return queryOptions({- queryKey: workspaceSubscriptionKeys.issueLimitUsage(wsId),- queryFn: () => api.getIssueLimitUsage(),- enabled: wsId.length > 0,- staleTime: 30 * 1000,- refetchOnWindowFocus: true,- });-}-/*** A validated price snapshot is stable deployment configuration, but a null* parse fallback is not a snapshot. Keeping null fresh made one transientdiff --git a/packages/core/modals/index.ts b/packages/core/modals/index.tsindex 69c6261e94..a530f670d0 100644--- a/packages/core/modals/index.ts+++ b/packages/core/modals/index.ts@@ -1,2 +1,2 @@export { useModalStore } from "./store";-export type { IssueLimitRecoveryReason } from "./store";+export type { LimitRecoveryReason } from "./store";diff --git a/packages/core/modals/store.ts b/packages/core/modals/store.tsindex aea7f9b8bb..7c31c64d1f 100644--- a/packages/core/modals/store.ts+++ b/packages/core/modals/store.ts@@ -19,37 +19,32 @@ type ModalType =| "issue-workflow-handoff"| null;-export type IssueLimitRecoveryReason = "issue_limit" | "autopilot_quota";+// Each reason is a Cloud-enforced limit whose recovery dialog offers billing+// actions. Add a reason here when a new limit gets its own recovery copy.+export type LimitRecoveryReason = "autopilot_quota";interface ModalStore {modal: ModalType;data: Record<string, unknown> | null;- issueLimitRecoveryWorkspaceId: string | null;- issueLimitRecoveryReason: IssueLimitRecoveryReason;+ limitRecoveryWorkspaceId: string | null;+ limitRecoveryReason: LimitRecoveryReason;open: (modal: NonNullable<ModalType>, data?: Record<string, unknown> | null) => void;close: () => void;- showIssueLimitRecovery: (- workspaceId: string,- reason?: IssueLimitRecoveryReason,- ) => void;- dismissIssueLimitRecovery: () => void;+ showLimitRecovery: (workspaceId: string, reason: LimitRecoveryReason) => void;+ dismissLimitRecovery: () => void;}export const useModalStore = create<ModalStore>((set) => ({modal: null,data: null,- issueLimitRecoveryWorkspaceId: null,- issueLimitRecoveryReason: "issue_limit",+ limitRecoveryWorkspaceId: null,+ limitRecoveryReason: "autopilot_quota",open: (modal, data = null) => set({ modal, data }),close: () => set({ modal: null, data: null }),- showIssueLimitRecovery: (workspaceId, reason = "issue_limit") =>+ showLimitRecovery: (workspaceId, reason) =>set({- issueLimitRecoveryWorkspaceId: workspaceId,- issueLimitRecoveryReason: reason,- }),- dismissIssueLimitRecovery: () =>- set({- issueLimitRecoveryWorkspaceId: null,- issueLimitRecoveryReason: "issue_limit",+ limitRecoveryWorkspaceId: workspaceId,+ limitRecoveryReason: reason,}),+ dismissLimitRecovery: () => set({ limitRecoveryWorkspaceId: null }),}));diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex a32c58ee81..c236eddae2 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -209,7 +209,6 @@ export interface WorkspaceSubscriptionEntitlements {status: string;seats: number;limits: {- issueCount: WorkspaceEntitlementLimit;autopilotRuns: WorkspaceEntitlementLimit;};currentPeriodEnd: string | null;@@ -241,11 +240,6 @@ export interface WorkspaceSubscriptionSummary {};}-export interface IssueLimitUsage {- used: number;- limit: number;-}-export interface WorkspaceSeatCapacity {purchased: number;used: number;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 330f33642c..94cf0b2341 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -410,7 +410,6 @@ export type {WorkspaceEntitlementLimit,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,- IssueLimitUsage,WorkspaceSeatCapacity,WorkspaceSeatPurchaseSummary,WorkspaceSubscriptionPrice,diff --git a/packages/views/autopilots/components/run-now-toast.test.ts b/packages/views/autopilots/components/run-now-toast.test.tsindex 87fde1c2f5..a7deb20d69 100644--- a/packages/views/autopilots/components/run-now-toast.test.ts+++ b/packages/views/autopilots/components/run-now-toast.test.ts@@ -35,9 +35,6 @@ describe("runNowBlockedKey", () => {expect(runNowBlockedKey("attribution_blocked")).toBe("run_blocked_attribution");expect(runNowBlockedKey("already_active")).toBe("run_blocked_already_active");expect(runNowBlockedKey("quota_exceeded")).toBe("run_blocked_quota_exceeded");- expect(runNowBlockedKey("issue_limit_reached")).toBe(- "run_blocked_issue_limit_reached",- );});it("maps runtime_access_denied to its dedicated key (PUCK-89)", () => {diff --git a/packages/views/autopilots/components/run-now-toast.ts b/packages/views/autopilots/components/run-now-toast.tsindex 7b60ebda03..335200e2bd 100644--- a/packages/views/autopilots/components/run-now-toast.ts+++ b/packages/views/autopilots/components/run-now-toast.ts@@ -38,7 +38,6 @@ export type RunNowBlockedKey =| "run_blocked_attribution"| "run_blocked_already_active"| "run_blocked_quota_exceeded"- | "run_blocked_issue_limit_reached"| "run_blocked_generic";export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedKey {@@ -63,8 +62,6 @@ export function runNowBlockedKey(reasonCode: string | undefined): RunNowBlockedKreturn "run_blocked_already_active";case "quota_exceeded":return "run_blocked_quota_exceeded";- case "issue_limit_reached":- return "run_blocked_issue_limit_reached";default:return "run_blocked_generic";}diff --git a/packages/views/billing/billing-test-page.tsx b/packages/views/billing/billing-test-page.tsxdeleted file mode 100644index 1ee802f02d..0000000000--- a/packages/views/billing/billing-test-page.tsx+++ /dev/null@@ -1,743 +0,0 @@-"use client";--// Test-quality billing page. Stuffs every /api/cloud-billing/* surface-// onto a single screen so we can verify the proxy + Stripe flow-// end-to-end without a designed UI. Sections:-//-// 1. Balance card-// 2. Stripe-success banner (visible only when the URL carries a-// ?session_id=... — the user just came back from Stripe Checkout-// and we poll the upstream until the topup is terminal).-// 3. Buy section: server-authoritative price tier buttons that POST-// a checkout-session and redirect.window.location.href = url.-// 4. Billing Portal button.-// 5. Three lists: transactions / batches / topups.-//-// Anything past "make the API talk to Stripe and surface results" is-// out of scope here on purpose — when the real billing UI ships it-// will live elsewhere and this whole page can be deleted. Strings-// are still routed through useT() so the package-wide-// i18next/no-literal-string lint rule passes; the namespace is-// `billing` and the en/zh-Hans bundles live alongside the other-// namespaces. When the real UI lands, both the namespace and this-// file get deleted together.--import { useEffect, useState } from "react";-import { useQuery } from "@tanstack/react-query";-import { Loader2, RefreshCw, ExternalLink } from "@multica/ui/icons";-import { toast } from "sonner";-import {- billingBalanceOptions,- billingBatchesOptions,- billingCheckoutSessionOptions,- billingPriceTiersOptions,- billingTopupsOptions,- billingTransactionsOptions,- useCreateCloudBillingCheckoutSession,- useCreateCloudBillingPortalSession,- useInvalidateBillingDataAfterCredit,-} from "@multica/core/billing";-import type {- BillingBatch,- BillingPriceTier,- BillingTopup,- BillingTransaction,-} from "@multica/core/types";-import { Button } from "@multica/ui/components/ui/button";-import {- Card,- CardContent,- CardDescription,- CardHeader,- CardTitle,-} from "@multica/ui/components/ui/card";-import { useLocale, useT } from "../i18n";-import { useNavigation } from "../navigation";--// 1 credit = 1_000_000 micro-credit; cents → dollars factor for the-// Stripe-side display column. Documented at the top of the cloud-// billing.md so we don't sprinkle magic numbers through the UI.-const MICRO_PER_CREDIT = 1_000_000;-const CENTS_PER_DOLLAR = 100;--export function BillingTestPage() {- const { t } = useT("billing");- const { searchParams, replace, pathname } = useNavigation();-- // The Stripe success URL on the cloud side has the literal- // {CHECKOUT_SESSION_ID} placeholder which Stripe substitutes before- // redirecting the browser. So when we land here, the param is real.- const sessionId = searchParams.get("session_id") ?? "";-- return (- <div className="space-y-6 p-6">- <header>- <h1 className="text-title-lg font-semibold">{t(($) => $.title)}</h1>- <p className="mt-1 text-body text-muted-foreground">- {t(($) => $.subtitle)}- </p>- </header>-- {sessionId && (- <CheckoutSessionStatusBanner- sessionId={sessionId}- onDismiss={() => {- // After we've shown the terminal status we strip- // session_id from the URL so a refresh doesn't re-poll a- // stale order. `replace` keeps the browser at the same- // pathname without adding history.- replace(pathname);- }}- />- )}-- <BalanceCard />-- <BuyAndPortalSection />-- <TransactionsCard />-- <BatchesCard />-- <TopupsCard />- </div>- );-}--// ─── Stripe-success banner ───────────────────────────────────────────--// Polls /checkout-sessions/{id} every 2s until the order reaches a-// terminal state. Mounted only when ?session_id is in the URL.-function CheckoutSessionStatusBanner({- sessionId,- onDismiss,-}: {- sessionId: string;- onDismiss: () => void;-}) {- const { t } = useT("billing");- const locale = useLocale();- const { data, isLoading, isError, error } = useQuery(- billingCheckoutSessionOptions(sessionId),- );-- const status = data?.status ?? (isLoading ? "loading" : "");- const terminal =- status === "credited" || status === "failed" || status === "canceled";-- // When the polling reaches a terminal state, the rest of the page- // (balance, transactions, batches, topups) is still showing the- // pre-checkout snapshot. Without this effect the user would see- // "Final status: credited" up here while the balance card still- // displays the old number — the only signal that things were stale- // would be a manual refresh click. Invalidate the dependent- // queries so they re-fetch in the background.- //- // Dep list `terminal`: terminal only flips from false→true once- // per session-id, so the invalidation fires exactly once. If the- // caller mounts this banner with a session that is already in a- // terminal state (e.g. user revisits the success URL after closing- // and reopening the tab), terminal flips false→true on the first- // data load and we still re-fetch — which is what we want, because- // the cached snapshot is just as stale in that case.- const invalidateBillingDataAfterCredit = useInvalidateBillingDataAfterCredit();- useEffect(() => {- if (terminal) invalidateBillingDataAfterCredit();- }, [terminal, invalidateBillingDataAfterCredit]);-- return (- <Card className="border-primary/40 bg-primary/5">- <CardHeader>- <CardTitle className="text-body">- {t(($) => $.checkout.session_label, { prefix: sessionId.slice(0, 16) })}- </CardTitle>- <CardDescription className="text-caption">- {isLoading- ? t(($) => $.checkout.loading)- : isError- ? t(($) => $.checkout.fetch_failed, {- error:- error instanceof Error- ? error.message- : t(($) => $.checkout.fetch_failed_unknown),- })- : terminal- ? t(($) => $.checkout.final_status, { status })- : t(($) => $.checkout.polling_status, {- status: status || t(($) => $.checkout.status_unknown),- })}- </CardDescription>- </CardHeader>- {data && (- <CardContent className="text-caption">- <dl className="grid grid-cols-[120px_1fr] gap-y-1">- <dt className="text-muted-foreground">{t(($) => $.checkout.label_order)}</dt>- <dd className="font-mono">{data.order_id}</dd>- <dt className="text-muted-foreground">{t(($) => $.checkout.label_tier)}</dt>- <dd>{data.tier_id}</dd>- <dt className="text-muted-foreground">{t(($) => $.checkout.label_charged)}</dt>- <dd>- {data.bonus_credits > 0- ? t(($) => $.checkout.charged_with_bonus, {- money: formatMoney(data.amount_cents, data.currency, locale),- credits: data.credits.toLocaleString(locale),- bonus: data.bonus_credits.toLocaleString(locale),- })- : t(($) => $.checkout.charged_value, {- money: formatMoney(data.amount_cents, data.currency, locale),- credits: data.credits.toLocaleString(locale),- })}- </dd>- </dl>- {terminal && (- <Button- variant="outline"- size="sm"- className="mt-3"- onClick={onDismiss}- >- {t(($) => $.checkout.clear_url)}- </Button>- )}- </CardContent>- )}- </Card>- );-}--// ─── Balance ─────────────────────────────────────────────────────────--function BalanceCard() {- const { t } = useT("billing");- const locale = useLocale();- const balance = useQuery(billingBalanceOptions());-- return (- <Card>- <CardHeader className="flex flex-row items-center justify-between">- <div>- <CardTitle className="text-body">{t(($) => $.balance.title)}</CardTitle>- <CardDescription className="text-caption">- {t(($) => $.endpoints.balance)}- </CardDescription>- </div>- <RefreshButton- isLoading={balance.isFetching}- onClick={() => void balance.refetch()}- />- </CardHeader>- <CardContent>- {balance.isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : balance.isError ? (- <ErrorText error={balance.error} />- ) : (- <div className="space-y-1 text-body">- <div className="text-display-sm font-semibold tabular-nums">- {balance.data?.balance_credit.toLocaleString(locale) ?? 0}- <span className="ml-1 text-body font-normal text-muted-foreground">- {t(($) => $.balance.credits_suffix)}- </span>- </div>- <div className="text-caption text-muted-foreground">- {t(($) => $.balance.meta, {- micro: balance.data?.balance_micro.toLocaleString(locale) ?? 0,- owner: balance.data?.owner_id.slice(0, 8) ?? "",- updated: formatDate(balance.data?.updated_at, t, locale),- })}- </div>- </div>- )}- </CardContent>- </Card>- );-}--// ─── Buy + Portal ────────────────────────────────────────────────────--function BuyAndPortalSection() {- const { t } = useT("billing");- const tiers = useQuery(billingPriceTiersOptions());- const createCheckout = useCreateCloudBillingCheckoutSession();- const createPortal = useCreateCloudBillingPortalSession();- const [busyTier, setBusyTier] = useState<string | null>(null);-- const handleBuy = async (tier: BillingPriceTier) => {- setBusyTier(tier.id);- try {- const { url } = await createCheckout.mutateAsync({ tier_id: tier.id });- if (!url) {- toast.error(t(($) => $.buy.toast_no_url));- return;- }- // Redirect via window.location instead of window.open so the- // browser back button returns the user to this page after- // Stripe redirects out. Stripe-hosted pages handle their own- // SPA-like behaviour from there.- // eslint-disable-next-line no-restricted-syntax -- web-only test page; Desktop has no route to it- window.location.href = url;- } catch (err) {- toast.error(- err instanceof Error ? err.message : t(($) => $.buy.toast_checkout_failed),- );- } finally {- setBusyTier(null);- }- };-- const handlePortal = async () => {- try {- const { url } = await createPortal.mutateAsync();- if (!url) {- toast.error(t(($) => $.buy.toast_no_portal_url));- return;- }- // Open in a new tab — the portal is a customer self-service- // surface and keeping our session in this tab makes it easy to- // come back and verify the resulting state via this same page.- window.open(url, "_blank", "noopener,noreferrer");- } catch (err) {- // 400 is the documented "no Stripe customer yet" case from- // upstream. Surface the body verbatim — it's the most useful- // signal during testing.- toast.error(- err instanceof Error ? err.message : t(($) => $.buy.toast_portal_failed),- );- }- };-- return (- <Card>- <CardHeader>- <CardTitle className="text-body">{t(($) => $.buy.title)}</CardTitle>- <CardDescription className="text-caption">- {t(($) => $.endpoints.buy)}- </CardDescription>- </CardHeader>- <CardContent className="space-y-4">- {tiers.isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : tiers.isError ? (- <ErrorText error={tiers.error} />- ) : tiers.data?.length ? (- <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">- {tiers.data.map((tier) => (- <TierButton- key={tier.id}- tier={tier}- busy={busyTier === tier.id}- disabled={busyTier !== null}- onClick={() => void handleBuy(tier)}- />- ))}- </div>- ) : (- <p className="text-caption text-muted-foreground">{t(($) => $.buy.no_tiers)}</p>- )}-- <div className="border-t pt-4">- <Button- type="button"- variant="outline"- size="sm"- disabled={createPortal.isPending}- onClick={() => void handlePortal()}- >- {createPortal.isPending ? (- <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />- ) : (- <ExternalLink className="mr-1.5 h-3.5 w-3.5" />- )}- {t(($) => $.buy.open_portal)}- </Button>- <p className="mt-1 text-caption text-muted-foreground">- {t(($) => $.buy.portal_hint)}- </p>- </div>- </CardContent>- </Card>- );-}--function TierButton({- tier,- busy,- disabled,- onClick,-}: {- tier: BillingPriceTier;- busy: boolean;- disabled: boolean;- onClick: () => void;-}) {- const { t } = useT("billing");- const locale = useLocale();- const display = tier.display_name || tier.id;- const baseLine = t(($) => $.buy.tier_money_to_credits, {- money: formatMoney(tier.amount_cents, "usd", locale),- credits: tier.credits.toLocaleString(locale),- });- const bonusLine = tier.bonus_credits- ? tier.bonus_expires_in- ? t(($) => $.buy.tier_bonus_with_expiry, {- credits: tier.bonus_credits.toLocaleString(locale),- expiry: tier.bonus_expires_in,- })- : t(($) => $.buy.tier_bonus, {- credits: tier.bonus_credits.toLocaleString(locale),- })- : "";- return (- <button- type="button"- disabled={disabled}- onClick={onClick}- className="rounded-md border bg-background p-3 text-left transition hover:border-primary disabled:cursor-not-allowed disabled:opacity-50"- >- <div className="flex items-center justify-between">- <div className="text-body font-medium">{display}</div>- {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}- </div>- <div className="mt-1 text-caption text-muted-foreground">- {baseLine}- {bonusLine}- </div>- <div className="mt-1 font-mono text-micro text-muted-foreground">- {t(($) => $.buy.tier_id, { id: tier.id })}- </div>- </button>- );-}--// ─── Lists ───────────────────────────────────────────────────────────--function TransactionsCard() {- const { t } = useT("billing");- const txs = useQuery(billingTransactionsOptions({ page: 1, page_size: 20 }));- return (- <Card>- <CardHeader className="flex flex-row items-center justify-between">- <div>- <CardTitle className="text-body">{t(($) => $.transactions.title)}</CardTitle>- <CardDescription className="text-caption">- {t(($) => $.endpoints.transactions)}- </CardDescription>- </div>- <RefreshButton- isLoading={txs.isFetching}- onClick={() => void txs.refetch()}- />- </CardHeader>- <CardContent>- {txs.isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : txs.isError ? (- <ErrorText error={txs.error} />- ) : txs.data?.items.length ? (- <ul className="space-y-2 text-caption">- {txs.data.items.map((row) => (- <TransactionRow key={row.id} row={row} />- ))}- </ul>- ) : (- <EmptyText>{t(($) => $.transactions.empty)}</EmptyText>- )}- <PagingFooter- page={txs.data?.page ?? 1}- pageSize={txs.data?.page_size ?? 20}- total={txs.data?.total ?? 0}- />- </CardContent>- </Card>- );-}--function TransactionRow({ row }: { row: BillingTransaction }) {- const { t } = useT("billing");- const locale = useLocale();- const credit = row.amount_micro / MICRO_PER_CREDIT;- return (- <li className="rounded-md border bg-background p-2.5">- <div className="flex items-center justify-between gap-2">- <span className="text-caption font-medium">- {row.tx_type}- <span className="ml-1.5 rounded-xs bg-muted px-1.5 py-0.5 font-mono text-micro text-muted-foreground">- {row.source}- </span>- </span>- <span- className={`text-body tabular-nums ${- credit >= 0- ? "text-green-700 dark:text-green-400"- : "text-red-700 dark:text-red-400"- }`}- >- {t(($) => $.transactions.credits_value, {- value: `${credit >= 0 ? "+" : ""}${credit.toLocaleString(locale)}`,- })}- </span>- </div>- {row.description && (- <div className="mt-1 text-caption text-muted-foreground">{row.description}</div>- )}- <div className="mt-1 font-mono text-micro text-muted-foreground">- {t(($) => $.transactions.row_meta, {- date: formatDate(row.created_at, t, locale),- balance: (row.balance_after / MICRO_PER_CREDIT).toLocaleString(locale),- ref: row.reference_id || t(($) => $.transactions.ref_empty),- })}- </div>- </li>- );-}--function BatchesCard() {- const { t } = useT("billing");- const batches = useQuery(billingBatchesOptions({ page: 1, page_size: 20 }));- return (- <Card>- <CardHeader className="flex flex-row items-center justify-between">- <div>- <CardTitle className="text-body">{t(($) => $.batches.title)}</CardTitle>- <CardDescription className="text-caption">- {t(($) => $.endpoints.batches)}- </CardDescription>- </div>- <RefreshButton- isLoading={batches.isFetching}- onClick={() => void batches.refetch()}- />- </CardHeader>- <CardContent>- {batches.isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : batches.isError ? (- <ErrorText error={batches.error} />- ) : batches.data?.items.length ? (- <ul className="space-y-2 text-caption">- {batches.data.items.map((row) => (- <BatchRow key={row.id} row={row} />- ))}- </ul>- ) : (- <EmptyText>{t(($) => $.batches.empty)}</EmptyText>- )}- <PagingFooter- page={batches.data?.page ?? 1}- pageSize={batches.data?.page_size ?? 20}- total={batches.data?.total ?? 0}- />- </CardContent>- </Card>- );-}--function BatchRow({ row }: { row: BillingBatch }) {- const { t } = useT("billing");- const locale = useLocale();- const total = row.total_micro / MICRO_PER_CREDIT;- const remaining = row.remaining_micro / MICRO_PER_CREDIT;- const consumed = total - remaining;- return (- <li className="rounded-md border bg-background p-2.5">- <div className="flex items-center justify-between gap-2">- <span className="text-caption font-medium">- {row.source_type}- <span className="ml-1.5 font-mono text-micro text-muted-foreground">- {t(($) => $.batches.id_suffix, { id: row.id.slice(0, 8) })}- </span>- </span>- <span className="text-body tabular-nums">- {t(($) => $.batches.remaining_over_total, {- remaining: remaining.toLocaleString(locale),- total: total.toLocaleString(locale),- })}- </span>- </div>- <div className="mt-1 text-caption text-muted-foreground">- {t(($) => $.batches.consumed, { value: consumed.toLocaleString(locale) })}- {row.expires_at- ? t(($) => $.batches.expires_suffix, { value: formatDate(row.expires_at, t, locale) })- : t(($) => $.batches.never_expires_suffix)}- </div>- </li>- );-}--function TopupsCard() {- const { t } = useT("billing");- const topups = useQuery(billingTopupsOptions({ page: 1, page_size: 20 }));- return (- <Card>- <CardHeader className="flex flex-row items-center justify-between">- <div>- <CardTitle className="text-body">{t(($) => $.topups.title)}</CardTitle>- <CardDescription className="text-caption">- {t(($) => $.endpoints.topups)}- </CardDescription>- </div>- <RefreshButton- isLoading={topups.isFetching}- onClick={() => void topups.refetch()}- />- </CardHeader>- <CardContent>- {topups.isLoading ? (- <Loader2 className="h-4 w-4 animate-spin" />- ) : topups.isError ? (- <ErrorText error={topups.error} />- ) : topups.data?.items.length ? (- <ul className="space-y-2 text-caption">- {topups.data.items.map((row) => (- <TopupRow key={row.id} row={row} />- ))}- </ul>- ) : (- <EmptyText>{t(($) => $.topups.empty)}</EmptyText>- )}- <PagingFooter- page={topups.data?.page ?? 1}- pageSize={topups.data?.page_size ?? 20}- total={topups.data?.total ?? 0}- />- </CardContent>- </Card>- );-}--function TopupRow({ row }: { row: BillingTopup }) {- const { t } = useT("billing");- const locale = useLocale();- return (- <li className="rounded-md border bg-background p-2.5">- <div className="flex items-center justify-between gap-2">- <span className="text-caption font-medium">- {row.tier_id || row.id.slice(0, 8)}- <span- className={`ml-1.5 rounded-xs px-1.5 py-0.5 font-mono text-micro ${- row.status === "credited"- ? "bg-green-500/10 text-green-700 dark:text-green-400"- : row.status === "failed" || row.status === "canceled"- ? "bg-red-500/10 text-red-700 dark:text-red-400"- : "bg-amber-500/10 text-amber-700 dark:text-amber-400"- }`}- >- {row.status}- </span>- </span>- <span className="text-body tabular-nums">- {row.bonus_credits > 0- ? t(($) => $.topups.amount_to_credits_with_bonus, {- money: formatMoney(row.amount_cents, row.currency, locale),- credits: row.credits.toLocaleString(locale),- bonus: row.bonus_credits.toLocaleString(locale),- })- : t(($) => $.topups.amount_to_credits, {- money: formatMoney(row.amount_cents, row.currency, locale),- credits: row.credits.toLocaleString(locale),- })}- </span>- </div>- <div className="mt-1 font-mono text-micro text-muted-foreground">- {t(($) => $.topups.row_meta, {- date: formatDate(row.created_at, t, locale),- checkout: row.stripe_checkout_id || t(($) => $.topups.stripe_empty),- })}- </div>- </li>- );-}--// ─── Shared bits ─────────────────────────────────────────────────────--function PagingFooter({- page,- pageSize,- total,-}: {- page: number;- pageSize: number;- total: number;-}) {- const { t } = useT("billing");- if (total === 0) return null;- return (- <div className="mt-3 text-micro text-muted-foreground">- {t(($) => $.shared.paging, {- page,- totalPages: Math.max(1, Math.ceil(total / pageSize)),- total,- })}- </div>- );-}--function RefreshButton({- isLoading,- onClick,-}: {- isLoading: boolean;- onClick: () => void;-}) {- const { t } = useT("billing");- return (- <Button- type="button"- variant="ghost"- size="sm"- className="h-7 w-7 p-0"- onClick={onClick}- disabled={isLoading}- aria-label={t(($) => $.shared.refresh)}- >- <RefreshCw className={`h-3.5 w-3.5 ${isLoading ? "animate-spin" : ""}`} />- </Button>- );-}--function ErrorText({ error }: { error: unknown }) {- const { t } = useT("billing");- return (- <p className="text-caption text-destructive">- {error instanceof Error ? error.message : t(($) => $.shared.request_failed)}- </p>- );-}--function EmptyText({ children }: { children: React.ReactNode }) {- return <p className="text-caption text-muted-foreground">{children}</p>;-}--function formatMoney(- amountCents: number,- currency: string,- locale: string,-): string {- // Intl is fine here — no currency conversion happening, just canonical- // display in the same locale as the surrounding translated sentence.- try {- return new Intl.NumberFormat(locale, {- style: "currency",- currency: currency.toUpperCase(),- }).format(amountCents / CENTS_PER_DOLLAR);- } catch {- return `${(amountCents / CENTS_PER_DOLLAR).toFixed(2)} ${currency.toUpperCase()}`;- }-}--// formatDate returns an ISO-ish localized string or the locale's "—"-// dash for missing/invalid input. The dash itself goes through the-// translation bundle so it stays consistent if either locale ever-// wants to swap it for a localized placeholder. Caller passes in `t`-// so we don't run useT() inside a util (the rule of hooks would-// trip on the conditional path).-function formatDate(- value: string | undefined,- t: ReturnType<typeof useT<"billing">>["t"],- locale: string,-): string {- if (!value) return t(($) => $.shared.date_dash);- const d = new Date(value);- if (Number.isNaN(d.getTime())) return value;- return d.toLocaleString(locale);-}diff --git a/packages/views/billing/index.ts b/packages/views/billing/index.tsindex c87df8153f..1b9f38ef12 100644--- a/packages/views/billing/index.ts+++ b/packages/views/billing/index.ts@@ -1,2 +1 @@-export { BillingTestPage } from "./billing-test-page";export { BillingReturnPage } from "./billing-return-page";diff --git a/packages/views/inbox/components/inbox-page-query.test.tsx b/packages/views/inbox/components/inbox-page-query.test.tsxindex 8416c6bda9..36768243c7 100644--- a/packages/views/inbox/components/inbox-page-query.test.tsx+++ b/packages/views/inbox/components/inbox-page-query.test.tsx@@ -21,8 +21,8 @@ vi.mock("@multica/core/paths", () => ({issueDetail: (id: string) => `/acme/issues/${id}`,}),}));-vi.mock("../../modals/use-issue-limit-upgrade-prompt", () => ({- useIssueLimitUpgradePrompt: () => vi.fn(),+vi.mock("../../modals/use-limit-recovery-prompt", () => ({+ useLimitRecoveryPrompt: () => vi.fn(),}));const detailUnmounted = vi.hoisted(() => vi.fn());diff --git a/packages/views/inbox/components/inbox-page.test.tsx b/packages/views/inbox/components/inbox-page.test.tsxindex e85ecce1ef..1600207010 100644--- a/packages/views/inbox/components/inbox-page.test.tsx+++ b/packages/views/inbox/components/inbox-page.test.tsx@@ -1,7 +1,6 @@import { act, fireEvent, render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import { toast } from "sonner";-import { ApiError } from "@multica/core/api";import type { AgentTask, InboxItem } from "@multica/core/types";import { useInboxFilterStore } from "@multica/core/inbox/filter-store";import { useInboxSelectionStore } from "@multica/core/inbox/selection-store";@@ -91,14 +90,10 @@ const markUnreadMutate = vi.fn();const archiveMutate = vi.fn();const unarchiveMutate = vi.fn();const retrySourceContextMutateAsync = vi.fn();-const showIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());const showAutopilotQuotaRecoveryPrompt = vi.hoisted(() => vi.fn());-vi.mock("../../modals/use-issue-limit-upgrade-prompt", () => ({- useIssueLimitUpgradePrompt: (reason?: string) =>- reason === "autopilot_quota"- ? showAutopilotQuotaRecoveryPrompt- : showIssueLimitUpgradePrompt,+vi.mock("../../modals/use-limit-recovery-prompt", () => ({+ useLimitRecoveryPrompt: () => showAutopilotQuotaRecoveryPrompt,}));vi.mock("@multica/core/inbox/mutations", () => {@@ -280,7 +275,6 @@ function reset() {unarchiveMutate.mockClear();retrySourceContextMutateAsync.mockReset();retrySourceContextMutateAsync.mockResolvedValue({});- showIssueLimitUpgradePrompt.mockClear();showAutopilotQuotaRecoveryPrompt.mockClear();modalState.modal = null;vi.mocked(toast.success).mockClear();@@ -881,40 +875,6 @@ describe("InboxPage", () => {fireEvent.click(screen.getByTestId("autopilot-quota-recovery"));expect(showAutopilotQuotaRecoveryPrompt).toHaveBeenCalledTimes(1);- expect(showIssueLimitUpgradePrompt).not.toHaveBeenCalled();- });-- it("shows issue-limit recovery when a source-context retry is rejected", async () => {- reset();- retrySourceContextMutateAsync.mockRejectedValue(- new ApiError(- "workspace has reached its issue limit",- 402,- "Payment Required",- { code: "issue_limit_reached" },- ),- );- listData.active = [- item({- id: "source-context-limit",- issue_id: null,- type: "quick_create_failed",- details: {- task_id: "task-1",- source_context_id: "context-1",- original_prompt: "make a child",- },- }),- ];-- render(<InboxPage />);- fireEvent.click(screen.getByTestId("row"));- fireEvent.click(screen.getByTestId("retry-source-context"));-- await act(async () => undefined);- expect(showIssueLimitUpgradePrompt).toHaveBeenCalledTimes(1);- expect(showAutopilotQuotaRecoveryPrompt).not.toHaveBeenCalled();- expect(toast.error).not.toHaveBeenCalled();});it("marks the opened notification read", () => {diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 9239f0e274..7a6a2ad33c 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -125,7 +125,7 @@ import { useArchiveInboxBatchWithUndo, useArchiveInboxWithUndo, useRestoreInboximport { useInboxSnooze } from "./use-inbox-snooze";import { InboxAppRequest } from "../../common/app-requests";import { useT } from "../../i18n";-import { useIssueLimitUpgradePrompt } from "../../modals/use-issue-limit-upgrade-prompt";+import { useLimitRecoveryPrompt } from "../../modals/use-limit-recovery-prompt";/** The phone's Inbox list, apart from the Work panel section's. */@@ -135,8 +135,7 @@ export function InboxPage() {const queryClient = useQueryClient();const { t } = useT("inbox");const { t: tCommon } = useT("common");- const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();- const showAutopilotQuotaRecoveryPrompt = useIssueLimitUpgradePrompt(+ const showAutopilotQuotaRecoveryPrompt = useLimitRecoveryPrompt("autopilot_quota",);const { searchParams, replace } = useNavigation();@@ -1079,13 +1078,6 @@ export function InboxPage() {await retrySourceContextMutation.mutateAsync(detailItem.details!.task_id!);toast.success(t(($) => $.toasts.source_context_retry_started));} catch (error) {- if (- error instanceof ApiError &&- errorCode(error) === "issue_limit_reached"- ) {- showIssueLimitUpgradePrompt();- return;- }toast.error(error instanceof ApiError &&errorCode(error) === "source_context_retry_unavailable"diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.jsonindex 9741ef23ae..e4572a79a9 100644--- a/packages/views/locales/en/autopilots.json+++ b/packages/views/locales/en/autopilots.json@@ -81,7 +81,6 @@"run_blocked_attribution": "Not triggered — the run couldn't be attributed to a responsible member","run_blocked_already_active": "Not triggered — a recent run already covers this","run_blocked_quota_exceeded": "Not triggered — the run limit for this period has been reached",- "run_blocked_issue_limit_reached": "Not triggered — the workspace has reached its issue limit","run_blocked_generic": "Not triggered — the run was blocked","section_triggers": "Triggers","section_run_history": "Run history",diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 32ce53a6bf..b674007029 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -1,71 +1,4 @@{- "title": "Billing (test page)",- "subtitle": "Direct passthrough to multica-cloud's /api/v1/billing/*. Not a finished UI — just every endpoint stuffed onto one page so we can verify the proxy + Stripe flow.",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "Balance",- "credits_suffix": "credits",- "meta": "raw micro: {{micro}} · owner: {{owner}}… · updated {{updated}}"- },- "buy": {- "title": "Buy credits / Manage billing",- "no_tiers": "No price tiers configured. Cloud probably has no Stripe key set — checkout will return 503.",- "tier_money_to_credits": "{{money}} → {{credits}} credits",- "tier_bonus": " + {{credits}} bonus",- "tier_bonus_with_expiry": " + {{credits}} bonus ({{expiry}})",- "tier_id": "id: {{id}}",- "open_portal": "Open Stripe Billing Portal",- "portal_hint": "400 is expected for users who haven't paid yet (no Stripe customer record exists).",- "toast_no_url": "Cloud returned no checkout URL",- "toast_checkout_failed": "Checkout failed",- "toast_no_portal_url": "No portal URL returned",- "toast_portal_failed": "Portal failed"- },- "checkout": {- "session_label": "Checkout session {{prefix}}…",- "loading": "Loading order status…",- "fetch_failed": "Failed to fetch status: {{error}}",- "fetch_failed_unknown": "unknown error",- "final_status": "Final status: {{status}}",- "polling_status": "Polling status… current: {{status}}",- "status_unknown": "unknown",- "label_order": "Order",- "label_tier": "Tier",- "label_charged": "Charged",- "charged_value": "{{money}} · {{credits}} credits",- "charged_with_bonus": "{{money}} · {{credits}} credits + {{bonus}} bonus",- "clear_url": "Clear from URL"- },- "transactions": {- "title": "Transactions",- "empty": "No transactions yet.",- "credits_value": "{{value}} credits",- "row_meta": "{{date}} · balance after: {{balance}} credits · ref: {{ref}}",- "ref_empty": "—"- },- "batches": {- "title": "Credit batches",- "empty": "No batches yet.",- "remaining_over_total": "{{remaining}} / {{total}} credits",- "id_suffix": "{{id}}…",- "consumed": "Consumed: {{value}} credits",- "expires_suffix": " · expires {{value}}",- "never_expires_suffix": " · never expires"- },- "topups": {- "title": "Topup orders",- "empty": "No topup orders yet.",- "amount_to_credits": "{{money}} → {{credits}} credits",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} credits + {{bonus}} bonus",- "row_meta": "{{date}} · stripe: {{checkout}}",- "stripe_empty": "—"- },"workspace": {"title": "Billing","description": "Manage this workspace's plan, limits, human seats, and Stripe billing.",@@ -171,7 +104,6 @@},"limits": {"title": "Usage and limits",- "issues": "Issues","autopilots": "Automation runs","unlimited": "Unlimited","per_month": "{{count}} / month",@@ -246,12 +178,6 @@"description": "Billing interval: {{interval}}. Current human members: {{count}}. Stripe will re-count seats and show the final amount before payment."}},- "shared": {- "request_failed": "Request failed",- "refresh": "Refresh",- "paging": "page {{page}} / {{totalPages}} · {{total}} total",- "date_dash": "—"- },"return_page": {"redirecting": "Returning you to workspace billing…","load_failed_title": "Could not open workspace billing",diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.jsonindex 75889a2eec..ab8e241a00 100644--- a/packages/views/locales/en/modals.json+++ b/packages/views/locales/en/modals.json@@ -184,19 +184,6 @@"toast_failed": "Failed to create issue","toast_duplicate_title": "Duplicate issue","toast_duplicate_view": "View existing issue",- "issue_limit": {- "title": "This workspace has reached its issue limit",- "checking_description": "Checking the billing actions available for this workspace…",- "upgrade_description": "Upgrade to Pro to keep creating issues.",- "portal_description": "Open Billing Portal to manage this workspace's subscription and restore issue creation.",- "contact_description": "Ask a workspace owner or admin to upgrade to Pro.",- "billing_description": "Open Billing to see the upgrade options available for this workspace.",- "billing_unavailable_description": "Billing actions could not be loaded. Open Billing to try again.",- "billing_disabled_description": "Delete an existing issue to free space, or contact your workspace administrator.",- "upgrade_action": "Upgrade to Pro",- "portal_action": "Open Billing Portal",- "billing_action": "View Billing"- },"autopilot_quota_limit": {"title": "This workspace has reached its autopilot run limit","checking_description": "Checking the billing actions available for this workspace…",diff --git a/packages/views/locales/es/autopilots.json b/packages/views/locales/es/autopilots.jsonindex 8f4932ff31..7bcb5b6e97 100644--- a/packages/views/locales/es/autopilots.json+++ b/packages/views/locales/es/autopilots.json@@ -79,7 +79,6 @@"run_blocked_attribution": "No disparado: la ejecución no pudo atribuirse a un miembro responsable","run_blocked_already_active": "No disparado: una ejecución reciente ya cubre esto","run_blocked_quota_exceeded": "No disparado: se alcanzó el límite de ejecuciones de este periodo",- "run_blocked_issue_limit_reached": "No disparado: el espacio de trabajo alcanzó su límite de tareas","run_blocked_generic": "No se ha disparado: la ejecución se ha bloqueado","section_triggers": "Disparadores","section_run_history": "Historial de ejecuciones",diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex 550753f78f..67a7abaf57 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -1,71 +1,4 @@{- "title": "Facturación (página de prueba)",- "subtitle": "Pasarela directa a /api/v1/billing/* de multica-cloud. No es una UI terminada: solo todos los endpoints metidos en una página para poder verificar el proxy y el flujo de Stripe.",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "Saldo",- "credits_suffix": "créditos",- "meta": "micros en bruto: {{micro}} · propietario: {{owner}}… · actualizado {{updated}}"- },- "buy": {- "title": "Comprar créditos / Gestionar facturación",- "no_tiers": "No hay niveles de precio configurados. Es probable que Cloud no tenga clave de Stripe: checkout devolverá 503.",- "tier_money_to_credits": "{{money}} → {{credits}} créditos",- "tier_bonus": " + {{credits}} de bonus",- "tier_bonus_with_expiry": " + {{credits}} de bonus ({{expiry}})",- "tier_id": "id: {{id}}",- "open_portal": "Abrir el portal de facturación de Stripe",- "portal_hint": "400 es lo esperado para usuarios que aún no han pagado (no existe registro de cliente en Stripe).",- "toast_no_url": "Cloud no devolvió URL de checkout",- "toast_checkout_failed": "El checkout falló",- "toast_no_portal_url": "No se devolvió URL del portal",- "toast_portal_failed": "El portal falló"- },- "checkout": {- "session_label": "Sesión de checkout {{prefix}}…",- "loading": "Cargando el estado del pedido…",- "fetch_failed": "No se ha podido obtener el estado: {{error}}",- "fetch_failed_unknown": "error desconocido",- "final_status": "Estado final: {{status}}",- "polling_status": "Consultando el estado… actual: {{status}}",- "status_unknown": "desconocido",- "label_order": "Pedido",- "label_tier": "Nivel",- "label_charged": "Cobrado",- "charged_value": "{{money}} · {{credits}} créditos",- "charged_with_bonus": "{{money}} · {{credits}} créditos + {{bonus}} de bonus",- "clear_url": "Quitar de la URL"- },- "transactions": {- "title": "Transacciones",- "empty": "Aún no hay transacciones.",- "credits_value": "{{value}} créditos",- "row_meta": "{{date}} · saldo después: {{balance}} créditos · ref: {{ref}}",- "ref_empty": "-"- },- "batches": {- "title": "Lotes de crédito",- "empty": "Aún no hay lotes.",- "remaining_over_total": "{{remaining}} / {{total}} créditos",- "id_suffix": "{{id}}…",- "consumed": "Consumidos: {{value}} créditos",- "expires_suffix": " · caduca {{value}}",- "never_expires_suffix": " · nunca caduca"- },- "topups": {- "title": "Pedidos de recarga",- "empty": "Aún no hay pedidos de recarga.",- "amount_to_credits": "{{money}} → {{credits}} créditos",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} créditos + {{bonus}} de bonus",- "row_meta": "{{date}} · stripe: {{checkout}}",- "stripe_empty": "-"- },"workspace": {"title": "Facturación","description": "Gestiona el plan, los límites, los puestos humanos y la facturación de Stripe de este espacio de trabajo.",@@ -171,7 +104,6 @@},"limits": {"title": "Uso y límites",- "issues": "Tareas","autopilots": "Ejecuciones de automatización","unlimited": "Ilimitado","per_month": "{{count}} / mes",@@ -246,12 +178,6 @@"description": "Intervalo de facturación: {{interval}}. Miembros humanos actuales: {{count}}. Stripe volverá a contar los puestos y mostrará el importe final antes del pago."}},- "shared": {- "request_failed": "La solicitud falló",- "refresh": "Actualizar",- "paging": "página {{page}} / {{totalPages}} · {{total}} en total",- "date_dash": "-"- },"return_page": {"redirecting": "Volviendo a la facturación del espacio de trabajo…","load_failed_title": "No se ha podido abrir la facturación del espacio de trabajo",diff --git a/packages/views/locales/es/modals.json b/packages/views/locales/es/modals.jsonindex 73f6961254..4f9ed517de 100644--- a/packages/views/locales/es/modals.json+++ b/packages/views/locales/es/modals.json@@ -159,19 +159,6 @@"toast_failed": "No se ha podido crear la tarea","toast_duplicate_title": "Tarea duplicada","toast_duplicate_view": "Ver la tarea existente",- "issue_limit": {- "title": "Este espacio de trabajo ha alcanzado su límite de tareas",- "checking_description": "Comprobando las acciones de facturación disponibles para este espacio de trabajo…",- "upgrade_description": "Actualiza a Pro para seguir creando tareas.",- "portal_description": "Abre el portal de facturación para gestionar la suscripción de este espacio de trabajo y restaurar la creación de tareas.",- "contact_description": "Pide a un propietario o administrador del espacio de trabajo que actualice a Pro.",- "billing_description": "Abre Facturación para ver las opciones de actualización disponibles para este espacio de trabajo.",- "billing_unavailable_description": "No se han podido cargar las acciones de facturación. Abre Facturación para reintentarlo.",- "billing_disabled_description": "Elimina una tarea existente para liberar espacio, o contacta con el administrador de tu espacio de trabajo.",- "upgrade_action": "Actualizar a Pro",- "portal_action": "Abrir portal de facturación",- "billing_action": "Ver facturación"- },"autopilot_quota_limit": {"title": "Este espacio de trabajo ha alcanzado su límite de ejecuciones de automatizaciones","checking_description": "Comprobando las acciones de facturación disponibles para este espacio de trabajo…",diff --git a/packages/views/locales/fr/autopilots.json b/packages/views/locales/fr/autopilots.jsonindex c3d22ca6d9..2862963d87 100644--- a/packages/views/locales/fr/autopilots.json+++ b/packages/views/locales/fr/autopilots.json@@ -81,7 +81,6 @@"run_blocked_attribution": "Non déclenchée — l'exécution n'a pas pu être attribuée à un membre responsable","run_blocked_already_active": "Non déclenchée — une exécution récente couvre déjà ce cas","run_blocked_quota_exceeded": "Non déclenché — la limite d'exécutions de la période est atteinte",- "run_blocked_issue_limit_reached": "Non déclenchée : l'espace de travail a atteint sa limite de tâches","run_blocked_generic": "Non déclenchée — l'exécution a été bloquée","section_triggers": "Déclencheurs","section_run_history": "Historique des exécutions",diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex 2e35855e9d..d67d057578 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -1,71 +1,4 @@{- "title": "Facturation (page de test)",- "subtitle": "Passe-plat direct vers /api/v1/billing/* de multica-cloud. Interface inachevée — tous les points d'accès entassés sur une page pour vérifier le proxy et le flux Stripe.",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "Solde",- "credits_suffix": "crédits",- "meta": "micro brut : {{micro}} · propriétaire : {{owner}}… · mis à jour {{updated}}"- },- "buy": {- "title": "Acheter des crédits / Gérer la facturation",- "no_tiers": "Aucun palier tarifaire configuré. Le cloud n'a probablement pas de clé Stripe — le paiement renverra 503.",- "tier_money_to_credits": "{{money}} → {{credits}} crédits",- "tier_bonus": " + {{credits}} en bonus",- "tier_bonus_with_expiry": " + {{credits}} en bonus ({{expiry}})",- "tier_id": "id : {{id}}",- "open_portal": "Ouvrir le portail de facturation Stripe",- "portal_hint": "Un 400 est attendu pour les utilisateurs qui n'ont pas encore payé (aucune fiche client Stripe n'existe).",- "toast_no_url": "Le cloud n'a renvoyé aucune URL de paiement",- "toast_checkout_failed": "Échec du paiement",- "toast_no_portal_url": "Aucune URL de portail renvoyée",- "toast_portal_failed": "Échec du portail"- },- "checkout": {- "session_label": "Session de paiement {{prefix}}…",- "loading": "Chargement de l'état de la commande…",- "fetch_failed": "Échec de la récupération de l'état : {{error}}",- "fetch_failed_unknown": "erreur inconnue",- "final_status": "État final : {{status}}",- "polling_status": "Interrogation de l'état… actuel : {{status}}",- "status_unknown": "inconnu",- "label_order": "Commande",- "label_tier": "Palier",- "label_charged": "Facturé",- "charged_value": "{{money}} · {{credits}} crédits",- "charged_with_bonus": "{{money}} · {{credits}} crédits + {{bonus}} en bonus",- "clear_url": "Effacer de l'URL"- },- "transactions": {- "title": "Transactions",- "empty": "Aucune transaction pour l'instant.",- "credits_value": "{{value}} crédits",- "row_meta": "{{date}} · solde après : {{balance}} crédits · réf. : {{ref}}",- "ref_empty": "—"- },- "batches": {- "title": "Lots de crédits",- "empty": "Aucun lot pour l'instant.",- "remaining_over_total": "{{remaining}} / {{total}} crédits",- "id_suffix": "{{id}}…",- "consumed": "Consommés : {{value}} crédits",- "expires_suffix": " · expire {{value}}",- "never_expires_suffix": " · n'expire jamais"- },- "topups": {- "title": "Commandes de recharge",- "empty": "Aucune commande de recharge pour l'instant.",- "amount_to_credits": "{{money}} → {{credits}} crédits",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} crédits + {{bonus}} en bonus",- "row_meta": "{{date}} · stripe : {{checkout}}",- "stripe_empty": "—"- },"workspace": {"title": "Facturation","description": "Gérez le forfait, les limites, les sièges humains et la facturation Stripe de cet espace de travail.",@@ -171,7 +104,6 @@},"limits": {"title": "Consommation et limites",- "issues": "Tâches","autopilots": "Exécutions d'automatisation","unlimited": "Illimité","per_month": "{{count}} / mois",@@ -246,12 +178,6 @@"description": "Intervalle de facturation : {{interval}}. Membres humains actuels : {{count}}. Stripe recomptera les sièges et affichera le montant final avant le paiement."}},- "shared": {- "request_failed": "Échec de la requête",- "refresh": "Actualiser",- "paging": "page {{page}} / {{totalPages}} · {{total}} au total",- "date_dash": "—"- },"return_page": {"redirecting": "Retour vers la facturation de l'espace de travail…","load_failed_title": "Impossible d'ouvrir la facturation de l'espace de travail",diff --git a/packages/views/locales/fr/modals.json b/packages/views/locales/fr/modals.jsonindex 212d7eeac0..b5d0308284 100644--- a/packages/views/locales/fr/modals.json+++ b/packages/views/locales/fr/modals.json@@ -184,19 +184,6 @@"toast_failed": "Échec de la création de la tâche","toast_duplicate_title": "Tâche en double","toast_duplicate_view": "Voir la tâche existante",- "issue_limit": {- "title": "Cet espace de travail a atteint sa limite de tâches",- "checking_description": "Vérification des actions de facturation disponibles pour cet espace de travail…",- "upgrade_description": "Passez à Pro pour continuer à créer des tâches.",- "portal_description": "Ouvrez le portail de facturation pour gérer l'abonnement de cet espace de travail et rétablir la création de tâches.",- "contact_description": "Demandez à un propriétaire ou administrateur de l'espace de travail de passer à Pro.",- "billing_description": "Ouvrez Facturation pour voir les options de mise à niveau disponibles pour cet espace de travail.",- "billing_unavailable_description": "Impossible de charger les actions de facturation. Ouvrez Facturation pour réessayer.",- "billing_disabled_description": "Supprimez une tâche existante pour libérer de la place ou contactez l'administrateur de votre espace de travail.",- "upgrade_action": "Passer à Pro",- "portal_action": "Ouvrir le portail de facturation",- "billing_action": "Voir la facturation"- },"autopilot_quota_limit": {"title": "Cet espace de travail a atteint sa limite d'exécutions d'automatisation","checking_description": "Vérification des actions de facturation disponibles pour cet espace de travail…",diff --git a/packages/views/locales/ja/autopilots.json b/packages/views/locales/ja/autopilots.jsonindex 9a398c7361..173677a554 100644--- a/packages/views/locales/ja/autopilots.json+++ b/packages/views/locales/ja/autopilots.json@@ -81,7 +81,6 @@"run_blocked_attribution": "実行されませんでした — 実行の責任者を特定できませんでした","run_blocked_already_active": "実行されませんでした — 直近の実行が本件をカバーしています","run_blocked_quota_exceeded": "実行されませんでした — この期間の実行上限に達しました",- "run_blocked_issue_limit_reached": "実行されませんでした — ワークスペースのタスク数上限に達しました","run_blocked_generic": "実行されませんでした — 実行がブロックされました","section_triggers": "トリガー","section_run_history": "実行履歴",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex dae35de86f..3b07f089ec 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -1,71 +1,4 @@{- "title": "請求(テストページ)",- "subtitle": "multica-cloud の /api/v1/billing/* に直接パススルーします。完成した UI ではなく、proxy と Stripe フローを検証するためにすべての endpoint を 1 つのページにまとめたものです。",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "残高",- "credits_suffix": "credits",- "meta": "raw micro: {{micro}} · owner: {{owner}}… · updated {{updated}}"- },- "buy": {- "title": "クレジット購入 / 請求の管理",- "no_tiers": "設定された価格 tier がありません。Cloud に Stripe key が設定されていない可能性があり、checkout は 503 を返します。",- "tier_money_to_credits": "{{money}} → {{credits}} credits",- "tier_bonus": " + ボーナス {{credits}}",- "tier_bonus_with_expiry": " + ボーナス {{credits}}({{expiry}})",- "tier_id": "id: {{id}}",- "open_portal": "Stripe Billing Portal を開く",- "portal_hint": "まだ支払いをしていないユーザーには 400 が想定されます(Stripe customer record がまだ存在しません)。",- "toast_no_url": "Cloud が checkout URL を返しませんでした",- "toast_checkout_failed": "Checkout に失敗しました",- "toast_no_portal_url": "Portal URL が返されませんでした",- "toast_portal_failed": "Portal を開けませんでした"- },- "checkout": {- "session_label": "Checkout session {{prefix}}…",- "loading": "注文ステータスを読み込み中…",- "fetch_failed": "ステータスの取得に失敗しました: {{error}}",- "fetch_failed_unknown": "不明なエラー",- "final_status": "最終ステータス: {{status}}",- "polling_status": "ステータスを確認中… 現在: {{status}}",- "status_unknown": "unknown",- "label_order": "注文",- "label_tier": "Tier",- "label_charged": "請求済み",- "charged_value": "{{money}} · {{credits}} credits",- "charged_with_bonus": "{{money}} · {{credits}} credits + ボーナス {{bonus}}",- "clear_url": "URL から消去"- },- "transactions": {- "title": "取引履歴",- "empty": "取引履歴はまだありません。",- "credits_value": "{{value}} credits",- "row_meta": "{{date}} · balance after: {{balance}} credits · ref: {{ref}}",- "ref_empty": "—"- },- "batches": {- "title": "クレジット batch",- "empty": "batch はまだありません。",- "remaining_over_total": "{{remaining}} / {{total}} credits",- "id_suffix": "{{id}}…",- "consumed": "使用済み: {{value}} credits",- "expires_suffix": " · 有効期限 {{value}}",- "never_expires_suffix": " · 有効期限なし"- },- "topups": {- "title": "Topup 注文",- "empty": "topup 注文はまだありません。",- "amount_to_credits": "{{money}} → {{credits}} credits",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} credits + ボーナス {{bonus}}",- "row_meta": "{{date}} · stripe: {{checkout}}",- "stripe_empty": "—"- },"workspace": {"title": "請求とプラン","description": "このワークスペースのプラン、上限、ユーザー席、Stripe 請求を管理します。",@@ -169,7 +102,6 @@},"limits": {"title": "使用量と上限",- "issues": "タスク数","autopilots": "自動化の実行","unlimited": "無制限","per_month": "月 {{count}} 回",@@ -239,12 +171,6 @@"description": "請求期間: {{interval}}。現在のユーザーメンバー: {{count}}。Stripe が席数を再集計し、お支払い前に最終金額を表示します。"}},- "shared": {- "request_failed": "リクエストに失敗しました",- "refresh": "更新",- "paging": "{{page}} / {{totalPages}} ページ · 合計 {{total}}件",- "date_dash": "—"- },"return_page": {"redirecting": "ワークスペースの請求ページに戻ります…","load_failed_title": "ワークスペースの請求ページを開けませんでした",diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.jsonindex 2c8933fb41..345716ab18 100644--- a/packages/views/locales/ja/modals.json+++ b/packages/views/locales/ja/modals.json@@ -182,19 +182,6 @@"toast_failed": "タスクを作成できませんでした","toast_duplicate_title": "重複タスク","toast_duplicate_view": "既存のタスクを表示",- "issue_limit": {- "title": "このワークスペースはタスク数の上限に達しました",- "checking_description": "このワークスペースで利用可能な請求操作を確認しています…",- "upgrade_description": "Pro にアップグレードすると、引き続きタスクを作成できます。",- "portal_description": "請求ポータルを開いてワークスペースのサブスクリプションを管理し、タスク作成を再開してください。",- "contact_description": "ワークスペースの所有者または管理者に Pro へのアップグレードを依頼してください。",- "billing_description": "請求設定を開いて、このワークスペースで利用可能なアップグレードオプションを確認してください。",- "billing_unavailable_description": "請求操作を読み込めませんでした。請求設定を開いて再試行してください。",- "billing_disabled_description": "既存のタスクを削除して空きを作るか、ワークスペースの管理者に連絡してください。",- "upgrade_action": "Pro にアップグレード",- "portal_action": "請求ポータルを開く",- "billing_action": "請求設定を表示"- },"autopilot_quota_limit": {"title": "このワークスペースはオートパイロット実行数の上限に達しました","checking_description": "このワークスペースで利用可能な請求操作を確認しています…",diff --git a/packages/views/locales/ko/autopilots.json b/packages/views/locales/ko/autopilots.jsonindex adef8cfba4..9079ee780b 100644--- a/packages/views/locales/ko/autopilots.json+++ b/packages/views/locales/ko/autopilots.json@@ -81,7 +81,6 @@"run_blocked_attribution": "실행되지 않음 — 실행의 책임 구성원을 확인할 수 없습니다","run_blocked_already_active": "실행되지 않음 — 최근 실행이 이미 이 건을 처리했습니다","run_blocked_quota_exceeded": "실행되지 않음 — 이 기간의 실행 한도에 도달했습니다",- "run_blocked_issue_limit_reached": "실행되지 않음 — 워크스페이스가 태스크 수 한도에 도달했습니다","run_blocked_generic": "실행되지 않음 — 실행이 차단되었습니다","section_triggers": "트리거","section_run_history": "실행 기록",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex bef7f6743c..f3a3a0882e 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -1,71 +1,4 @@{- "title": "결제(테스트 페이지)",- "subtitle": "multica-cloud의 /api/v1/billing/*로 직접 전달합니다. 완성된 UI가 아니라 proxy와 Stripe 흐름을 검증하기 위해 모든 endpoint를 한 페이지에 모아둔 것입니다.",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "잔액",- "credits_suffix": "credits",- "meta": "raw micro: {{micro}} · owner: {{owner}}… · updated {{updated}}"- },- "buy": {- "title": "크레딧 구매 / 결제 관리",- "no_tiers": "설정된 가격 tier가 없습니다. Cloud에 Stripe key가 설정되지 않았을 수 있으며 checkout은 503을 반환합니다.",- "tier_money_to_credits": "{{money}} → {{credits}} credits",- "tier_bonus": " + 보너스 {{credits}}",- "tier_bonus_with_expiry": " + 보너스 {{credits}}({{expiry}})",- "tier_id": "id: {{id}}",- "open_portal": "Stripe Billing Portal 열기",- "portal_hint": "아직 결제하지 않은 사용자에게는 400이 예상됩니다(Stripe customer record가 아직 없음).",- "toast_no_url": "Cloud가 checkout URL을 반환하지 않았습니다",- "toast_checkout_failed": "Checkout 실패",- "toast_no_portal_url": "Portal URL이 반환되지 않았습니다",- "toast_portal_failed": "Portal 열기 실패"- },- "checkout": {- "session_label": "Checkout session {{prefix}}…",- "loading": "주문 상태를 불러오는 중…",- "fetch_failed": "상태 조회 실패: {{error}}",- "fetch_failed_unknown": "알 수 없는 오류",- "final_status": "최종 상태: {{status}}",- "polling_status": "상태 확인 중… 현재: {{status}}",- "status_unknown": "unknown",- "label_order": "주문",- "label_tier": "Tier",- "label_charged": "결제됨",- "charged_value": "{{money}} · {{credits}} credits",- "charged_with_bonus": "{{money}} · {{credits}} credits + 보너스 {{bonus}}",- "clear_url": "URL에서 지우기"- },- "transactions": {- "title": "거래 내역",- "empty": "아직 거래 내역이 없습니다.",- "credits_value": "{{value}} credits",- "row_meta": "{{date}} · balance after: {{balance}} credits · ref: {{ref}}",- "ref_empty": "—"- },- "batches": {- "title": "크레딧 batch",- "empty": "아직 batch가 없습니다.",- "remaining_over_total": "{{remaining}} / {{total}} credits",- "id_suffix": "{{id}}…",- "consumed": "사용됨: {{value}} credits",- "expires_suffix": " · 만료 {{value}}",- "never_expires_suffix": " · 만료 없음"- },- "topups": {- "title": "Topup 주문",- "empty": "아직 topup 주문이 없습니다.",- "amount_to_credits": "{{money}} → {{credits}} credits",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} credits + 보너스 {{bonus}}",- "row_meta": "{{date}} · stripe: {{checkout}}",- "stripe_empty": "—"- },"workspace": {"title": "결제 및 요금제","description": "이 워크스페이스의 요금제, 한도, 사용자 좌석 및 Stripe 결제를 관리합니다.",@@ -169,7 +102,6 @@},"limits": {"title": "사용량 및 한도",- "issues": "태스크 수","autopilots": "자동화 실행","unlimited": "무제한","per_month": "월 {{count}}회",@@ -239,12 +171,6 @@"description": "결제 주기: {{interval}}. 현재 사용자 멤버: {{count}}. Stripe가 좌석을 다시 계산하고 결제 전에 최종 금액을 표시합니다."}},- "shared": {- "request_failed": "요청 실패",- "refresh": "새로고침",- "paging": "{{page}} / {{totalPages}} 페이지 · 총 {{total}}개",- "date_dash": "—"- },"return_page": {"redirecting": "워크스페이스 결제 페이지로 돌아갑니다…","load_failed_title": "워크스페이스 결제 페이지를 열 수 없습니다",diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.jsonindex 4d2dc728bc..d008eec970 100644--- a/packages/views/locales/ko/modals.json+++ b/packages/views/locales/ko/modals.json@@ -182,19 +182,6 @@"toast_failed": "태스크를 만들지 못했습니다","toast_duplicate_title": "중복 태스크","toast_duplicate_view": "기존 태스크 보기",- "issue_limit": {- "title": "이 워크스페이스가 태스크 수 한도에 도달했습니다",- "checking_description": "이 워크스페이스에서 사용할 수 있는 결제 작업을 확인하는 중입니다…",- "upgrade_description": "Pro로 업그레이드하면 태스크를 계속 만들 수 있습니다.",- "portal_description": "결제 포털을 열어 이 워크스페이스의 구독을 관리하고 태스크 만들기를 복구하세요.",- "contact_description": "워크스페이스 소유자 또는 관리자에게 Pro 업그레이드를 요청하세요.",- "billing_description": "결제 설정에서 이 워크스페이스에 사용 가능한 업그레이드 옵션을 확인하세요.",- "billing_unavailable_description": "결제 작업을 불러오지 못했습니다. 결제 설정을 열어 다시 시도하세요.",- "billing_disabled_description": "기존 태스크를 삭제해 공간을 확보하거나 워크스페이스 관리자에게 문의하세요.",- "upgrade_action": "Pro로 업그레이드",- "portal_action": "결제 포털 열기",- "billing_action": "결제 설정 보기"- },"autopilot_quota_limit": {"title": "이 워크스페이스가 오토파일럿 실행 한도에 도달했습니다","checking_description": "이 워크스페이스에서 사용할 수 있는 결제 작업을 확인하는 중입니다…",diff --git a/packages/views/locales/ru/autopilots.json b/packages/views/locales/ru/autopilots.jsonindex 424e7cab62..f9dae37581 100644--- a/packages/views/locales/ru/autopilots.json+++ b/packages/views/locales/ru/autopilots.json@@ -79,7 +79,6 @@"run_blocked_attribution": "Не запущен — не удалось определить ответственного участника для запуска","run_blocked_already_active": "Не запущен — недавний запуск уже покрывает это","run_blocked_quota_exceeded": "Не запущен — достигнут лимит запусков за этот период",- "run_blocked_issue_limit_reached": "Не запущен — рабочее пространство достигло лимита задач","run_blocked_generic": "Не запущен — запуск заблокирован","section_triggers": "Триггеры","section_run_history": "История запусков",diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex d128b2eaba..6a31277255 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -1,71 +1,4 @@{- "title": "Биллинг (тестовая страница)",- "subtitle": "Прямая передача в /api/v1/billing/* multica-cloud. Не готовый интерфейс — просто все эндпоинты собраны на одной странице, чтобы проверить прокси и Stripe-флоу.",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "Баланс",- "credits_suffix": "кредитов",- "meta": "raw micro: {{micro}} · владелец: {{owner}}… · обновлено {{updated}}"- },- "buy": {- "title": "Купить кредиты / Управление биллингом",- "no_tiers": "Тарифные планы не настроены. Скорее всего, в Cloud не задан ключ Stripe — checkout вернёт 503.",- "tier_money_to_credits": "{{money}} → {{credits}} кредитов",- "tier_bonus": " + {{credits}} бонус",- "tier_bonus_with_expiry": " + {{credits}} бонус ({{expiry}})",- "tier_id": "id: {{id}}",- "open_portal": "Открыть Stripe Billing Portal",- "portal_hint": "Код 400 ожидаем для пользователей, которые ещё не платили (записи клиента в Stripe не существует).",- "toast_no_url": "Cloud не вернул ссылку на checkout",- "toast_checkout_failed": "Не удалось создать checkout",- "toast_no_portal_url": "Ссылка на портал не получена",- "toast_portal_failed": "Не удалось открыть портал"- },- "checkout": {- "session_label": "Сессия оформления заказа {{prefix}}…",- "loading": "Загрузка статуса заказа…",- "fetch_failed": "Не удалось получить статус: {{error}}",- "fetch_failed_unknown": "неизвестная ошибка",- "final_status": "Итоговый статус: {{status}}",- "polling_status": "Опрос статуса… текущий: {{status}}",- "status_unknown": "неизвестно",- "label_order": "Заказ",- "label_tier": "Тариф",- "label_charged": "Списано",- "charged_value": "{{money}} · {{credits}} кредитов",- "charged_with_bonus": "{{money}} · {{credits}} кредитов + {{bonus}} бонус",- "clear_url": "Очистить URL"- },- "transactions": {- "title": "Транзакции",- "empty": "Пока нет транзакций.",- "credits_value": "{{value}} кредитов",- "row_meta": "{{date}} · баланс после: {{balance}} кредитов · ref: {{ref}}",- "ref_empty": "—"- },- "batches": {- "title": "Пакеты кредитов",- "empty": "Пока нет пакетов.",- "remaining_over_total": "{{remaining}} / {{total}} кредитов",- "id_suffix": "{{id}}…",- "consumed": "Израсходовано: {{value}} кредитов",- "expires_suffix": " · истекает {{value}}",- "never_expires_suffix": " · бессрочно"- },- "topups": {- "title": "Заказы пополнения",- "empty": "Пока нет заказов пополнения.",- "amount_to_credits": "{{money}} → {{credits}} кредитов",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} кредитов + {{bonus}} бонус",- "row_meta": "{{date}} · stripe: {{checkout}}",- "stripe_empty": "—"- },"workspace": {"title": "Биллинг","description": "Управляйте тарифом, лимитами, местами для участников и биллингом Stripe этого рабочего пространства.",@@ -175,7 +108,6 @@},"limits": {"title": "Использование и лимиты",- "issues": "Задачи","autopilots": "Запуски автоматизации","unlimited": "Без ограничений","per_month": "{{count}} / месяц",@@ -260,12 +192,6 @@"description": "Интервал оплаты: {{interval}}. Текущее число участников-людей: {{count}}. Stripe пересчитает места и покажет итоговую сумму перед оплатой."}},- "shared": {- "request_failed": "Запрос не выполнен",- "refresh": "Обновить",- "paging": "страница {{page}} / {{totalPages}} · всего {{total}}",- "date_dash": "—"- },"return_page": {"redirecting": "Возвращаем вас к биллингу рабочего пространства…","load_failed_title": "Не удалось открыть биллинг рабочего пространства",diff --git a/packages/views/locales/ru/modals.json b/packages/views/locales/ru/modals.jsonindex 024c2357f6..3f36233a2e 100644--- a/packages/views/locales/ru/modals.json+++ b/packages/views/locales/ru/modals.json@@ -182,19 +182,6 @@"toast_failed": "Не удалось создать задачу","toast_duplicate_title": "Дублирующаяся задача","toast_duplicate_view": "Открыть существующую задачу",- "issue_limit": {- "title": "Это рабочее пространство достигло лимита задач",- "checking_description": "Проверяем доступные для этого рабочего пространства действия по оплате…",- "upgrade_description": "Перейдите на Pro, чтобы продолжить создавать задачи.",- "portal_description": "Откройте портал биллинга, чтобы управлять подпиской этого рабочего пространства и восстановить создание задач.",- "contact_description": "Попросите владельца или администратора рабочего пространства перейти на Pro.",- "billing_description": "Откройте раздел «Биллинг», чтобы увидеть доступные варианты обновления для этого рабочего пространства.",- "billing_unavailable_description": "Не удалось загрузить действия по оплате. Откройте «Биллинг», чтобы попробовать снова.",- "billing_disabled_description": "Удалите существующую задачу, чтобы освободить место, или обратитесь к администратору рабочего пространства.",- "upgrade_action": "Перейти на Pro",- "portal_action": "Открыть портал биллинга",- "billing_action": "Просмотреть биллинг"- },"autopilot_quota_limit": {"title": "Это рабочее пространство достигло лимита запусков Автопилота","checking_description": "Проверяем доступные для этого рабочего пространства действия по оплате…",diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.jsonindex 2bee06e3dd..da6cbd042a 100644--- a/packages/views/locales/zh-Hans/autopilots.json+++ b/packages/views/locales/zh-Hans/autopilots.json@@ -81,7 +81,6 @@"run_blocked_attribution": "未触发——无法确定本次运行的负责成员","run_blocked_already_active": "未触发——最近已有一次运行覆盖了本次","run_blocked_quota_exceeded": "未触发——本周期的运行额度已用尽",- "run_blocked_issue_limit_reached": "未触发——工作区任务总数已达到上限","run_blocked_generic": "未触发——本次运行已被拦截","section_triggers": "触发器","section_run_history": "运行历史",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex c0b45ea99c..9b284d8811 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -1,71 +1,4 @@{- "title": "账单(测试页)",- "subtitle": "直接透传 multica-cloud 的 /api/v1/billing/*。不是正式 UI——只是把所有端点塞到一个页面方便验证 Stripe 流程。",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "余额",- "credits_suffix": "credits",- "meta": "raw micro: {{micro}} · owner: {{owner}}… · updated {{updated}}"- },- "buy": {- "title": "购买 credits / 管理账单",- "no_tiers": "未配置任何价格档位。Cloud 那边应该没有配 Stripe key——checkout 会返回 503。",- "tier_money_to_credits": "{{money}} → {{credits}} credits",- "tier_bonus": " + 赠送 {{credits}}",- "tier_bonus_with_expiry": " + 赠送 {{credits}}({{expiry}})",- "tier_id": "id: {{id}}",- "open_portal": "打开 Stripe Billing Portal",- "portal_hint": "对于尚未付款的用户预期返回 400(Stripe 还没建 customer 记录)。",- "toast_no_url": "Cloud 没有返回 checkout URL",- "toast_checkout_failed": "Checkout 失败",- "toast_no_portal_url": "没拿到 portal URL",- "toast_portal_failed": "打开 Portal 失败"- },- "checkout": {- "session_label": "Checkout session {{prefix}}…",- "loading": "正在加载订单状态…",- "fetch_failed": "拉取订单状态失败:{{error}}",- "fetch_failed_unknown": "未知错误",- "final_status": "最终状态:{{status}}",- "polling_status": "正在轮询订单状态…当前:{{status}}",- "status_unknown": "unknown",- "label_order": "订单",- "label_tier": "档位",- "label_charged": "已收款",- "charged_value": "{{money}} · {{credits}} credits",- "charged_with_bonus": "{{money}} · {{credits}} credits + {{bonus}} 赠送",- "clear_url": "从 URL 清除"- },- "transactions": {- "title": "流水",- "empty": "暂无流水。",- "credits_value": "{{value}} credits",- "row_meta": "{{date}} · balance after: {{balance}} credits · ref: {{ref}}",- "ref_empty": "—"- },- "batches": {- "title": "Credit 批次",- "empty": "暂无批次。",- "remaining_over_total": "{{remaining}} / {{total}} credits",- "id_suffix": "{{id}}…",- "consumed": "已消耗:{{value}} credits",- "expires_suffix": " · 过期时间 {{value}}",- "never_expires_suffix": " · 永不过期"- },- "topups": {- "title": "充值订单",- "empty": "暂无充值订单。",- "amount_to_credits": "{{money}} → {{credits}} credits",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} credits + {{bonus}} 赠送",- "row_meta": "{{date}} · stripe: {{checkout}}",- "stripe_empty": "—"- },"workspace": {"title": "账单与套餐","description": "管理这个工作区的套餐、限额、成员席位和 Stripe 账单。",@@ -169,7 +102,6 @@},"limits": {"title": "用量与限额",- "issues": "任务数量","autopilots": "自动化执行","unlimited": "不限","per_month": "每月 {{count}} 次",@@ -239,12 +171,6 @@"description": "付款周期:{{interval}}。当前成员:{{count}}。Stripe 会重新统计席位,并在付款前显示最终金额。"}},- "shared": {- "request_failed": "请求失败",- "refresh": "刷新",- "paging": "第 {{page}} / {{totalPages}} 页 · 共 {{total}} 条",- "date_dash": "—"- },"return_page": {"redirecting": "正在返回工作区账单页…","load_failed_title": "无法打开工作区账单页",diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.jsonindex f641660b9b..a605f437cb 100644--- a/packages/views/locales/zh-Hans/modals.json+++ b/packages/views/locales/zh-Hans/modals.json@@ -182,19 +182,6 @@"toast_failed": "创建任务失败","toast_duplicate_title": "已存在同名任务","toast_duplicate_view": "查看已有任务",- "issue_limit": {- "title": "该工作区的任务总数已达到上限",- "checking_description": "正在查询该工作区可用的账单操作…",- "upgrade_description": "升级到 Pro 后可继续创建任务。",- "portal_description": "打开账单门户管理该工作区的订阅,以恢复任务创建。",- "contact_description": "请联系工作区所有者或管理员升级到 Pro。",- "billing_description": "请前往账单设置查看该工作区可用的升级选项。",- "billing_unavailable_description": "暂时无法加载账单操作,请前往账单设置重试。",- "billing_disabled_description": "请删除已有任务以释放名额,或联系工作区管理员。",- "upgrade_action": "升级到 Pro",- "portal_action": "打开账单门户",- "billing_action": "查看账单"- },"autopilot_quota_limit": {"title": "该工作区的自动化执行次数已达到上限","checking_description": "正在查询该工作区可用的账单操作…",diff --git a/packages/views/locales/zh-Hant/autopilots.json b/packages/views/locales/zh-Hant/autopilots.jsonindex 62110ea655..446a2a45e9 100644--- a/packages/views/locales/zh-Hant/autopilots.json+++ b/packages/views/locales/zh-Hant/autopilots.json@@ -81,7 +81,6 @@"run_blocked_attribution": "未觸發——無法確定本次執行的負責成員","run_blocked_already_active": "未觸發——最近已有一次執行覆蓋了本次","run_blocked_quota_exceeded": "未觸發——本週期的執行額度已用盡",- "run_blocked_issue_limit_reached": "未觸發——工作區任務總數已達到上限","run_blocked_generic": "未觸發——本次執行已被攔截","section_triggers": "觸發器","section_run_history": "執行歷史",diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex 0670d7133f..db9969b65b 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -1,71 +1,4 @@{- "title": "帳單(測試頁)",- "subtitle": "直接透傳 multica-cloud 的 /api/v1/billing/*。不是正式 UI——只是把所有端點塞到一個頁面方便驗證 Stripe 流程。",- "endpoints": {- "balance": "GET /api/cloud-billing/balance",- "transactions": "GET /api/cloud-billing/transactions",- "batches": "GET /api/cloud-billing/batches",- "topups": "GET /api/cloud-billing/topups",- "buy": "GET /price-tiers · POST /checkout-sessions · POST /portal-sessions"- },- "balance": {- "title": "餘額",- "credits_suffix": "credits",- "meta": "raw micro: {{micro}} · owner: {{owner}}… · updated {{updated}}"- },- "buy": {- "title": "購買 credits / 管理帳單",- "no_tiers": "未配置任何價格檔位。Cloud 那邊應該沒有配 Stripe key——checkout 會返回 503。",- "tier_money_to_credits": "{{money}} → {{credits}} credits",- "tier_bonus": " + 贈送 {{credits}}",- "tier_bonus_with_expiry": " + 贈送 {{credits}}({{expiry}})",- "tier_id": "id: {{id}}",- "open_portal": "開啟 Stripe Billing Portal",- "portal_hint": "對於尚未付款的使用者預期返回 400(Stripe 還沒建 customer 記錄)。",- "toast_no_url": "Cloud 沒有返回 checkout URL",- "toast_checkout_failed": "Checkout 失敗",- "toast_no_portal_url": "沒拿到 portal URL",- "toast_portal_failed": "開啟 Portal 失敗"- },- "checkout": {- "session_label": "Checkout session {{prefix}}…",- "loading": "正在載入訂單狀態…",- "fetch_failed": "拉取訂單狀態失敗:{{error}}",- "fetch_failed_unknown": "未知錯誤",- "final_status": "最終狀態:{{status}}",- "polling_status": "正在輪詢訂單狀態…當前:{{status}}",- "status_unknown": "unknown",- "label_order": "訂單",- "label_tier": "檔位",- "label_charged": "已收款",- "charged_value": "{{money}} · {{credits}} credits",- "charged_with_bonus": "{{money}} · {{credits}} credits + {{bonus}} 贈送",- "clear_url": "從 URL 清除"- },- "transactions": {- "title": "流水",- "empty": "暫無流水。",- "credits_value": "{{value}} credits",- "row_meta": "{{date}} · balance after: {{balance}} credits · ref: {{ref}}",- "ref_empty": "—"- },- "batches": {- "title": "Credit 批次",- "empty": "暫無批次。",- "remaining_over_total": "{{remaining}} / {{total}} credits",- "id_suffix": "{{id}}…",- "consumed": "已消耗:{{value}} credits",- "expires_suffix": " · 過期時間 {{value}}",- "never_expires_suffix": " · 永不過期"- },- "topups": {- "title": "充值訂單",- "empty": "暫無充值訂單。",- "amount_to_credits": "{{money}} → {{credits}} credits",- "amount_to_credits_with_bonus": "{{money}} → {{credits}} credits + {{bonus}} 贈送",- "row_meta": "{{date}} · stripe: {{checkout}}",- "stripe_empty": "—"- },"workspace": {"title": "帳單與套餐","description": "管理這個工作區的套餐、限額、成員席位和 Stripe 帳單。",@@ -169,7 +102,6 @@},"limits": {"title": "用量與限額",- "issues": "任務數量","autopilots": "自動化執行","unlimited": "不限","per_month": "每月 {{count}} 次",@@ -239,12 +171,6 @@"description": "付款週期:{{interval}}。當前成員:{{count}}。Stripe 會重新統計席位,並在付款前顯示最終金額。"}},- "shared": {- "request_failed": "請求失敗",- "refresh": "重新整理",- "paging": "第 {{page}} / {{totalPages}} 頁 · 共 {{total}} 條",- "date_dash": "—"- },"return_page": {"redirecting": "正在返回工作區帳單頁…","load_failed_title": "無法開啟工作區帳單頁",diff --git a/packages/views/locales/zh-Hant/modals.json b/packages/views/locales/zh-Hant/modals.jsonindex 5cdd0e63a5..0bd63abcb1 100644--- a/packages/views/locales/zh-Hant/modals.json+++ b/packages/views/locales/zh-Hant/modals.json@@ -182,19 +182,6 @@"toast_failed": "建立任務失敗","toast_duplicate_title": "已存在同名任務","toast_duplicate_view": "檢視已有任務",- "issue_limit": {- "title": "該工作區的任務總數已達到上限",- "checking_description": "正在查詢該工作區可用的帳單操作…",- "upgrade_description": "升級到 Pro 後可繼續建立任務。",- "portal_description": "開啟帳單門戶管理該工作區的訂閱,以恢復任務建立。",- "contact_description": "請聯絡工作區所有者或管理員升級到 Pro。",- "billing_description": "請前往帳單設定檢視該工作區可用的升級選項。",- "billing_unavailable_description": "暫時無法載入帳單操作,請前往帳單設定重試。",- "billing_disabled_description": "請刪除已有任務以釋放名額,或聯絡工作區管理員。",- "upgrade_action": "升級到 Pro",- "portal_action": "開啟帳單門戶",- "billing_action": "檢視帳單"- },"autopilot_quota_limit": {"title": "該工作區的自動化執行次數已達到上限","checking_description": "正在查詢該工作區可用的帳單操作…",diff --git a/packages/views/modals/create-issue-batch-continuation.test.tsx b/packages/views/modals/create-issue-batch-continuation.test.tsxindex 1c40f2f1c0..9889a37c91 100644--- a/packages/views/modals/create-issue-batch-continuation.test.tsx+++ b/packages/views/modals/create-issue-batch-continuation.test.tsx@@ -110,10 +110,6 @@ vi.mock("@multica/core/auth", () => {};});-vi.mock("./use-issue-limit-upgrade-prompt", () => ({- useIssueLimitUpgradePrompt: () => vi.fn(),-}));-vi.mock("@multica/core/issues/queries", () => ({issueDetailOptions: (wsId: string, id: string) => ({queryKey: ["issues", wsId, "detail", id],diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsxindex 81f9d023cb..a1cd92b930 100644--- a/packages/views/modals/create-issue.test.tsx+++ b/packages/views/modals/create-issue.test.tsx@@ -62,7 +62,6 @@ const mockSetKeepOpen = vi.hoisted(() => vi.fn());const mockToastCustom = vi.hoisted(() => vi.fn());const mockToastDismiss = vi.hoisted(() => vi.fn());const mockToastError = vi.hoisted(() => vi.fn());-const mockShowIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());// Uploads flow through the module-level coordinator, which calls// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2). Tests drive uploads by// mocking that call; it resolves a plain server Attachment row.@@ -238,10 +237,6 @@ vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-test",}));-vi.mock("./use-issue-limit-upgrade-prompt", () => ({- useIssueLimitUpgradePrompt: () => mockShowIssueLimitUpgradePrompt,-}));-vi.mock("@multica/core/issues/queries", () => ({issueDetailOptions: (wsId: string, id: string) => ({queryKey: ["issues", wsId, "detail", id],@@ -1632,29 +1627,6 @@ describe("CreateIssueModal", () => {expect(mockToastCustom).not.toHaveBeenCalled();});- it("offers the Cloud-authorized upgrade recovery when manual create reaches the issue limit", async () => {- const user = userEvent.setup();- const onClose = vi.fn();- mockCreateIssue.mockRejectedValue(- new ApiError("workspace has reached its issue limit", 402, "Payment Required", {- code: "issue_limit_reached",- limit: 1000,- policy_revision: 1,- }),- );-- renderModal(<CreateIssueModal onClose={onClose} />);- await user.type(screen.getByPlaceholderText("Issue title"), "One more issue");- await user.click(screen.getByRole("button", { name: "Create Issue" }));-- await waitFor(() => {- expect(mockShowIssueLimitUpgradePrompt).toHaveBeenCalledTimes(1);- });- expect(mockToastError).not.toHaveBeenCalled();- expect(mockClearDraft).not.toHaveBeenCalled();- expect(onClose).not.toHaveBeenCalled();- });-// Non-409 errors with a real message: surface the backend reason rather// than the generic i18n fallback. This is the whole point of the issue.it("surfaces err.message verbatim for non-duplicate errors", async () => {diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsxindex d37d55e86d..0f5fb38524 100644--- a/packages/views/modals/create-issue.tsx+++ b/packages/views/modals/create-issue.tsx@@ -101,7 +101,6 @@ import {import { IssuePickerModal } from "./issue-picker-modal";import { useT } from "../i18n";import { SourceContextPreviewCard, useSourceContextFailureMessage } from "./source-context-preview";-import { useIssueLimitUpgradePrompt } from "./use-issue-limit-upgrade-prompt";import { CopyParentFields } from "./copy-parent-fields";// ManualCreatePanel — manual-mode body of the create-issue dialog. Renders@@ -258,7 +257,6 @@ export function ManualCreatePanel({: undefined;const onSourceContextExpandedChange = data?.source_context_on_expanded_change as ((expanded: boolean) => void) | undefined;const sourceContextFailureMessage = useSourceContextFailureMessage();- const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();const draft = useIssueDraftStore((s) => s.draft);const setManual = useIssueDraftStore((s) => s.setManual);@@ -719,10 +717,6 @@ export function ManualCreatePanel({toast.error(sourceContextFailureMessage(err) ?? tIssues(($) => $.source_context.error_too_large));return false;}- if (sourceCode === "issue_limit_reached") {- showIssueLimitUpgradePrompt();- return false;- }if (sourceCode === "invalid_issue_property" && err instanceof ApiError) {const propertyId =err.body && typeof err.body === "object"diff --git a/packages/views/modals/issue-limit-upgrade-dialog.test.tsx b/packages/views/modals/limit-recovery-dialog.test.tsxsimilarity index 82%rename from packages/views/modals/issue-limit-upgrade-dialog.test.tsxrename to packages/views/modals/limit-recovery-dialog.test.tsxindex db589be4e4..cb226fd972 100644--- a/packages/views/modals/issue-limit-upgrade-dialog.test.tsx+++ b/packages/views/modals/limit-recovery-dialog.test.tsx@@ -70,8 +70,8 @@ vi.mock("@multica/core/billing", () => ({}),}));-import { IssueLimitUpgradeDialog } from "./issue-limit-upgrade-dialog";-import { useIssueLimitUpgradePrompt } from "./use-issue-limit-upgrade-prompt";+import { LimitRecoveryDialog } from "./limit-recovery-dialog";+import { useLimitRecoveryPrompt } from "./use-limit-recovery-prompt";const TEST_RESOURCES = {en: { common: enCommon, modals: enModals },@@ -87,33 +87,33 @@ const actions = (});function PromptHarness() {- const showPrompt = useIssueLimitUpgradePrompt();+ const showPrompt = useLimitRecoveryPrompt("autopilot_quota");return (<><button type="button" onClick={showPrompt}>Show recovery</button>- <IssueLimitUpgradeDialog />+ <LimitRecoveryDialog /></>);}function LayeredPromptHarness() {- const [createOpen, setCreateOpen] = useState(true);- const showPrompt = useIssueLimitUpgradePrompt();+ const [underlyingOpen, setUnderlyingOpen] = useState(true);+ const showPrompt = useLimitRecoveryPrompt("autopilot_quota");return (<>- <Dialog open={createOpen} onOpenChange={setCreateOpen}>+ <Dialog open={underlyingOpen} onOpenChange={setUnderlyingOpen}><DialogContent showCloseButton={false}>- <DialogTitle>Create an issue</DialogTitle>- <DialogDescription>Your draft remains here.</DialogDescription>+ <DialogTitle>Underlying dialog</DialogTitle>+ <DialogDescription>It stays open below recovery.</DialogDescription><button type="button" onClick={showPrompt}>Show recovery</button></DialogContent></Dialog>- <IssueLimitUpgradeDialog />+ <LimitRecoveryDialog /></>);}@@ -144,11 +144,11 @@ async function openPrompt() {function queryRecoveryDialog() {return screen.queryByRole("dialog", {- name: "This workspace has reached its issue limit",+ name: "This workspace has reached its autopilot run limit",});}-describe("IssueLimitUpgradeDialog", () => {+describe("LimitRecoveryDialog", () => {beforeEach(() => {vi.clearAllMocks();featureState.billingEnabled = true;@@ -159,8 +159,8 @@ describe("IssueLimitUpgradeDialog", () => {useModalStore.setState({modal: null,data: null,- issueLimitRecoveryWorkspaceId: null,- issueLimitRecoveryReason: "issue_limit",+ limitRecoveryWorkspaceId: null,+ limitRecoveryReason: "autopilot_quota",});mockSummaryQuery.mockImplementation(async () => {if (summaryState.pending) return summaryState.pending;@@ -177,8 +177,8 @@ describe("IssueLimitUpgradeDialog", () => {useModalStore.setState({modal: null,data: null,- issueLimitRecoveryWorkspaceId: null,- issueLimitRecoveryReason: "issue_limit",+ limitRecoveryWorkspaceId: null,+ limitRecoveryReason: "autopilot_quota",});});@@ -199,14 +199,14 @@ describe("IssueLimitUpgradeDialog", () => {expect(screen.getAllByRole("button", { name: "Close" })).toHaveLength(1);});- it("uses autopilot-specific copy when Inbox opens the shared recovery surface", async () => {+ it("opens and dismisses through the modal store", async () => {summaryState.value = { availableActions: actions({ checkout: true }) };renderPrompt();act(() => {useModalStore.getState()- .showIssueLimitRecovery("ws-test", "autopilot_quota");+ .showLimitRecovery("ws-test", "autopilot_quota");});expect(@@ -218,7 +218,7 @@ describe("IssueLimitUpgradeDialog", () => {await screen.findByText("Upgrade to Pro to restore autopilot runs."),).toBeInTheDocument();- act(() => useModalStore.getState().dismissIssueLimitRecovery());+ act(() => useModalStore.getState().dismissLimitRecovery());await waitFor(() => {expect(screen.queryByRole("dialog", {@@ -228,7 +228,7 @@ describe("IssueLimitUpgradeDialog", () => {});});- it("closes only recovery when Escape is pressed above a create dialog", async () => {+ it("closes only recovery when Escape is pressed above another dialog", async () => {summaryState.value = { availableActions: actions({ checkout: true }) };renderPrompt({ layered: true });const user = await openPrompt();@@ -237,7 +237,7 @@ describe("IssueLimitUpgradeDialog", () => {await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());expect(- screen.getByRole("dialog", { name: "Create an issue" }),+ screen.getByRole("dialog", { name: "Underlying dialog" }),).toBeInTheDocument();});@@ -254,7 +254,7 @@ describe("IssueLimitUpgradeDialog", () => {await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());expect(- screen.getByRole("dialog", { name: "Create an issue" }),+ screen.getByRole("dialog", { name: "Underlying dialog" }),).toBeInTheDocument();});@@ -279,17 +279,6 @@ describe("IssueLimitUpgradeDialog", () => {expect(queryRecoveryDialog()).not.toBeInTheDocument();});- it("keeps the create modal open when recovery is merely dismissed", async () => {- summaryState.value = { availableActions: actions({ checkout: true }) };- useModalStore.getState().open("create-issue");- renderPrompt();- const user = await openPrompt();-- await user.click(screen.getByRole("button", { name: "Close" }));-- expect(useModalStore.getState().modal).toBe("create-issue");- });-it("dismisses recovery instead of carrying it into another workspace", async () => {summaryState.value = { availableActions: actions({ checkout: true }) };const { client, rerender } = renderPrompt();@@ -300,7 +289,7 @@ describe("IssueLimitUpgradeDialog", () => {await waitFor(() => {expect(- useModalStore.getState().issueLimitRecoveryWorkspaceId,+ useModalStore.getState().limitRecoveryWorkspaceId,).toBeNull();});expect(queryRecoveryDialog()).not.toBeInTheDocument();@@ -308,7 +297,6 @@ describe("IssueLimitUpgradeDialog", () => {it("offers Upgrade to Pro only when Cloud authorizes checkout", async () => {summaryState.value = { availableActions: actions({ checkout: true }) };- useModalStore.getState().open("create-issue");renderPrompt();const user = await openPrompt();@@ -316,14 +304,12 @@ describe("IssueLimitUpgradeDialog", () => {await screen.findByRole("button", { name: "Upgrade to Pro" }),);- expect(useModalStore.getState().modal).toBeNull();expect(mockPush).toHaveBeenCalledWith("/ws-test/settings?tab=billing");await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());});it("opens Billing Portal for a past-due manager authorized for portal", async () => {summaryState.value = { availableActions: actions({ portal: true }) };- useModalStore.getState().open("quick-create-issue");renderPrompt();const user = await openPrompt();@@ -333,7 +319,7 @@ describe("IssueLimitUpgradeDialog", () => {await waitFor(() => expect(mockCreatePortal).toHaveBeenCalledTimes(1));expect(mockCreatePortal.mock.calls[0]?.[0]).toMatch(- /^issue-limit-portal-ws-test-/,+ /^limit-recovery-portal-ws-test-/,);await waitFor(() => {expect(mockOpenExternal).toHaveBeenCalledWith(@@ -341,12 +327,11 @@ describe("IssueLimitUpgradeDialog", () => {{ webTarget: "same-tab" },);});- expect(useModalStore.getState().modal).toBeNull();+ await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());});it("keeps a Billing recovery action when Portal cannot be opened", async () => {summaryState.value = { availableActions: actions({ portal: true }) };- useModalStore.getState().open("create-issue");mockCreatePortal.mockRejectedValue(new Error("portal unavailable"));renderPrompt();const user = await openPrompt();@@ -358,7 +343,6 @@ describe("IssueLimitUpgradeDialog", () => {expect(await screen.findByRole("button", { name: "View Billing" }),).toBeInTheDocument();- expect(useModalStore.getState().modal).toBe("create-issue");expect(queryRecoveryDialog()).toBeInTheDocument();});@@ -409,7 +393,7 @@ describe("IssueLimitUpgradeDialog", () => {expect(screen.getByText(- "Delete an existing issue to free space, or contact your workspace administrator.",+ "Wait for the current allowance to reset, or contact your workspace administrator.",),).toBeInTheDocument();expect(diff --git a/packages/views/modals/issue-limit-upgrade-dialog.tsx b/packages/views/modals/limit-recovery-dialog.tsxsimilarity index 71%rename from packages/views/modals/issue-limit-upgrade-dialog.tsxrename to packages/views/modals/limit-recovery-dialog.tsxindex 4bd68c48fe..01617f5970 100644--- a/packages/views/modals/issue-limit-upgrade-dialog.tsx+++ b/packages/views/modals/limit-recovery-dialog.tsx@@ -13,7 +13,7 @@ import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flagimport { useWorkspaceId } from "@multica/core/hooks";import {useModalStore,- type IssueLimitRecoveryReason,+ type LimitRecoveryReason,} from "@multica/core/modals";import { useWorkspacePaths } from "@multica/core/paths";import type { WorkspaceSubscriptionSummary } from "@multica/core/types";@@ -37,22 +37,22 @@ function createPortalIdempotencyKey(wsId: string): string {const suffix =globalThis.crypto?.randomUUID?.() ??`${Date.now()}-${Math.random().toString(36).slice(2)}`;- return `issue-limit-portal-${wsId}-${suffix}`.slice(0, 255);+ return `limit-recovery-portal-${wsId}-${suffix}`.slice(0, 255);}/**- * Centered recovery surface shared by manual create, Quick Create, and quota+ * Centered recovery surface for Cloud-enforced limits, opened from quota* notices in Inbox. The modal reason changes copy, never authorization.* Cloud's complete action set is the only input that decides which billing* action appears; no local role, plan, subscription, or quota inference does.*/-export function IssueLimitUpgradeDialog() {+export function LimitRecoveryDialog() {const recoveryWorkspaceId = useModalStore(- (state) => state.issueLimitRecoveryWorkspaceId,+ (state) => state.limitRecoveryWorkspaceId,);- const dismiss = useModalStore((state) => state.dismissIssueLimitRecovery);+ const dismiss = useModalStore((state) => state.dismissLimitRecovery);const recoveryReason = useModalStore(- (state) => state.issueLimitRecoveryReason,+ (state) => state.limitRecoveryReason,);const { t } = useT("modals");const wsId = useWorkspaceId();@@ -88,21 +88,8 @@ export function IssueLimitUpgradeDialog() {setPortalFailed(false);}, [visible, wsId]);- const closeForBillingAction = () => {- dismiss();-- // Recovery can also open from Inbox. Only close an underlying issue-create- // modal when following its billing action; leave every other modal alone.- const modalStore = useModalStore.getState();- if (- modalStore.modal === "create-issue" ||- modalStore.modal === "quick-create-issue"- ) {- modalStore.close();- }- };const openBilling = () => {- closeForBillingAction();+ dismiss();navigation.push(`${paths.settings()}?tab=billing`);};const openPortal = async () => {@@ -117,7 +104,7 @@ export function IssueLimitUpgradeDialog() {return;}portalIntentKeyRef.current = null;- closeForBillingAction();+ dismiss();openExternal(response.url, { webTarget: "same-tab" });} catch {setPortalFailed(true);@@ -220,72 +207,46 @@ interface RecoveryCopy {function getRecoveryCopy(t: ModalsT,- reason: IssueLimitRecoveryReason,+ reason: LimitRecoveryReason,): RecoveryCopy {- if (reason === "autopilot_quota") {- return {- title: t(($) => $.create_issue.autopilot_quota_limit.title),- billingDisabledDescription: t(- ($) =>- $.create_issue.autopilot_quota_limit.billing_disabled_description,- ),- upgradeDescription: t(- ($) => $.create_issue.autopilot_quota_limit.upgrade_description,- ),- portalDescription: t(- ($) => $.create_issue.autopilot_quota_limit.portal_description,- ),- contactDescription: t(- ($) => $.create_issue.autopilot_quota_limit.contact_description,- ),- billingDescription: t(- ($) => $.create_issue.autopilot_quota_limit.billing_description,- ),- billingUnavailableDescription: t(- ($) =>- $.create_issue.autopilot_quota_limit.billing_unavailable_description,- ),- checkingDescription: t(- ($) => $.create_issue.autopilot_quota_limit.checking_description,- ),- upgradeAction: t(- ($) => $.create_issue.autopilot_quota_limit.upgrade_action,- ),- portalAction: t(- ($) => $.create_issue.autopilot_quota_limit.portal_action,- ),- billingAction: t(- ($) => $.create_issue.autopilot_quota_limit.billing_action,- ),- };+ switch (reason) {+ case "autopilot_quota":+ return {+ title: t(($) => $.create_issue.autopilot_quota_limit.title),+ billingDisabledDescription: t(+ ($) =>+ $.create_issue.autopilot_quota_limit.billing_disabled_description,+ ),+ upgradeDescription: t(+ ($) => $.create_issue.autopilot_quota_limit.upgrade_description,+ ),+ portalDescription: t(+ ($) => $.create_issue.autopilot_quota_limit.portal_description,+ ),+ contactDescription: t(+ ($) => $.create_issue.autopilot_quota_limit.contact_description,+ ),+ billingDescription: t(+ ($) => $.create_issue.autopilot_quota_limit.billing_description,+ ),+ billingUnavailableDescription: t(+ ($) =>+ $.create_issue.autopilot_quota_limit.billing_unavailable_description,+ ),+ checkingDescription: t(+ ($) => $.create_issue.autopilot_quota_limit.checking_description,+ ),+ upgradeAction: t(+ ($) => $.create_issue.autopilot_quota_limit.upgrade_action,+ ),+ portalAction: t(+ ($) => $.create_issue.autopilot_quota_limit.portal_action,+ ),+ billingAction: t(+ ($) => $.create_issue.autopilot_quota_limit.billing_action,+ ),+ };}- return {- title: t(($) => $.create_issue.issue_limit.title),- billingDisabledDescription: t(- ($) => $.create_issue.issue_limit.billing_disabled_description,- ),- upgradeDescription: t(- ($) => $.create_issue.issue_limit.upgrade_description,- ),- portalDescription: t(- ($) => $.create_issue.issue_limit.portal_description,- ),- contactDescription: t(- ($) => $.create_issue.issue_limit.contact_description,- ),- billingDescription: t(- ($) => $.create_issue.issue_limit.billing_description,- ),- billingUnavailableDescription: t(- ($) => $.create_issue.issue_limit.billing_unavailable_description,- ),- checkingDescription: t(- ($) => $.create_issue.issue_limit.checking_description,- ),- upgradeAction: t(($) => $.create_issue.issue_limit.upgrade_action),- portalAction: t(($) => $.create_issue.issue_limit.portal_action),- billingAction: t(($) => $.create_issue.issue_limit.billing_action),- };}function resolveRecoveryPresentation({diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsxindex 4d58c7c87c..fe02d246fb 100644--- a/packages/views/modals/quick-create-issue.test.tsx+++ b/packages/views/modals/quick-create-issue.test.tsx@@ -30,7 +30,6 @@ const mockSetQuickCreateFieldVisible = vi.hoisted(() => vi.fn());const mockSetKeepOpen = vi.hoisted(() => vi.fn());const mockSetLastMode = vi.hoisted(() => vi.fn());const mockToastSuccess = vi.hoisted(() => vi.fn());-const mockShowIssueLimitUpgradePrompt = vi.hoisted(() => vi.fn());// Uploads flow through the module-level coordinator, which calls// `api.uploadFile(file, ctx, signal)` (MUL-5181 L2).const mockApiUploadFile = vi.hoisted(() => vi.fn());@@ -206,10 +205,6 @@ vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-test",}));-vi.mock("./use-issue-limit-upgrade-prompt", () => ({- useIssueLimitUpgradePrompt: () => mockShowIssueLimitUpgradePrompt,-}));-vi.mock("@multica/core/paths", () => ({useCurrentWorkspace: () => ({ name: "Test Workspace" }),useWorkspacePaths: () => ({@@ -718,28 +713,6 @@ describe("AgentCreatePanel", () => {});});- it("shows the upgrade recovery immediately when quick create is rejected by the issue preflight", async () => {- const user = userEvent.setup();- const onClose = vi.fn();- mockQuickCreateIssue.mockRejectedValue(- new ApiError("workspace has reached its issue limit", 402, "Payment Required", {- code: "issue_limit_reached",- limit: 1000,- policy_revision: 1,- }),- );-- renderPanel({ onClose, isExpanded: false, setIsExpanded: vi.fn() });- await user.click(screen.getByRole("button", { name: /^Create$/i }));-- await waitFor(() => {- expect(mockShowIssueLimitUpgradePrompt).toHaveBeenCalledTimes(1);- });- expect(mockToastSuccess).not.toHaveBeenCalled();- expect(mockClearDraft).not.toHaveBeenCalled();- expect(onClose).not.toHaveBeenCalled();- });-it("reveals optional fields from the overflow and submits their values", async () => {const user = userEvent.setup();diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsxindex a05cd49130..6bbeaa452e 100644--- a/packages/views/modals/quick-create-issue.tsx+++ b/packages/views/modals/quick-create-issue.tsx@@ -89,7 +89,6 @@ import { FileUploadButton } from "@multica/ui/components/common/file-upload-buttimport { useT } from "../i18n";import { matchesPinyin } from "../editor/extensions/pinyin-match";import { SourceContextPreviewCard, useSourceContextFailureMessage } from "./source-context-preview";-import { useIssueLimitUpgradePrompt } from "./use-issue-limit-upgrade-prompt";type ActorSelection =| { type: "agent"; id: string }@@ -141,7 +140,6 @@ export function AgentCreatePanel({: undefined;const onSourceContextExpandedChange = data?.source_context_on_expanded_change as ((expanded: boolean) => void) | undefined;const sourceContextFailureMessage = useSourceContextFailureMessage();- const showIssueLimitUpgradePrompt = useIssueLimitUpgradePrompt();const userId = useAuthStore((s) => s.user?.id);const { data: members = [] } = useQuery(memberListOptions(wsId));const { data: agents = [] } = useQuery(agentListOptions(wsId));@@ -509,10 +507,6 @@ export function AgentCreatePanel({current_version?: string;min_version?: string;};- if (body.code === "issue_limit_reached") {- showIssueLimitUpgradePrompt();- return false;- }if (body.code === "agent_unavailable") {setError(body.reason || t(($) => $.create_issue.agent.error_agent_unavailable_fallback));return false;diff --git a/packages/views/modals/registry.tsx b/packages/views/modals/registry.tsxindex 9d32ad4fc6..803e0e4ff2 100644--- a/packages/views/modals/registry.tsx+++ b/packages/views/modals/registry.tsx@@ -15,7 +15,7 @@ import { RenameProjectModal } from "./rename-project";import { DeleteIssueConfirmModal } from "./delete-issue-confirm";import { RunConfirmModal } from "./run-confirm";import { WorkflowHandoffModal } from "./workflow-handoff";-import { IssueLimitUpgradeDialog } from "./issue-limit-upgrade-dialog";+import { LimitRecoveryDialog } from "./limit-recovery-dialog";export function ModalRegistry() {const modal = useModalStore((s) => s.modal);@@ -85,7 +85,7 @@ export function ModalRegistry() {return (<>{activeModal}- <IssueLimitUpgradeDialog />+ <LimitRecoveryDialog /></>);}diff --git a/packages/views/modals/use-issue-limit-upgrade-prompt.ts b/packages/views/modals/use-limit-recovery-prompt.tssimilarity index 64%rename from packages/views/modals/use-issue-limit-upgrade-prompt.tsrename to packages/views/modals/use-limit-recovery-prompt.tsindex 44b67b64e5..8f4f71d341 100644--- a/packages/views/modals/use-issue-limit-upgrade-prompt.ts+++ b/packages/views/modals/use-limit-recovery-prompt.ts@@ -4,16 +4,16 @@ import { useCallback } from "react";import { useWorkspaceId } from "@multica/core/hooks";import {useModalStore,- type IssueLimitRecoveryReason,+ type LimitRecoveryReason,} from "@multica/core/modals";/** Opens the shared limit-recovery dialog without closing the current surface. */-export function useIssueLimitUpgradePrompt(- reason: IssueLimitRecoveryReason = "issue_limit",+export function useLimitRecoveryPrompt(+ reason: LimitRecoveryReason,): () => void {const wsId = useWorkspaceId();return useCallback(() => {- useModalStore.getState().showIssueLimitRecovery(wsId, reason);+ useModalStore.getState().showLimitRecovery(wsId, reason);}, [reason, wsId]);}diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.tsindex 64d1091883..b4c3ecb5ed 100644--- a/packages/views/settings/components/billing-state.test.ts+++ b/packages/views/settings/components/billing-state.test.ts@@ -17,7 +17,6 @@ const freeEntitlements: WorkspaceSubscriptionEntitlements = {status: "inactive",seats: 3,limits: {- issueCount: { mode: "limited", limit: 17 },autopilotRuns: { mode: "limited", limit: 7 },},currentPeriodEnd: null,diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex 641b37ae72..3ca3c1fc4d 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -6,7 +6,6 @@ import { configStore } from "@multica/core/config";import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";import type {AutopilotQuotaUsage,- IssueLimitUsage,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,} from "@multica/core/types";@@ -21,7 +20,6 @@ const mocks = vi.hoisted(() => ({refetch: vi.fn(),refetchSummary: vi.fn(),refetchUsage: vi.fn(),- refetchIssueLimitUsage: vi.fn(),refetchPrices: vi.fn(),openExternal: vi.fn(),workspaceId: "workspace-1",@@ -58,7 +56,6 @@ const mocks = vi.hoisted(() => ({status: "inactive",seats: 3,limits: {- issueCount: { mode: "limited", limit: 17 },autopilotRuns: { mode: "limited", limit: 7 },},currentPeriodEnd: null as string | null,@@ -92,10 +89,6 @@ const mocks = vi.hoisted(() => ({purchaseSeats: false,},} as WorkspaceSubscriptionSummary,- issueLimitUsage: {- used: 11,- limit: 17,- } as IssueLimitUsage,usage: {action: "enforce" as "off" | "observe" | "enforce",used: 3 as number | null,@@ -121,9 +114,6 @@ vi.mock("@multica/core/billing", () => ({workspaceSubscriptionSummaryOptions: (wsId: string) => ({queryKey: ["workspace-subscriptions", wsId, "summary"],}),- issueLimitUsageOptions: (wsId: string) => ({- queryKey: ["workspace-subscriptions", wsId, "issue-limit-usage"],- }),useCreateWorkspaceSubscriptionCheckout: () => ({mutateAsync: mocks.checkout,isPending: false,@@ -264,7 +254,6 @@ describe("BillingTab", () => {status: "inactive",seats: 3,limits: {- issueCount: { mode: "limited", limit: 17 },autopilotRuns: { mode: "limited", limit: 7 },},currentPeriodEnd: null,@@ -285,10 +274,6 @@ describe("BillingTab", () => {purchaseSeats: false,},});- Object.assign(mocks.issueLimitUsage, {- used: 11,- limit: 17,- });Object.assign(mocks.usage, {action: "enforce",used: 3,@@ -327,15 +312,6 @@ describe("BillingTab", () => {refetch: mocks.refetchSummary,};}- if (queryKey?.[queryKey.length - 1] === "issue-limit-usage") {- return {- data: mocks.issueLimitUsage,- isPending: false,- isFetching: false,- isError: false,- refetch: mocks.refetchIssueLimitUsage,- };- }if (queryKey?.[queryKey.length - 1] === "usage") {return {data: mocks.usageError ? undefined : mocks.usage,@@ -400,7 +376,6 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);expect(screen.getByRole("heading", { name: "Billing" })).toBeInTheDocument();- expect(screen.getByText("11 / 17")).toBeInTheDocument();expect(screen.getByText("5 / 7")).toBeInTheDocument();expect(screen.getByText("3 completed · 2 in progress")).toBeInTheDocument();expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();@@ -703,7 +678,6 @@ describe("BillingTab", () => {).toBeInTheDocument();expect(screen.queryByText("Pro is active")).not.toBeInTheDocument();expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();- expect(screen.getByText("11 / 17")).toBeInTheDocument();expect(screen.getByText("5 / 7")).toBeInTheDocument();const summaryOptions = mocks.useQuery.mock.calls.map(([options]) => options)@@ -727,7 +701,6 @@ describe("BillingTab", () => {plan: "pro",status: "active",limits: {- issueCount: { mode: "unlimited", limit: null },autopilotRuns: { mode: "unlimited", limit: null },},});@@ -738,7 +711,7 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);expect(screen.getByText("Pro is active")).toBeInTheDocument();- expect(screen.getAllByText("Unlimited")).toHaveLength(2);+ expect(screen.getByText("Unlimited")).toBeInTheDocument();expect(screen.queryByText("5 / 7")).not.toBeInTheDocument();} finally {vi.useRealTimers();@@ -1342,7 +1315,6 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();- expect(screen.getByText("11 / 17")).toBeInTheDocument();expect(screen.getByText("5 / 7")).toBeInTheDocument();expect(screen.getByText(@@ -1389,7 +1361,6 @@ describe("BillingTab", () => {plan: "pro",status: "active",limits: {- issueCount: { mode: "unlimited", limit: null },autopilotRuns: { mode: "unlimited", limit: null },},currentPeriodEnd: "2026-09-13T00:00:00Z",@@ -1403,7 +1374,7 @@ describe("BillingTab", () => {expect(screen.getByRole("button", { name: "Manage billing" }),).toBeInTheDocument();- expect(screen.getAllByText("Unlimited")).toHaveLength(2);+ expect(screen.getByText("Unlimited")).toBeInTheDocument();expect(screen.queryByText("5 / 7")).not.toBeInTheDocument();expect(screen.queryByRole("button", { name: "Upgrade to Pro" }),diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 3a67492bd2..3e0f9b6407 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -19,7 +19,6 @@ import {useCreateWorkspaceSubscriptionPortal,usePreviewWorkspaceSeatPurchase,usePurchaseWorkspaceSeats,- issueLimitUsageOptions,workspaceSubscriptionPricesOptions,workspaceSubscriptionSummaryOptions,} from "@multica/core/billing";@@ -334,12 +333,6 @@ function BillingTabContent() {summaryQuery.isError ||(!summaryQuery.isPending && summaryQuery.data == null);const quotaUsageQuery = useQuery(autopilotQuotaUsageOptions(wsId));- const issueLimitUsageQuery = useQuery({- ...issueLimitUsageOptions(wsId),- enabled:- wsId.length > 0 &&- entitlements?.limits.issueCount.mode === "limited",- });const hasSeatCapacity = hasActiveWorkspaceSeatCapacity(summaryQuery.data);const canUpgrade = summaryQuery.data?.availableActions.checkout === true;const pricesQuery = useQuery({@@ -820,14 +813,6 @@ function BillingTabContent() {? formatDateTime(quotaUsage.resetAt, locale): null;const numberFormatter = new Intl.NumberFormat(locale);- const issueCountLimit = entitlements.limits.issueCount;- const issueLimitUsage = issueLimitUsageQuery.data;- const issueLimitValue =- issueCountLimit.mode === "unlimited"- ? t(($) => $.workspace.limits.unlimited)- : issueLimitUsage?.limit === issueCountLimit.limit- ? `${numberFormatter.format(issueLimitUsage.used)} / ${numberFormatter.format(issueLimitUsage.limit)}`- : numberFormatter.format(issueCountLimit.limit);const isMutating =checkoutMutation.isPending ||portalMutation.isPending ||@@ -1197,11 +1182,6 @@ function BillingTabContent() {title={t(($) => $.workspace.limits.title)}><SettingsCard>- <SettingsRow- label={t(($) => $.workspace.limits.issues)}- >- <span className="tabular-nums">{issueLimitValue}</span>- </SettingsRow><SettingsRowlabel={t(($) => $.workspace.limits.autopilots)}>diff --git a/packages/views/settings/components/seat-invite-purchase.test.ts b/packages/views/settings/components/seat-invite-purchase.test.tsindex 6f64b388f6..e1ed6906b3 100644--- a/packages/views/settings/components/seat-invite-purchase.test.ts+++ b/packages/views/settings/components/seat-invite-purchase.test.ts@@ -33,7 +33,6 @@ function summary(purchased: number, available: number): WorkspaceSubscriptionSumstatus: "active",seats: purchased,limits: {- issueCount: { mode: "unlimited", limit: null },autopilotRuns: { mode: "unlimited", limit: null },},currentPeriodEnd: null,diff --git a/packages/views/test/shard-timings.json b/packages/views/test/shard-timings.jsonindex 12ad273718..a819ea7ea2 100644--- a/packages/views/test/shard-timings.json+++ b/packages/views/test/shard-timings.json@@ -427,7 +427,7 @@"modals/create-squad.test.tsx": 1362,"modals/delete-issue-confirm.test.tsx": 928,"modals/feedback.test.tsx": 1002,- "modals/issue-limit-upgrade-dialog.test.tsx": 1236,+ "modals/limit-recovery-dialog.test.tsx": 1236,"modals/issue-parent-modals.test.tsx": 736,"modals/issue-picker-modal.test.tsx": 1797,"modals/mark-duplicate-issue.test.tsx": 3588,diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f6144f9023..548b8abc03 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -479,8 +479,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busopts.BusinessMetrics.RecordEntitlementConfigError()} else if entitlementClient.Enabled() {h.Entitlements = entitlementClient- h.TaskService.Entitlements = entitlementClient- h.IssueService.Entitlements = entitlementClienth.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics}@@ -2164,7 +2162,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Issuesr.Route("/api/issues", func(r chi.Router) {- r.Get("/limit-usage", h.GetIssueLimitUsage)r.Post("/table/groups", h.ListIssueTableGroups)r.Post("/table/rows", h.ListIssueTableRows)r.Post("/table/facets", h.ListIssueTableFacets)diff --git a/server/internal/dispatch/reason.go b/server/internal/dispatch/reason.goindex e8a3d54099..04189b0f73 100644--- a/server/internal/dispatch/reason.go+++ b/server/internal/dispatch/reason.go@@ -96,9 +96,6 @@ const (// ReasonQuotaExceeded is a policy-neutral refusal for an exhausted// Cloud-provided autopilot interval.ReasonQuotaExceeded ReasonCode = "quota_exceeded"- // ReasonIssueLimitReached means a create_issue Autopilot was admitted for a- // run, but Cloud's effective workspace issue-count limit blocked the issue.- ReasonIssueLimitReached ReasonCode = "issue_limit_reached"// ReasonInternalError: an unexpected server error prevented a clean decision.ReasonInternalError ReasonCode = "internal_error")diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex 7a104e95fa..885908a3ed 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -7,8 +7,7 @@ switches.Production wiring has one boundary: setting `MULTICA_CLOUD_URL` connects thisconsumer as well as the other managed Cloud clients. An empty URL performs no-HTTP request, issue creation does not count rows, and the autopilot consumer-does not access its quota tables. Self-hosted deployments therefore retain the+HTTP request and the autopilot consumer does not access its quota tables. Self-hosted deployments therefore retain theunlimited paths. Request timeout and stale grace use bounded code defaultsinstead of deployment configuration.@@ -45,8 +44,10 @@ a missing notification policy as notices-disabled while continuing to enforcethe quota. The reverse order is safe because older consumers ignore theadditive notification fields.-Responses tolerate unknown JSON fields for additive compatibility. Unknown-schema/action, malformed fields, missing gates, HTTP failures, and timeouts fail+Responses tolerate unknown JSON fields for additive compatibility, including+gates this consumer does not read: Cloud may keep sending the retired+`issue_count` gate to older consumers, and it is ignored here. Unknown+schema/action, malformed fields, a missing `autopilot_runs` gate, HTTP failures, and timeouts failopen.## Cache and degradation@@ -62,27 +63,7 @@ cached `enforce` is downgraded to `observe`; after the grace, the result isalso bounds Cloud request rate when an outage returns errors immediately; coldfailures are cached only as `off` and never as policy.-## Issue count limit--The `issue_count` gate limits the total number of rows in a workspace's-`issue` table. It does not use `workspace.issue_counter`: that counter only-allocates monotonically increasing display numbers, while deleting an issue-must release one unit of capacity.--Issue creation resolves the Cloud instruction before opening a transaction.-Inside the transaction, incrementing the workspace issue counter locks the-workspace row, serializing concurrent admission; a bounded `CountIssuesUpTo`-read then admits only when the current row count is below Cloud's limit. A-blocked create rolls back the counter increment with the rest of the-transaction. The usage read is also bounded and samples at most `limit + 1`-rows, with overflow protection for the maximum integer limit.--Entitlement lookup, refresh, expiry, and policy-validation failures are-fail-open: the consumer skips the count and issue creation proceeds. The local-`observe` degradation is likewise normalized to `off` by this consumer; the-shared entitlement decision metric still records the stale observation. Once-a valid `enforce` instruction enters the transaction, ordinary database errors-still abort that transaction rather than creating a partially persisted issue.+## Autopilot quotaThe client itself has no background goroutine and introduces no startupdependency; the autopilot consumer owns its policy-neutral accounting anddiff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.goindex ce8fb932af..b22a5bda85 100644--- a/server/internal/entitlement/client.go+++ b/server/internal/entitlement/client.go@@ -280,8 +280,10 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {wire.ValidUntil.IsZero() || wire.ValidForSeconds <= 0 || wire.ValidForSeconds > int64(maxPolicyTTL/time.Second) {return fetchedPolicy{}, ErrInvalidPolicy}- gates := make(map[GateName]Gate, 2)- for _, name := range []GateName{GateIssueCount, GateAutopilotRuns} {+ // Gates this consumer does not know are ignored, so Cloud can keep sending+ // retired gates (such as issue_count) to older consumers during a rollout.+ gates := make(map[GateName]Gate, 1)+ for _, name := range []GateName{GateAutopilotRuns} {wireGate, ok := wire.Gates[string(name)]if !ok {return fetchedPolicy{}, ErrInvalidPolicydiff --git a/server/internal/entitlement/client_test.go b/server/internal/entitlement/client_test.goindex e8c350a4c8..77048fae89 100644--- a/server/internal/entitlement/client_test.go+++ b/server/internal/entitlement/client_test.go@@ -17,10 +17,7 @@ import ("github.com/google/uuid")-const (- testIssueLimit = 137- testAutopilotLimit = 23-)+const testAutopilotLimit = 23func TestDefaultConfigIsDisabledAndPerformsNoIO(t *testing.T) {var calls atomic.Int64@@ -34,7 +31,7 @@ func TestDefaultConfigIsDisabledAndPerformsNoIO(t *testing.T) {if client.Enabled() {t.Fatal("zero Config must be disabled")}- decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)+ decision := client.Gate(context.Background(), uuid.New(), GateAutopilotRuns)if decision.Gate.Action != ActionOff || decision.Reason != ReasonDisabled || calls.Load() != 0 {t.Fatalf("decision = %+v, calls = %d", decision, calls.Load())}@@ -81,8 +78,8 @@ func TestGateFetchesMachinePolicyWithoutHumanIdentity(t *testing.T) {defer server.Close()client := newTestClient(t, server.URL, nil)- decision := client.Gate(context.Background(), workspaceID, GateIssueCount)- if decision.Gate.Action != ActionEnforce || decision.Gate.Limit == nil || *decision.Gate.Limit != testIssueLimit ||+ decision := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)+ if decision.Gate.Action != ActionEnforce || decision.Gate.Limit == nil || *decision.Gate.Limit != testAutopilotLimit ||decision.Reason != ReasonRefreshed || decision.PolicyRevision != 7 || decision.SubscriptionVersion != 3 {t.Fatalf("decision = %+v", decision)}@@ -98,11 +95,11 @@ func TestGateCachesByWorkspaceAndClonesResults(t *testing.T) {client := newTestClient(t, server.URL, nil)workspaceID := uuid.New()- first := client.Gate(context.Background(), workspaceID, GateIssueCount)+ first := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)*first.Gate.Limit = 999- second := client.Gate(context.Background(), workspaceID, GateIssueCount)+ second := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)autopilot := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)- if second.Reason != ReasonCacheFresh || second.Gate.Limit == nil || *second.Gate.Limit != testIssueLimit {+ if second.Reason != ReasonCacheFresh || second.Gate.Limit == nil || *second.Gate.Limit != testAutopilotLimit {t.Fatalf("cached decision = %+v", second)}if autopilot.Gate.Action != ActionEnforce || calls.Load() != 1 {@@ -174,7 +171,7 @@ func TestConcurrentWorkspaceMissesUseSingleflight(t *testing.T) {go func() {defer wg.Done()<-start- results <- client.Gate(context.Background(), workspaceID, GateIssueCount)+ results <- client.Gate(context.Background(), workspaceID, GateAutopilotRuns)}()}close(start)@@ -221,14 +218,14 @@ func TestCancelledLeaderDoesNotCancelSharedRefresh(t *testing.T) {leaderCtx, cancelLeader := context.WithCancel(context.Background())leaderResult := make(chan Decision, 1)go func() {- leaderResult <- client.Gate(leaderCtx, workspaceID, GateIssueCount)+ leaderResult <- client.Gate(leaderCtx, workspaceID, GateAutopilotRuns)}()<-requestStartedcancelLeader()followerResult := make(chan Decision, 1)go func() {- followerResult <- client.Gate(context.Background(), workspaceID, GateIssueCount)+ followerResult <- client.Gate(context.Background(), workspaceID, GateAutopilotRuns)}()close(release)@@ -250,7 +247,9 @@ func TestWorkspaceIsolationAndBoundedLRUEviction(t *testing.T) {workspaceID := strings.TrimPrefix(r.URL.Path, "/api/v1/internal/entitlement-policies/")policy := samplePolicy(1, 0, 60, ActionEnforce)limit := limits[workspaceID]- policy.Gates[string(GateIssueCount)] = wireGate{Action: string(ActionEnforce), Limit: &limit}+ gate := policy.Gates[string(GateAutopilotRuns)]+ gate.Limit = &limit+ policy.Gates[string(GateAutopilotRuns)] = gatewritePolicy(t, w, policy)}))defer server.Close()@@ -260,7 +259,7 @@ func TestWorkspaceIsolationAndBoundedLRUEviction(t *testing.T) {workspaceID uuid.UUIDwantLimit int}{{workspaceA, 11}, {workspaceB, 22}, {workspaceA, 11}} {- decision := client.Gate(context.Background(), tc.workspaceID, GateIssueCount)+ decision := client.Gate(context.Background(), tc.workspaceID, GateAutopilotRuns)if decision.Gate.Limit == nil || *decision.Gate.Limit != tc.wantLimit {t.Fatalf("workspace %s decision = %+v", tc.workspaceID, decision)}@@ -283,14 +282,14 @@ func TestColdFailuresFailOpen(t *testing.T) {{"oversized response", bodyHandler(http.StatusOK, strings.Repeat("x", maxResponseBodySize+1)), ReasonInvalidPolicy},{"unknown schema", policyHandler(func(p *wirePolicy) { p.SchemaVersion = 2 }), ReasonInvalidPolicy},{"unknown action", policyHandler(func(p *wirePolicy) {- gate := p.Gates[string(GateIssueCount)]+ gate := p.Gates[string(GateAutopilotRuns)]gate.Action = "future"- p.Gates[string(GateIssueCount)] = gate+ p.Gates[string(GateAutopilotRuns)] = gate}), ReasonInvalidPolicy},{"cloud observe action", policyHandler(func(p *wirePolicy) {- gate := p.Gates[string(GateIssueCount)]+ gate := p.Gates[string(GateAutopilotRuns)]gate.Action = string(ActionObserve)- p.Gates[string(GateIssueCount)] = gate+ p.Gates[string(GateAutopilotRuns)] = gate}), ReasonInvalidPolicy},{"missing gate", policyHandler(func(p *wirePolicy) { delete(p.Gates, string(GateAutopilotRuns)) }), ReasonInvalidPolicy},{"excessive TTL", policyHandler(func(p *wirePolicy) { p.ValidForSeconds = 301 }), ReasonInvalidPolicy},@@ -310,7 +309,7 @@ func TestColdFailuresFailOpen(t *testing.T) {server := httptest.NewServer(tt.handler)defer server.Close()client := newTestClient(t, server.URL, nil)- decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)+ decision := client.Gate(context.Background(), uuid.New(), GateAutopilotRuns)if decision.Gate.Action != ActionOff || decision.Reason != tt.wantReason {t.Fatalf("decision = %+v", decision)}@@ -341,7 +340,7 @@ func TestTimeoutFailsOpenWithinIndependentBound(t *testing.T) {client.timeout = 20 * time.Millisecondstarted := time.Now()- decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)+ decision := client.Gate(context.Background(), uuid.New(), GateAutopilotRuns)if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {t.Fatalf("decision = %+v", decision)}@@ -363,7 +362,7 @@ func TestInternalPolicyClientDoesNotFollowRedirect(t *testing.T) {defer origin.Close()client := newTestClient(t, origin.URL, nil)- decision := client.Gate(context.Background(), uuid.New(), GateIssueCount)+ decision := client.Gate(context.Background(), uuid.New(), GateAutopilotRuns)if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {t.Fatalf("decision = %+v", decision)}@@ -385,7 +384,7 @@ func TestFastFailuresAreRateLimitedPerWorkspace(t *testing.T) {workspaceID := uuid.New()for range 2 {- decision := client.Gate(context.Background(), workspaceID, GateIssueCount)+ decision := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {t.Fatalf("decision = %+v", decision)}@@ -394,7 +393,7 @@ func TestFastFailuresAreRateLimitedPerWorkspace(t *testing.T) {t.Fatalf("HTTP calls during retry suppression = %d, want 1", calls.Load())}clock = clock.Add(defaultFailureRetry + time.Millisecond)- _ = client.Gate(context.Background(), workspaceID, GateIssueCount)+ _ = client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if calls.Load() != 2 {t.Fatalf("HTTP calls after retry suppression = %d, want 2", calls.Load())}@@ -416,11 +415,11 @@ func TestObserverRecordsCacheRefreshDecisionAndDegradation(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- _ = client.Gate(context.Background(), workspaceID, GateIssueCount)- _ = client.Gate(context.Background(), workspaceID, GateIssueCount)+ _ = client.Gate(context.Background(), workspaceID, GateAutopilotRuns)+ _ = client.Gate(context.Background(), workspaceID, GateAutopilotRuns)fail.Store(true)clock = clock.Add(6 * time.Second)- _ = client.Gate(context.Background(), workspaceID, GateIssueCount)+ _ = client.Gate(context.Background(), workspaceID, GateAutopilotRuns)cache, refresh, decisions, _ := observer.snapshot()if strings.Join(cache, ",") != "miss,hit,expired" {@@ -429,7 +428,7 @@ func TestObserverRecordsCacheRefreshDecisionAndDegradation(t *testing.T) {if strings.Join(refresh, ",") != "ok,5xx" {t.Fatalf("refresh observations = %v", refresh)}- if strings.Join(decisions, ",") != "issue_count/enforce/refreshed,issue_count/enforce/cache_fresh,issue_count/observe/stale" {+ if strings.Join(decisions, ",") != "autopilot_runs/enforce/refreshed,autopilot_runs/enforce/cache_fresh,autopilot_runs/observe/stale" {t.Fatalf("decision observations = %v", decisions)}}@@ -454,18 +453,18 @@ func TestExpiredPolicyNeverEnforcesAndIgnoresCloudClock(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- fresh := client.Gate(context.Background(), workspaceID, GateIssueCount)+ fresh := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if fresh.Gate.Action != ActionEnforce {t.Fatalf("fresh = %+v", fresh)}fail.Store(true)clock = clock.Add(6 * time.Second)- stale := client.Gate(context.Background(), workspaceID, GateIssueCount)- if stale.Gate.Action != ActionObserve || stale.Gate.Limit == nil || *stale.Gate.Limit != testIssueLimit || stale.Reason != ReasonStale {+ stale := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)+ if stale.Gate.Action != ActionObserve || stale.Gate.Limit == nil || *stale.Gate.Limit != testAutopilotLimit || stale.Reason != ReasonStale {t.Fatalf("stale = %+v", stale)}clock = clock.Add(10 * time.Second)- expired := client.Gate(context.Background(), workspaceID, GateIssueCount)+ expired := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if expired.Gate.Action != ActionOff || expired.Reason != ReasonUnavailable {t.Fatalf("expired = %+v", expired)}@@ -490,12 +489,12 @@ func TestSubscriptionVersionSwitchReplacesExpiredSnapshot(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- if got := client.Gate(context.Background(), workspaceID, GateIssueCount); got.Gate.Action != ActionEnforce {+ if got := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); got.Gate.Action != ActionEnforce {t.Fatalf("initial = %+v", got)}subscriptionVersion.Store(2)clock = clock.Add(6 * time.Second)- got := client.Gate(context.Background(), workspaceID, GateIssueCount)+ got := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if got.Gate.Action != ActionOff || got.PolicyRevision != 1 || got.SubscriptionVersion != 2 || got.Reason != ReasonRefreshed {t.Fatalf("switched = %+v", got)}@@ -516,7 +515,7 @@ func TestSubscriptionVersionRegressionCannotOverwriteWorkspaceCache(t *testing.Tclient.now = func() time.Time { return clock }workspaceID := uuid.New()- initial := client.Gate(context.Background(), workspaceID, GateIssueCount)+ initial := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if initial.Gate.Action != ActionEnforce {t.Fatalf("initial = %+v", initial)}@@ -524,7 +523,7 @@ func TestSubscriptionVersionRegressionCannotOverwriteWorkspaceCache(t *testing.Tpolicy = samplePolicy(1, 3, 5, ActionOff)mu.Unlock()clock = clock.Add(6 * time.Second)- regressed := client.Gate(context.Background(), workspaceID, GateIssueCount)+ regressed := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if regressed.Gate.Action != ActionObserve || regressed.PolicyRevision != 1 || regressed.SubscriptionVersion != 4 {t.Fatalf("regressed = %+v", regressed)}@@ -548,19 +547,19 @@ func TestSubscriptionVersionRegressionIsAcceptedAfterStaleGrace(t *testing.T) {client.now = func() time.Time { return clock }workspaceID := uuid.New()- initial := client.Gate(context.Background(), workspaceID, GateIssueCount)+ initial := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if initial.SubscriptionVersion != 2 || initial.Reason != ReasonRefreshed {t.Fatalf("initial = %+v", initial)}subscriptionVersion.Store(1)clock = clock.Add(71 * time.Second)- recovered := client.Gate(context.Background(), workspaceID, GateIssueCount)+ recovered := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if recovered.SubscriptionVersion != 1 || recovered.Reason != ReasonRefreshed {t.Fatalf("recovered = %+v", recovered)}clock = clock.Add(defaultFailureRetry + time.Millisecond)- cached := client.Gate(context.Background(), workspaceID, GateIssueCount)+ cached := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)if cached.SubscriptionVersion != 1 || cached.Reason != ReasonCacheFresh || calls.Load() != 2 {t.Fatalf("cached = %+v, HTTP calls = %d", cached, calls.Load())}@@ -578,7 +577,7 @@ func TestInvalidWorkspaceAndUnknownGateDoNotFetch(t *testing.T) {workspaceID uuid.UUIDgate GateNamereason Reason- }{{uuid.Nil, GateIssueCount, ReasonInvalidWorkspace}, {uuid.New(), GateName("future_gate"), ReasonUnknownGate}}+ }{{uuid.Nil, GateAutopilotRuns, ReasonInvalidWorkspace}, {uuid.New(), GateName("future_gate"), ReasonUnknownGate}}for _, tt := range tests {decision := client.Gate(context.Background(), tt.workspaceID, tt.gate)if decision.Gate.Action != ActionOff || decision.Reason != tt.reason {@@ -606,14 +605,20 @@ func newTestClient(t *testing.T, baseURL string, mutate func(*Config)) *Client {return client}-func samplePolicy(policyRevision, subscriptionVersion, validForSeconds int64, issueAction Action) wirePolicy {- issueLimit := testIssueLimit+func samplePolicy(policyRevision, subscriptionVersion, validForSeconds int64, autopilotAction Action) wirePolicy {autopilotLimit := testAutopilotLimit+ retiredIssueLimit := 1000periodStart := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)periodEnd := periodStart.AddDate(0, 1, 0)- issueGate := wireGate{Action: string(issueAction)}- if issueAction != ActionOff {- issueGate.Limit = &issueLimit+ autopilotGate := wireGate{Action: string(autopilotAction)}+ if autopilotAction != ActionOff {+ autopilotGate.Limit = &autopilotLimit+ autopilotGate.PeriodStart = &periodStart+ autopilotGate.PeriodEnd = &periodEnd+ autopilotGate.ResetAt = &periodEnd+ autopilotGate.Notifications = &wireNotificationPolicy{+ OnRejection: NotificationFirstRejectionPerPeriod,+ }}return wirePolicy{SchemaVersion: SchemaVersion,@@ -622,14 +627,10 @@ func samplePolicy(policyRevision, subscriptionVersion, validForSeconds int64, isValidUntil: time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC),ValidForSeconds: validForSeconds,Gates: map[string]wireGate{- string(GateIssueCount): issueGate,- string(GateAutopilotRuns): {- Action: string(ActionEnforce), Limit: &autopilotLimit,- PeriodStart: &periodStart, PeriodEnd: &periodEnd, ResetAt: &periodEnd,- Notifications: &wireNotificationPolicy{- OnRejection: NotificationFirstRejectionPerPeriod,- },- },+ // Cloud may keep sending the retired issue_count gate to older+ // consumers; this consumer must ignore it.+ "issue_count": {Action: string(ActionEnforce), Limit: &retiredIssueLimit},+ string(GateAutopilotRuns): autopilotGate,},}}@@ -709,3 +710,23 @@ func (o *recordingObserver) snapshot() (cache, refresh, decisions []string, regrreturn append([]string(nil), o.cache...), append([]string(nil), o.refresh...),append([]string(nil), o.decisions...), o.versionRegressions}++func TestRetiredIssueCountGateDoesNotAffectPolicy(t *testing.T) {+ for _, tc := range []struct {+ name string+ mutate func(*wirePolicy)+ }{+ {"absent", func(p *wirePolicy) { delete(p.Gates, "issue_count") }},+ {"unreadable", func(p *wirePolicy) { p.Gates["issue_count"] = wireGate{Action: "future"} }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ server := httptest.NewServer(policyHandler(tc.mutate))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ decision := client.Gate(context.Background(), uuid.New(), GateAutopilotRuns)+ if decision.Gate.Action != ActionEnforce || decision.Reason != ReasonRefreshed {+ t.Fatalf("decision = %+v", decision)+ }+ })+ }+}diff --git a/server/internal/entitlement/entitlementtest/stub_test.go b/server/internal/entitlement/entitlementtest/stub_test.goindex 30400ed5f4..e2472c1700 100644--- a/server/internal/entitlement/entitlementtest/stub_test.go+++ b/server/internal/entitlement/entitlementtest/stub_test.go@@ -12,20 +12,20 @@ func TestStubIsWorkspaceScopedAndDefaultsOff(t *testing.T) {stub := New()workspaceA, workspaceB := uuid.New(), uuid.New()limit := 7- stub.Set(workspaceA, entitlement.GateIssueCount, entitlement.Decision{+ stub.Set(workspaceA, entitlement.GateAutopilotRuns, entitlement.Decision{Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},})- first := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueCount)+ first := stub.Gate(context.Background(), workspaceA, entitlement.GateAutopilotRuns)if first.Gate.Action != entitlement.ActionEnforce || first.Gate.Limit == nil || *first.Gate.Limit != 7 || first.Reason != entitlement.ReasonStub {t.Fatalf("configured = %+v", first)}*first.Gate.Limit = 99- second := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueCount)+ second := stub.Gate(context.Background(), workspaceA, entitlement.GateAutopilotRuns)if second.Gate.Limit == nil || *second.Gate.Limit != 7 {t.Fatalf("stub leaked mutable decision: %+v", second)}- missing := stub.Gate(context.Background(), workspaceB, entitlement.GateIssueCount)+ missing := stub.Gate(context.Background(), workspaceB, entitlement.GateAutopilotRuns)if missing.Gate.Action != entitlement.ActionOff || missing.Reason != entitlement.ReasonStub {t.Fatalf("missing = %+v", missing)}diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex d1834de9fc..9c9d2501fe 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -12,13 +12,12 @@ const SchemaVersion = 1type GateName stringconst (- GateIssueCount GateName = "issue_count"GateAutopilotRuns GateName = "autopilot_runs")func (n GateName) valid() bool {switch n {- case GateIssueCount, GateAutopilotRuns:+ case GateAutopilotRuns:return truedefault:return false@@ -75,8 +74,8 @@ type Decision struct {CloudValidUntil time.Time}-// Provider is the only interface issue-count and autopilot consumers-// need. It deliberately has no error return: every failure is represented by a+// Provider is the only interface the autopilot consumer+// needs. It deliberately has no error return: every failure is represented by a// fail-open Decision with ActionOff (or ActionObserve for a bounded stale// snapshot that can no longer enforce).type Provider interface {diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 981078ac2d..76d1348850 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3069,9 +3069,6 @@ func (h *Handler) QuickCreateIssue(w http.ResponseWriter, r *http.Request) {task, err := h.TaskService.EnqueueQuickCreateTask(r.Context(), wsUUID, requesterUUID, agentUUID, squadUUID, prompt, priority, dueDate, projectUUID, parentIssueUUID, attachmentIDs)if err != nil {- if writeIssueLimitReached(w, err) {- return- }if errors.Is(err, service.ErrProjectAccessDenied) {h.writeDispatchBlocked(w, http.StatusForbidden, ReasonProjectAccessBlocked)return@@ -3733,9 +3730,6 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {if writeIssueCreatePropertyError(w, err) {return}- if writeIssueLimitReached(w, err) {- return- }if writeIssueNumberCollision(w, err) {return}diff --git a/server/internal/handler/issue_limit.go b/server/internal/handler/issue_limit.godeleted file mode 100644index 57055f2fee..0000000000--- a/server/internal/handler/issue_limit.go+++ /dev/null@@ -1,66 +0,0 @@-package handler--import (- "errors"- "net/http"-- "github.com/multica-ai/multica/server/internal/entitlement"- "github.com/multica-ai/multica/server/internal/service"-)--type IssueLimitUsageResponse struct {- Used int64 `json:"used"`- Limit int64 `json:"limit"`-}--// GetIssueLimitUsage returns local usage for a currently enforced Cloud limit.-// Limit mode comes only from Cloud's subscription summary; this endpoint never-// infers unlimited access from cache or refresh reasons.-func (h *Handler) GetIssueLimitUsage(w http.ResponseWriter, r *http.Request) {- workspaceID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace_id")- if !ok {- return- }- policy := service.ResolveIssueCountPolicy(r.Context(), h.Entitlements, workspaceID)- if policy.Action != entitlement.ActionEnforce {- w.WriteHeader(http.StatusNoContent)- return- }- used, err := service.CountIssueUsage(r.Context(), h.Queries, workspaceID, policy)- if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load issue limit usage")- return- }- writeJSON(w, http.StatusOK, IssueLimitUsageResponse{Used: used, Limit: policy.Limit})-}--func writeIssueLimitReached(w http.ResponseWriter, err error) bool {- var limitErr *service.IssueLimitReachedError- if !errors.As(err, &limitErr) {- return false- }- writeJSON(w, http.StatusPaymentRequired, map[string]any{- "code": "issue_limit_reached",- "error": "workspace has reached its issue limit",- "limit": limitErr.Limit,- "policy_revision": limitErr.PolicyRevision,- })- return true-}--// writeIssueNumberCollision reports a number conflict that automatic repair-// could not resolve and directs the caller to a workspace administrator.-func writeIssueNumberCollision(w http.ResponseWriter, err error) bool {- var collisionErr *service.IssueNumberCollisionError- if !errors.As(err, &collisionErr) {- return false- }- writeJSON(w, http.StatusConflict, map[string]any{- "code": "issue_number_collision",- "error": "workspace issue counter is behind its highest issue number, so card creation cannot allocate a free number",- "allocated": collisionErr.Allocated,- "constraint": collisionErr.Constraint,- "repair": "Ask a workspace administrator to repair the issue counter, then retry.",- })- return true-}diff --git a/server/internal/handler/issue_number_collision.go b/server/internal/handler/issue_number_collision.gonew file mode 100644index 0000000000..3a8b6e6652--- /dev/null+++ b/server/internal/handler/issue_number_collision.go@@ -0,0 +1,25 @@+package handler++import (+ "errors"+ "net/http"++ "github.com/multica-ai/multica/server/internal/service"+)++// writeIssueNumberCollision reports a number conflict that automatic repair+// could not resolve and directs the caller to a workspace administrator.+func writeIssueNumberCollision(w http.ResponseWriter, err error) bool {+ var collisionErr *service.IssueNumberCollisionError+ if !errors.As(err, &collisionErr) {+ return false+ }+ writeJSON(w, http.StatusConflict, map[string]any{+ "code": "issue_number_collision",+ "error": "workspace issue counter is behind its highest issue number, so card creation cannot allocate a free number",+ "allocated": collisionErr.Allocated,+ "constraint": collisionErr.Constraint,+ "repair": "Ask a workspace administrator to repair the issue counter, then retry.",+ })+ return true+}diff --git a/server/internal/handler/quick_create_parent_test.go b/server/internal/handler/quick_create_parent_test.goindex 65464136d6..8b580e88f1 100644--- a/server/internal/handler/quick_create_parent_test.go+++ b/server/internal/handler/quick_create_parent_test.go@@ -7,9 +7,6 @@ import ("net/http/httptest""testing"- "github.com/google/uuid"- "github.com/multica-ai/multica/server/internal/entitlement"- "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/pkg/agent")@@ -184,54 +181,6 @@ func TestQuickCreateIssueParentTrustBoundary(t *testing.T) {}})- t.Run("full workspace is rejected before enqueue", func(t *testing.T) {- before := countQuickCreateTasks(t)- var issueCount int- if err := testPool.QueryRow(ctx,- `SELECT COUNT(*) FROM issue WHERE workspace_id = $1`,- testWorkspaceID,- ).Scan(&issueCount); err != nil {- t.Fatalf("count workspace issues: %v", err)- }- if issueCount <= 0 {- t.Fatal("full-workspace test requires at least one seeded issue")- }- stub := entitlementtest.New()- stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateIssueCount, entitlement.Decision{- Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &issueCount},- PolicyRevision: 23,- })- priorProvider := testHandler.TaskService.Entitlements- testHandler.TaskService.Entitlements = stub- t.Cleanup(func() {- testHandler.TaskService.Entitlements = priorProvider- })-- w := httptest.NewRecorder()- req := newRequest("POST", "/api/issues/quick-create", map[string]any{- "agent_id": agentID,- "prompt": "This task must not be queued when the workspace is full",- })- testHandler.QuickCreateIssue(w, req)- if w.Code != http.StatusPaymentRequired {- t.Fatalf("expected 402, got %d: %s", w.Code, w.Body.String())- }- var body struct {- Code string `json:"code"`- Limit int `json:"limit"`- PolicyRevision int `json:"policy_revision"`- }- if err := json.NewDecoder(w.Body).Decode(&body); err != nil {- t.Fatalf("decode issue-limit response: %v", err)- }- if body.Code != "issue_limit_reached" || body.Limit != issueCount || body.PolicyRevision != 23 {- t.Fatalf("unexpected issue-limit response: %+v", body)- }- if got := countQuickCreateTasks(t); got != before {- t.Fatalf("full workspace must not enqueue a task: expected %d, got %d", before, got)- }- })-t.Run("foreign workspace parent is rejected", func(t *testing.T) {before := countQuickCreateTasks(t)w := httptest.NewRecorder()diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.goindex a397781801..e3745b2ea6 100644--- a/server/internal/handler/source_context.go+++ b/server/internal/handler/source_context.go@@ -562,18 +562,6 @@ func (h *Handler) CreateCommentSubIssue(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusBadRequest, "mode must be manual or agent")return}- // Reject a full workspace before cloning source attachments. This early- // check avoids expensive work; the TaskService enqueue preflight and final- // transactional issue admission remain necessary because this is not a- // capacity reservation.- if err := service.CheckIssueCreateCapacity(r.Context(), h.Queries, h.Entitlements, wsUUID); err != nil {- if !writeIssueLimitReached(w, err) {- slog.Warn("source context issue-capacity preflight failed", append(logger.RequestAttrs(r), "error", err)...)- writeError(w, http.StatusInternalServerError, "failed to check issue capacity")- }- return- }-contextID := dbid.NewV7()capture, objectKeys, err := h.cloneSourceContext(r.Context(), wsUUID, userUUID, contextID, build)if err != nil {@@ -936,9 +924,6 @@ func (h *Handler) createAgentCommentSubIssue(w http.ResponseWriter, r *http.Requ}func (h *Handler) writeSourceContextError(w http.ResponseWriter, err error, limits service.SourceContextLimitUsage) {- if writeIssueLimitReached(w, err) {- return- }status := http.StatusInternalServerErrorcode := "source_context_capture_failed"message := "failed to capture source context"diff --git a/server/internal/handler/source_context_integration_test.go b/server/internal/handler/source_context_integration_test.goindex 14567cd489..37ac7e0c4c 100644--- a/server/internal/handler/source_context_integration_test.go+++ b/server/internal/handler/source_context_integration_test.go@@ -11,15 +11,10 @@ import ("testing""time"- "github.com/google/uuid"- "github.com/multica-ai/multica/server/internal/entitlement"- "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest""github.com/multica-ai/multica/server/internal/events"- "github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/projectaccess""github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"- db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -38,119 +33,6 @@ func TestWriteSourceContextErrorHidesInternalDetails(t *testing.T) {}}-func TestRetrySourceContextQuickCreateReturnsIssueLimitRecovery(t *testing.T) {- if testHandler == nil || testPool == nil {- t.Skip("database not available")- }- ctx := context.Background()- var agentID string- if err := testPool.QueryRow(ctx, `- SELECT id FROM agent- WHERE workspace_id = $1 AND runtime_id IS NOT NULL AND archived_at IS NULL- ORDER BY created_at ASC LIMIT 1- `, testWorkspaceID).Scan(&agentID); err != nil {- t.Fatalf("load retry test agent: %v", err)- }- contextID := uuid.NewString()- payload, err := json.Marshal(service.QuickCreateContext{- Type: service.QuickCreateContextType,- Prompt: "retry source context at issue limit",- RequesterID: testUserID,- WorkspaceID: testWorkspaceID,- SourceContextID: contextID,- })- if err != nil {- t.Fatalf("marshal retry context: %v", err)- }- number := int(time.Now().UnixNano()%100000) + 9_200_000- var sourceIssueID, taskID string- if err := testPool.QueryRow(ctx, `- INSERT INTO issue (workspace_id, title, creator_type, creator_id, number)- VALUES ($1, 'retry limit source', 'member', $2, $3)- RETURNING id- `, testWorkspaceID, testUserID, number).Scan(&sourceIssueID); err != nil {- t.Fatalf("insert retry source issue: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `DELETE FROM issue_source_context WHERE id = $1`, contextID)- _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE rerun_of_task_id = $1 OR id = $1`, taskID)- _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, sourceIssueID)- })- if err := testPool.QueryRow(ctx, `- INSERT INTO agent_task_queue (- agent_id, runtime_id, status, priority, context,- originator_user_id, accountable_user_id- )- SELECT $1, runtime_id, 'failed', 0, $2, $3, $3- FROM agent WHERE id = $1- RETURNING id- `, agentID, payload, testUserID).Scan(&taskID); err != nil {- t.Fatalf("insert failed source-context task: %v", err)- }- if _, err := testPool.Exec(ctx, `- INSERT INTO issue_source_context (- id, workspace_id, origin_task_id, source_issue_id, anchor_comment_id,- captured_by_user_id, snapshot_version, snapshot, capture_digest, state- ) VALUES ($1, $2, $3, $4, gen_random_uuid(), $5, 1, '{}'::jsonb, 'digest', 'pending')- `, contextID, testWorkspaceID, taskID, sourceIssueID, testUserID); err != nil {- t.Fatalf("insert pending source context: %v", err)- }- var issueCount int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&issueCount); err != nil {- t.Fatalf("count issues before retry: %v", err)- }- stub := entitlementtest.New()- stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateIssueCount, entitlement.Decision{- Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &issueCount},- PolicyRevision: 43,- })- priorProvider := testHandler.TaskService.Entitlements- testHandler.TaskService.Entitlements = stub- t.Cleanup(func() {- testHandler.TaskService.Entitlements = priorProvider- })-- recorder := httptest.NewRecorder()- request := withURLParam(newRequest(http.MethodPost, "/api/tasks/"+taskID+"/retry-source-context", nil), "taskId", taskID)- member, err := testHandler.Queries.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{- UserID: util.MustParseUUID(testUserID),- WorkspaceID: util.MustParseUUID(testWorkspaceID),- })- if err != nil {- t.Fatalf("load retry caller membership: %v", err)- }- request = request.WithContext(middleware.SetMemberContext(request.Context(), testWorkspaceID, member))- testHandler.RetrySourceContextQuickCreate(recorder, request)- if recorder.Code != http.StatusPaymentRequired {- t.Fatalf("source-context retry at limit = %d: %s", recorder.Code, recorder.Body.String())- }- var body struct {- Code string `json:"code"`- Limit int `json:"limit"`- PolicyRevision int `json:"policy_revision"`- }- if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {- t.Fatalf("decode retry issue-limit response: %v", err)- }- if body.Code != "issue_limit_reached" || body.Limit != issueCount || body.PolicyRevision != 43 {- t.Fatalf("retry issue-limit response = %+v", body)- }- var children int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE rerun_of_task_id = $1`, taskID).Scan(&children); err != nil {- t.Fatalf("count retry children: %v", err)- }- if children != 0 {- t.Fatalf("retry child count = %d, want 0", children)- }- var originTaskID string- if err := testPool.QueryRow(ctx, `SELECT origin_task_id FROM issue_source_context WHERE id = $1`, contextID).Scan(&originTaskID); err != nil {- t.Fatalf("load pending context after rejection: %v", err)- }- if originTaskID != taskID {- t.Fatalf("pending context moved to %s, want original task %s", originTaskID, taskID)- }-}-func TestCommentSourceContextLifecycle(t *testing.T) {if testHandler == nil || testPool == nil {t.Skip("database not available")@@ -331,82 +213,6 @@ func TestCommentSourceContextLifecycle(t *testing.T) {t.Fatalf("restore earlier thread comment: %v", err)}- t.Run("full workspace skips source attachment copies and enqueue", func(t *testing.T) {- var agentID string- if err := testPool.QueryRow(ctx, `- SELECT id FROM agent- WHERE workspace_id = $1 AND runtime_id = $2 AND archived_at IS NULL- ORDER BY created_at ASC LIMIT 1- `, testWorkspaceID, testRuntimeID).Scan(&agentID); err != nil {- t.Fatalf("load source-context test agent: %v", err)- }- var originalMetadata string- if err := testPool.QueryRow(ctx, `SELECT metadata::text FROM agent_runtime WHERE id = $1`, testRuntimeID).Scan(&originalMetadata); err != nil {- t.Fatalf("load original runtime metadata: %v", err)- }- if _, err := testPool.Exec(ctx, `- UPDATE agent_runtime- SET metadata = '{"cli_version":"0.4.3","capabilities":["source_context_quick_create_v1"]}'::jsonb- WHERE id = $1- `, testRuntimeID); err != nil {- t.Fatalf("enable source-context capability: %v", err)- }- t.Cleanup(func() {- _, _ = testPool.Exec(context.Background(), `UPDATE agent_runtime SET metadata = $1::jsonb WHERE id = $2`, originalMetadata, testRuntimeID)- })-- var issueCount int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue WHERE workspace_id = $1`, testWorkspaceID).Scan(&issueCount); err != nil {- t.Fatalf("count issues before source-context limit check: %v", err)- }- stub := entitlementtest.New()- stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateIssueCount, entitlement.Decision{- Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &issueCount},- PolicyRevision: 41,- })- priorHandlerProvider := testHandler.Entitlements- priorTaskProvider := testHandler.TaskService.Entitlements- testHandler.Entitlements = stub- testHandler.TaskService.Entitlements = stub- t.Cleanup(func() {- testHandler.Entitlements = priorHandlerProvider- testHandler.TaskService.Entitlements = priorTaskProvider- })-- beforeReads, beforeUploads := store.streamCopyCalls()- prompt := "source context must not enqueue while the workspace is full"- fullRecorder := httptest.NewRecorder()- fullRequest := withURLParam(newRequest(http.MethodPost, "/api/comments/"+selectedID+"/sub-issues", map[string]any{- "mode": "agent",- "capture_token": preview.CaptureToken,- "quick_create": map[string]any{- "agent_id": agentID,- "prompt": prompt,- },- }), "commentId", selectedID)- testHandler.CreateCommentSubIssue(fullRecorder, fullRequest)- if fullRecorder.Code != http.StatusPaymentRequired {- t.Fatalf("full source-context create = %d: %s", fullRecorder.Code, fullRecorder.Body.String())- }- var body struct {- Code string `json:"code"`- }- if err := json.Unmarshal(fullRecorder.Body.Bytes(), &body); err != nil || body.Code != "issue_limit_reached" {- t.Fatalf("full source-context response = %+v, err=%v", body, err)- }- afterReads, afterUploads := store.streamCopyCalls()- if afterReads != beforeReads || afterUploads != beforeUploads {- t.Fatalf("source attachments copied before rejection: reads %d->%d uploads %d->%d", beforeReads, afterReads, beforeUploads, afterUploads)- }- var queued int- if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE context->>'prompt' = $1`, prompt).Scan(&queued); err != nil {- t.Fatalf("count full source-context tasks: %v", err)- }- if queued != 0 {- t.Fatalf("full source-context task count = %d, want 0", queued)- }- })-// A damaged cross-issue parent chain is rejected instead of truncated.var foreignIssueID, foreignRootID stringif err := testPool.QueryRow(ctx, `diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.goindex 0e80d31aec..a6792181ac 100644--- a/server/internal/handler/task_lifecycle.go+++ b/server/internal/handler/task_lifecycle.go@@ -295,9 +295,6 @@ func (h *Handler) RetrySourceContextQuickCreate(w http.ResponseWriter, r *http.Rreturn h.canInvokeAgent(r.Context(), agent, "member", userID, userID, uuidToString(workspaceID))}task, err := h.TaskService.RetrySourceContextQuickCreate(r.Context(), workspaceID, requesterID, taskID, canInvoke)- if writeIssueLimitReached(w, err) {- return- }if errors.Is(err, service.ErrRerunInvokeNotAllowed) {h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)returndiff --git a/server/internal/integrations/slack/slash_command.go b/server/internal/integrations/slack/slash_command.goindex d2451075a4..43cd40a181 100644--- a/server/internal/integrations/slack/slash_command.go+++ b/server/internal/integrations/slack/slash_command.go@@ -12,7 +12,6 @@ import ("github.com/slack-go/slack""github.com/multica-ai/multica/server/internal/integrations/channel/engine"- "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -51,7 +50,6 @@ const (slashQueuedText = "✅ On it — I'm turning that into an issue. You'll get a Multica notification when it's ready."slashNotMemberText = "You're not a member of this Multica workspace, so I can't file an issue for you."slashLinkAccountFallback = "Link your Slack account to Multica first, then try `/issue` again."- slashIssueLimitText = "⚠️ This workspace has reached its issue limit. Open Multica to view the available recovery options."slashInternalErrorText = "⚠️ Something went wrong creating the issue. Please try again."slashDisabledText = "This Slack app isn't connected to Multica (or was disconnected). Ask a workspace admin to reconnect it."slashNewStartedText = "✅ Started a new Multica chat."@@ -284,10 +282,6 @@ func (p *SlashCommandProcessor) process(ctx context.Context, cmd slack.SlashCommpgtype.UUID{}, // no parent issuenil, // no attachments); err != nil {- var limitErr *service.IssueLimitReachedError- if errors.As(err, &limitErr) {- return slashIssueLimitText- }p.logger.WarnContext(ctx, "slack slash command: enqueue quick-create failed","app_id", cmd.APIAppID, "error", err)return slashInternalErrorTextdiff --git a/server/internal/integrations/slack/slash_command_test.go b/server/internal/integrations/slack/slash_command_test.goindex e198f98e50..4003acc315 100644--- a/server/internal/integrations/slack/slash_command_test.go+++ b/server/internal/integrations/slack/slash_command_test.go@@ -1,7 +1,6 @@package slackimport (- "bytes""context""errors""log/slog"@@ -13,7 +12,6 @@ import ("github.com/slack-go/slack""github.com/multica-ai/multica/server/internal/integrations/channel/engine"- "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -298,29 +296,6 @@ func TestSlashHandle_EnqueueFailureIsInternalError(t *testing.T) {}}-func TestSlashHandle_IssueLimitReachedIsActionable(t *testing.T) {- q := &fakeSlashQueries{- inst: activeSlashInstallation(),- binding: db.ChannelUserBinding{MulticaUserID: slashTestUUID(9)},- }- tasks := &fakeQuickCreate{err: &service.IssueLimitReachedError{Limit: 100, PolicyRevision: 7}}- p, captured, _ := newTestSlashProcessor(q, tasks, &fakeBindingMinter{})- var logs bytes.Buffer- p.logger = slog.New(slog.NewTextHandler(&logs, nil))-- p.Handle(context.Background(), issueSlashCmd())-- if tasks.calls != 1 {- t.Fatalf("expected the enqueue to be attempted once, got %d", tasks.calls)- }- if *captured != slashIssueLimitText {- t.Fatalf("expected issue-limit reply, got %q", *captured)- }- if logs.Len() != 0 {- t.Fatalf("expected issue-limit rejection not to emit a warning, got %q", logs.String())- }-}-func TestSlashHandle_IgnoresOtherCommands(t *testing.T) {tasks := &fakeQuickCreate{}p, _, count := newTestSlashProcessor(&fakeSlashQueries{inst: activeSlashInstallation()}, tasks, &fakeBindingMinter{})diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex fc74643baa..eb22da7b79 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -772,8 +772,6 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopiif err != nil {return fmt.Errorf("resolve leader: %w", err)}- issueCountPolicy := ResolveIssueCountPolicy(ctx, s.Entitlements, ap.WorkspaceID)-tx, err := s.TxStarter.Begin(ctx)if err != nil {return fmt.Errorf("begin tx: %w", err)@@ -818,16 +816,9 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopireturn &errDispatchSkipped{reason: "recent duplicate autopilot issue: " + util.UUIDToString(duplicate.ID), code: dispatch.ReasonAlreadyActive}}- issueNumber, err := AllocateIssueNumber(ctx, qtx, ap.WorkspaceID, issueCountPolicy)+ issueNumber, err := qtx.IncrementIssueCounter(ctx, ap.WorkspaceID)if err != nil {- var limitErr *IssueLimitReachedError- if errors.As(err, &limitErr) {- return &errDispatchSkipped{- reason: "workspace has reached its issue limit",- code: dispatch.ReasonIssueLimitReached,- }- }- return fmt.Errorf("allocate issue number: %w", err)+ return fmt.Errorf("increment issue counter: %w", err)}newPosition, err := issueposition.NextTopPosition(ctx, tx, ap.WorkspaceID, "todo")diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 49f229c0d5..7f96f4c333 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -5,16 +5,16 @@ import ("encoding/json""errors""fmt"- "github.com/multica-ai/multica/server/internal/attribution""log/slog""sort""time"+ "github.com/multica-ai/multica/server/internal/attribution"+"github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"- "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issueguard""github.com/multica-ai/multica/server/internal/issueposition"@@ -43,9 +43,6 @@ type IssueService struct {// Metrics as "PostHog only", so leaving it unset is safe.Metrics *obsmetrics.BusinessMetricsTaskService *TaskService- // Entitlements supplies Cloud's effective issue-count instruction. Nil is- // the self-hosted unlimited path.- Entitlements entitlement.Provider}func NewIssueService(q *db.Queries, tx TxStarter, bus *events.Bus, ac analytics.Client, ts *TaskService) *IssueService {@@ -223,7 +220,7 @@ type IssueCreateResult struct {//// A healthy create is byte-identical to before this existed — the allocation// query is untouched and nothing extra is read on the way through. The collision-// is the signal: AllocateIssueNumber bumps the counter inside the same+// is the signal: IncrementIssueCounter bumps the counter inside the same// transaction as the INSERT, so the unique violation rolls the increment back// too and every later create in that workspace retries the same taken number// forever. Moving the counter first is what makes the second attempt land on a@@ -281,7 +278,6 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss// Caller-owned validation is limited to transport-shaped checks: title// required, RFC3339 date format, assignee pair sanity.func (s *IssueService) createOnce(ctx context.Context, p IssueCreateParams, opts IssueCreateOpts) (IssueCreateResult, error) {- issueCountPolicy := ResolveIssueCountPolicy(ctx, s.Entitlements, p.WorkspaceID)tx, err := s.TxStarter.Begin(ctx)if err != nil {return IssueCreateResult{}, fmt.Errorf("begin tx: %w", err)@@ -410,7 +406,7 @@ func (s *IssueService) createOnce(ctx context.Context, p IssueCreateParams, optsreturn IssueCreateResult{DuplicateIssue: &dup}, ErrActiveDuplicate}- issueNumber, err := AllocateIssueNumber(ctx, qtx, p.WorkspaceID, issueCountPolicy)+ issueNumber, err := qtx.IncrementIssueCounter(ctx, p.WorkspaceID)if err != nil {return IssueCreateResult{}, fmt.Errorf("allocate issue number: %w", err)}diff --git a/server/internal/service/issue_limit.go b/server/internal/service/issue_limit.godeleted file mode 100644index dc5368e0bf..0000000000--- a/server/internal/service/issue_limit.go+++ /dev/null@@ -1,130 +0,0 @@-package service--import (- "context"- "fmt"- "math"-- "github.com/google/uuid"- "github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/entitlement"- db "github.com/multica-ai/multica/server/pkg/db/generated"-)--// IssueLimitReachedError carries Cloud's effective limit and policy revision-// to transport adapters. It never includes a plan name or subscription state.-type IssueLimitReachedError struct {- Limit int64- PolicyRevision int64-}--func (e *IssueLimitReachedError) Error() string {- return fmt.Sprintf("workspace issue limit reached: limit %d", e.Limit)-}--// IssueCountPolicy is the validated mechanical instruction received from-// Cloud. Resolve it before opening a database transaction so a network call-// never holds product-database locks.-type IssueCountPolicy struct {- Action entitlement.Action- Limit int64- PolicyRevision int64-}--func ResolveIssueCountPolicy(ctx context.Context, provider entitlement.Provider, workspaceID pgtype.UUID) IssueCountPolicy {- if provider == nil || !workspaceID.Valid {- return IssueCountPolicy{Action: entitlement.ActionOff}- }- decision := provider.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateIssueCount)- policy := IssueCountPolicy{- Action: decision.Gate.Action,- PolicyRevision: decision.PolicyRevision,- }- if decision.Gate.Limit != nil {- policy.Limit = int64(*decision.Gate.Limit)- }- switch policy.Action {- case entitlement.ActionOff:- policy.Limit = 0- case entitlement.ActionEnforce:- if policy.Limit > 0 {- return policy- }- policy.Action = entitlement.ActionOff- policy.Limit = 0- default:- policy.Action = entitlement.ActionOff- policy.Limit = 0- }- return policy-}--// CheckIssueCreateCapacity performs a read-only admission preflight for flows-// that do work before the issue transaction starts, such as agent quick create.-// It is deliberately not a reservation: callers must still use-// AllocateIssueNumber in the final create transaction to serialize concurrent-// admissions against the workspace row.-func CheckIssueCreateCapacity(ctx context.Context, q *db.Queries, provider entitlement.Provider, workspaceID pgtype.UUID) error {- policy := ResolveIssueCountPolicy(ctx, provider, workspaceID)- if policy.Action != entitlement.ActionEnforce {- return nil- }- used, err := CountIssueUsage(ctx, q, workspaceID, policy)- if err != nil {- return err- }- if used >= policy.Limit {- return &IssueLimitReachedError{Limit: policy.Limit, PolicyRevision: policy.PolicyRevision}- }- return nil-}--// AllocateIssueNumber serializes creates on the workspace row, then checks the-// current number of issue rows inside the same transaction. The caller must-// roll the transaction back on IssueLimitReachedError; that also rolls back-// the counter increment. Deleting an issue frees capacity because-// issue_counter is deliberately not used as quota usage.-func AllocateIssueNumber(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, policy IssueCountPolicy) (int32, error) {- number, err := q.IncrementIssueCounter(ctx, workspaceID)- if err != nil {- return 0, err- }- if policy.Action != entitlement.ActionEnforce {- return number, nil- }- used, err := q.CountIssuesUpTo(ctx, db.CountIssuesUpToParams{- WorkspaceID: workspaceID,- Limit: policy.Limit,- })- if err != nil {- return 0, err- }- if used >= policy.Limit {- return 0, &IssueLimitReachedError{Limit: policy.Limit, PolicyRevision: policy.PolicyRevision}- }- return number, nil-}--// CountIssueUsage performs a bounded read for a limited policy. The returned-// value is exact while below the limit and capped at the limit once the-// workspace is full.-func CountIssueUsage(ctx context.Context, q *db.Queries, workspaceID pgtype.UUID, policy IssueCountPolicy) (int64, error) {- if policy.Action != entitlement.ActionEnforce {- return 0, nil- }- sampleLimit := policy.Limit- if sampleLimit < math.MaxInt64 {- sampleLimit++- }- sampled, err := q.CountIssuesUpTo(ctx, db.CountIssuesUpToParams{- WorkspaceID: workspaceID,- Limit: sampleLimit,- })- if err != nil {- return 0, err- }- if sampled > policy.Limit {- return policy.Limit, nil- }- return sampled, nil-}diff --git a/server/internal/service/issue_limit_test.go b/server/internal/service/issue_limit_test.godeleted file mode 100644index 02ab6c66f2..0000000000--- a/server/internal/service/issue_limit_test.go+++ /dev/null@@ -1,160 +0,0 @@-package service--import (- "context"- "errors"- "fmt"- "sync"- "testing"-- "github.com/google/uuid"- "github.com/jackc/pgx/v5/pgtype"- "github.com/multica-ai/multica/server/internal/entitlement"- "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"- "github.com/multica-ai/multica/server/internal/util"- db "github.com/multica-ai/multica/server/pkg/db/generated"-)--type issueLimitProviderFunc func(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision--func (f issueLimitProviderFunc) Gate(ctx context.Context, workspaceID uuid.UUID, gate entitlement.GateName) entitlement.Decision {- return f(ctx, workspaceID, gate)-}--func TestResolveIssueCountPolicyUsesOnlyCloudInstruction(t *testing.T) {- workspace := uuid.New()- workspaceID := pgtype.UUID{Bytes: workspace, Valid: true}- limit := 17-- valid := ResolveIssueCountPolicy(context.Background(), issueLimitProviderFunc(- func(_ context.Context, gotWorkspace uuid.UUID, gate entitlement.GateName) entitlement.Decision {- if gotWorkspace != workspace || gate != entitlement.GateIssueCount {- t.Fatalf("gate request = %s %s", gotWorkspace, gate)- }- return entitlement.Decision{- Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},- PolicyRevision: 9,- Reason: entitlement.ReasonRefreshed,- }- }), workspaceID)- if valid.Action != entitlement.ActionEnforce || valid.Limit != int64(limit) || valid.PolicyRevision != 9 {- t.Fatalf("valid policy = %+v", valid)- }-- malformed := ResolveIssueCountPolicy(context.Background(), issueLimitProviderFunc(- func(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {- return entitlement.Decision{- Gate: entitlement.Gate{Action: entitlement.ActionEnforce},- Reason: entitlement.ReasonCacheFresh,- }- }), workspaceID)- if malformed.Action != entitlement.ActionOff {- t.Fatalf("malformed policy = %+v", malformed)- }-- observe := ResolveIssueCountPolicy(context.Background(), issueLimitProviderFunc(- func(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {- return entitlement.Decision{- Gate: entitlement.Gate{Action: entitlement.ActionObserve, Limit: &limit},- }- }), workspaceID)- if observe.Action != entitlement.ActionOff || observe.Limit != 0 {- t.Fatalf("observe policy = %+v, want fail-open off", observe)- }-- disabled := ResolveIssueCountPolicy(context.Background(), nil, workspaceID)- if disabled.Action != entitlement.ActionOff {- t.Fatalf("disabled policy = %+v", disabled)- }-}--func TestIssueCountLimitSerializesConcurrentCreatesAndDeleteFreesCapacity(t *testing.T) {- pool := newResolveOriginatorPool(t)- ctx := context.Background()- queries := db.New(pool)- workspaceIDString, userIDString, _, _ := seedAttributionFixture(t, pool)- workspaceID := util.MustParseUUID(workspaceIDString)- userID := util.MustParseUUID(userIDString)-- var initialCount int64- if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM issue WHERE workspace_id = $1`, workspaceID).Scan(&initialCount); err != nil {- t.Fatalf("count initial issues: %v", err)- }- limit := int(initialCount + 1)- stub := entitlementtest.New()- stub.Set(uuid.UUID(workspaceID.Bytes), entitlement.GateIssueCount, entitlement.Decision{- Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},- PolicyRevision: 13,- })- svc := NewIssueService(queries, pool, nil, nil, nil)- svc.Entitlements = stub-- create := func(title string) (db.Issue, error) {- result, err := svc.Create(ctx, IssueCreateParams{- WorkspaceID: workspaceID,- Title: title,- Status: "todo",- Priority: "none",- CreatorType: "member",- CreatorID: userID,- AllowDuplicate: true,- }, IssueCreateOpts{})- return result.Issue, err- }-- start := make(chan struct{})- type createResult struct {- issue db.Issue- err error- }- results := make(chan createResult, 2)- var wg sync.WaitGroup- for i := range 2 {- wg.Add(1)- go func(index int) {- defer wg.Done()- <-start- issue, err := create(fmt.Sprintf("issue-limit-race-%d", index))- results <- createResult{issue: issue, err: err}- }(i)- }- close(start)- wg.Wait()- close(results)-- var created db.Issue- createdCount, blockedCount := 0, 0- for result := range results {- switch {- case result.err == nil:- created = result.issue- createdCount++- default:- var limitErr *IssueLimitReachedError- if !errors.As(result.err, &limitErr) {- t.Fatalf("concurrent create: %v", result.err)- }- if limitErr.Limit != int64(limit) || limitErr.PolicyRevision != 13 {- t.Fatalf("limit error = %v", result.err)- }- blockedCount++- }- }- if createdCount != 1 || blockedCount != 1 {- t.Fatalf("created = %d, blocked = %d; want 1 and 1", createdCount, blockedCount)- }-- var countAtLimit int64- if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM issue WHERE workspace_id = $1`, workspaceID).Scan(&countAtLimit); err != nil {- t.Fatalf("count issues at limit: %v", err)- }- if countAtLimit != int64(limit) {- t.Fatalf("issue count = %d, want %d", countAtLimit, limit)- }- if err := queries.DeleteIssue(ctx, db.DeleteIssueParams{ID: created.ID, WorkspaceID: workspaceID}); err != nil {- t.Fatalf("delete admitted issue: %v", err)- }- if _, err := create("issue-limit-after-delete"); err != nil {- t.Fatalf("create after delete: %v", err)- }-}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex fdb5473d4c..a1f2199cee 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -19,7 +19,6 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/attribution""github.com/multica-ai/multica/server/internal/chattitle"- "github.com/multica-ai/multica/server/internal/entitlement""github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/featureflags""github.com/multica-ai/multica/server/internal/inbox"@@ -52,9 +51,6 @@ type TaskService struct {Wakeup TaskWakeupNotifier// PRSnapshotsEnabled reports whether the server can refresh GitHub check snapshots.PRSnapshotsEnabled bool- // Entitlements supplies Cloud's workspace-scoped issue-count instruction.- // Nil keeps self-hosted and isolated test services unlimited.- Entitlements entitlement.Provider// SourceContextStorage is used only by the bounded 30-day cleanup pass for// terminal quick-create captures. Nil disables it where storage is absent.SourceContextStorage SourceContextObjectStore@@ -1637,9 +1633,6 @@ func (s *TaskService) EnqueueQuickCreateTaskWithSourceContext(ctx context.Contex}func (s *TaskService) enqueueQuickCreateTask(ctx context.Context, workspaceID, requesterID pgtype.UUID, agentID, squadID pgtype.UUID, prompt, priority, dueDate string, projectID, parentIssueID pgtype.UUID, attachmentIDs []pgtype.UUID, capture *SourceContextCapture) (db.AgentTaskQueue, error) {- if err := CheckIssueCreateCapacity(ctx, s.Queries, s.Entitlements, workspaceID); err != nil {- return db.AgentTaskQueue{}, fmt.Errorf("preflight quick-create issue capacity: %w", err)- }agent, err := s.Queries.GetAgent(ctx, agentID)if err != nil {return db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)@@ -1816,9 +1809,6 @@ func (s *TaskService) RetrySourceContextQuickCreate(ctx context.Context, workspaif canInvoke != nil && !canInvoke(agent) {return nil, ErrRerunInvokeNotAllowed}- if err := CheckIssueCreateCapacity(ctx, s.Queries, s.Entitlements, workspaceID); err != nil {- return nil, fmt.Errorf("preflight quick-create issue capacity: %w", err)- }overlay := s.buildRuntimeMCPOverlay(ctx, requesterID, agent)tx, err := s.TxStarter.Begin(ctx)diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 1e383d5632..93d162322d 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -279,31 +279,6 @@ func (q *Queries) CountIssuesInTriage(ctx context.Context, arg CountIssuesInTriareturn count, err}-const countIssuesUpTo = `-- name: CountIssuesUpTo :one-SELECT COUNT(*)::bigint-FROM (- SELECT 1- FROM issue- WHERE workspace_id = $1- LIMIT $2::bigint-) bounded_issues-`--type CountIssuesUpToParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- Limit int64 `json:"limit"`-}--// Bounded count for issue-limit admission and display. Callers pass only the-// threshold needed for their decision, avoiding a full scan in an oversized-// workspace.-func (q *Queries) CountIssuesUpTo(ctx context.Context, arg CountIssuesUpToParams) (int64, error) {- row := q.db.QueryRow(ctx, countIssuesUpTo, arg.WorkspaceID, arg.Limit)- var column_1 int64- err := row.Scan(&column_1)- return column_1, err-}-const createIssue = `-- name: CreateIssue :oneINSERT INTO issue (workspace_id, title, description, status, priority,diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 4a1a3205d6..eab3b2ddff 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -783,18 +783,6 @@ SET first_executed_at = now()WHERE id = $1 AND first_executed_at IS NULLRETURNING id, workspace_id, creator_type, creator_id, first_executed_at;--- name: CountIssuesUpTo :one--- Bounded count for issue-limit admission and display. Callers pass only the--- threshold needed for their decision, avoiding a full scan in an oversized--- workspace.-SELECT COUNT(*)::bigint-FROM (- SELECT 1- FROM issue- WHERE workspace_id = $1- LIMIT sqlc.arg('limit')::bigint-) bounded_issues;--- name: ResolveIssueRequester :oneSELECT t.originator_user_id FROM agent_task_queue tJOIN agent a ON a.id = t.agent_id