Skip to content

Commit 0ee43d6

Browse files
fix(app-shell): upgrade links open the runtime's declared upgradeUrl (#34879)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBNgJrQDxaUNx2so1ektgf6A)_ Part of #34622 Clause-②: no Metadata-protocol: none repo:objectstack#3 · os-support-ai · session_01WGufzfrh8TiPJf1i2kMSoa ## 维护者速读 - **改了什么**:控制台开始读取 `/api/v1/runtime/config` 已经下发的 `upgradeUrl`(宿主声明的 Cloud 升级/计费页绝对地址),存储已满横幅的「Upgrade to continue」、AI 用量指示器的 CTA、AI 对话的配额升级按钮,在声明了该地址时直接打开它。 - **为什么改**:这三个链接原来打开 Cloud 根域名;单组织管理员访问 Cloud 根会被直接送回环境,升级链接永远到不了计费页(卡 #34622,阻塞 objectstack-ai/cloud#4804)。 - **风险与回滚**:低。未声明 `upgradeUrl` 时三个链接的目标和显示/隐藏规则与改动前完全相同;回滚即 revert 本 PR。 - **先看**:`ui/packages/app-shell/src/runtime-config.ts`(`upgradeUrl` 读取与 `getUpgradeUrl()`)、`ui/packages/app-shell/src/layout/AiUsageIndicator.tsx`(`showCta` 的门控)、`ui/packages/app-shell/src/console/ai/AiChatPage.tsx`(`onUpgrade` 一处)。 - **两分钟验证**:`pnpm --dir ui exec vitest run -t 34622 packages/app-shell/src/runtime-config.test.ts packages/app-shell/src/layout/__tests__/StorageUsageBanner.test.tsx packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx packages/app-shell/src/console/ai/__tests__/AiChatPage.upgradeUrl-34622.test.tsx`,预期 24 passed。 - **需要你做的**:无,席位落地。 ## What changes - `runtime-config.ts` reads the top-level `upgradeUrl` that `RuntimeConfigPlugin` serves (objectstack#14514, maintainer ruling cloud#1850 option A). It takes a non-empty string verbatim; absent, empty, whitespace-only and non-string values stay absent. Nothing is composed from `cloudUrl`. Each payload re-derives the key, so a later payload without it withdraws it. The new getter is `getUpgradeUrl(): string | undefined`. - `StorageUsageBanner` ("Upgrade to continue"), `AiUsageIndicator` (the CTA's `showCta` gate and its click) and `AiChatPage` (the `onUpgrade` exit only) open `getUpgradeUrl()` when it is declared. When it is absent, each one uses `cloudConsoleUrl()` as before, with the same show/hide rule (card item 3). - When `upgradeUrl` is declared on a runtime whose `cloudUrl` is empty, the link is now drawn and opens the declared address. Ruling A says the console renders the link when the key is present. - Patch changeset for `@object-ui/app-shell`. Out of scope, per the seat's correction (comment 6947939206): the marketplace "Open on Cloud" link needs a new Cloud-home key (`Clause-②: yes`, back to the seat). Nothing under `packages/cloud-connection/**` changes, and the avatar menu (#34591) is untouched. ## Tests Measured at head `4a23eddd`, after a dependency-closure build (`pnpm --workspace-concurrency=2 --filter '@object-ui/app-shell^...' build`, exit 0). - The new pins follow the shared-harness rule (ruling record 6583487846). The `runtime-config`, `StorageUsageBanner` and `AiUsageIndicator` pins are top-level `describe` blocks in each component's existing test file. `AiChatPage` has no shared harness file, so its pin is the new card-named `AiChatPage.upgradeUrl-34622.test.tsx`. - Each link has three kinds of test. Declared: it opens the declared address. Declared with no upstream cloud: it is drawn and opens the declared address. Absent (CONTROL): today's `cloudConsoleUrl()` target, and no link when the runtime names no upstream cloud. The component pins use the real runtime-config reader; only `fetch` is replaced, for the config request. - Card pins: 24 passed. The four files in full: 114 passed. - Ablation: in `runtime-config.ts`, `? body.upgradeUrl` was replaced with `? undefined` through `scripts/ablation-replace.mjs`. The anchor went from 1 hit to 0 and the blob from `a0be844f` to `8c5e8a2c`. 9 declared-path tests went red and the 15 absent/CONTROL tests stayed green, which is the expected direction. The restore was verified: the blob matched HEAD and `git diff HEAD` was empty. - Affected app-shell set: every app-shell test file that names one of the four touched modules, 148 files, 1358 passed. - `pnpm --filter @object-ui/app-shell run type-check` exit 0. Both projects ran, and `tsconfig.test.json` compiles the test files. <details><summary>Ablation run</summary> ``` ablation-replace: ok mutation landed: anchor 1 -> 0, blob a0be844 -> 8c5e8a2c969a Test Files 4 failed (4) Tests 9 failed | 15 passed | 90 skipped (114) ablation-replace: ok restored: blob == HEAD (a0be844) and `git diff HEAD` is empty ``` </details> ## Acceptance notes - The AI usage CTA opens `upgradeUrl` for both of its labels, "Upgrade to keep going" and "Add credits to continue" (top-up). The runtime config has one upgrade/billing entry, and the card names the billing/plan page for the AI quota. - Deviation, declared: I did not run the full app-shell suite locally (2291 test files). A run started under the shared lock and was stopped after 20 minutes so that it would not hold the lock any longer. The local run was narrowed to the 148 files above, which is an import-based narrowing: it does not see tests that render these components through an unnamed parent. CI's sharded `Test UI` runs the full suite. ## Verification - `node scripts/pm/dispatch-gates.mjs --commands`: 38 derived families, all run at `4a23eddd`, every one exit 0. The `--ran` reconciliation reported 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN. - `pnpm --dir ui check:new-line-citations`: 0 new citations. - `node scripts/pm/overlap-check.mjs --branch=claude/issue-34622-upgrade-url-links`: VERDICT clean, exit 0. It merges cleanly with `origin/main` (`d947a93c`), PR #34845 and PR #34851, which both share `AiChatPage.tsx`. - CI check-runs: not yet concluded when this body was written. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfrh8TiPJf1i2kMSoa)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfrh8TiPJf1i2kMSoa --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6fb3d0c commit 0ee43d6

9 files changed

Lines changed: 446 additions & 18 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
fix(app-shell): the upgrade links open the runtime's declared `upgradeUrl`
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`GET /api/v1/runtime/config` already serves a top-level `upgradeUrl` when the host declares one: the absolute address of the control plane's upgrade or billing page. The Console never read it, so three upgrade links opened the Cloud origin instead. On Cloud, the origin redirects to the console root, and a manager whose only organization has a running environment lands back in that environment, so the link never reaches billing.
11+
12+
The Console now reads `upgradeUrl` as served (an absent, empty or non-string value stays absent; nothing is composed in its place) and exposes it as `getUpgradeUrl()`. These links open it when it is declared:
13+
14+
- the storage-full banner's "Upgrade to continue";
15+
- the AI usage indicator's call to action;
16+
- the AI chat's quota upgrade button.
17+
18+
When the runtime declares no `upgradeUrl`, each link behaves as before: it opens `cloudConsoleUrl()`, and it is not drawn on a runtime that names no upstream cloud.

‎ui/packages/app-shell/src/console/ai/AiChatPage.tsx‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ import {
137137
publishPlanApprovalPending,
138138
subscribeMetadataRefresh,
139139
} from '../../assistant/assistantBus.js';
140-
import { getRuntimeConfig, isAiStudioEnabled } from '../../runtime-config.js';
140+
import { getRuntimeConfig, getUpgradeUrl, isAiStudioEnabled } from '../../runtime-config.js';
141141
import { makerConvergedOnBuild, makerVisibleAgents } from '../../hooks/surfaceAgent.js';
142142
import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js';
143143
import { useHomePath } from '../../hooks/useHomePath.js';
@@ -2939,13 +2939,13 @@ export function ChatPane({
29392939
>
29402940
<ChatbotEnhanced
29412941
className="min-h-0 flex-1 bg-background md:max-w-5xl"
2942-
// The paywall exit. Wired only when this runtime named an upstream
2943-
// cloud — an undefined `onUpgrade` renders NO upgrade button, which is
2944-
// the honest state for a runtime with no control plane behind it
2945-
// (objectui#7253).
2942+
// The paywall exit: the control plane's declared upgrade entry when
2943+
// served (objectstack#34622), else its origin. Neither ⇒ an undefined
2944+
// `onUpgrade` renders NO upgrade button, which is the honest state for
2945+
// a runtime with no control plane behind it (objectui#7253).
29462946
onUpgrade={
2947-
cloudConsoleUrl()
2948-
? () => window.open(cloudConsoleUrl(), '_blank', 'noopener,noreferrer')
2947+
(getUpgradeUrl() ?? cloudConsoleUrl())
2948+
? () => window.open(getUpgradeUrl() ?? cloudConsoleUrl(), '_blank', 'noopener,noreferrer')
29492949
: undefined
29502950
}
29512951
onOpenBuilder={openBuilder}
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#34622 — the AI chat's quota exit (`onUpgrade`, the paywall
5+
* button `ChatbotEnhanced` draws) opens the control plane's declared
6+
* `upgradeUrl` when this runtime serves one: a deep address, which the Cloud
7+
* console root's landing never redirects back into the environment.
8+
*
9+
* Absent, it is today's exit unchanged: the Cloud origin from
10+
* `cloudConsoleUrl()`, and NO button (`onUpgrade` undefined) on a runtime that
11+
* names no upstream cloud (objectui#7253).
12+
*
13+
* The pane is rendered for real with `ChatbotEnhanced` replaced by a prop
14+
* recorder, because the `onUpgrade` prop ChatPane hands down is the contract
15+
* under assertion. The runtime config is the REAL reader, fed one payload
16+
* through a replaced `fetch`.
17+
*/
18+
19+
import '@testing-library/jest-dom/vitest';
20+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
21+
import { cleanup, render } from '@testing-library/react';
22+
import { MemoryRouter } from 'react-router-dom';
23+
import React from 'react';
24+
25+
/** Props of the last `ChatbotEnhanced` render. */
26+
let captured: Record<string, unknown> = {};
27+
28+
vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
29+
const actual = await importOriginal<Record<string, unknown>>();
30+
return {
31+
...actual,
32+
ChatbotEnhanced: (props: Record<string, unknown>) => {
33+
captured = props;
34+
return null;
35+
},
36+
useObjectChat: () => ({
37+
messages: [],
38+
isLoading: false,
39+
error: undefined,
40+
sendMessage: vi.fn(),
41+
stop: vi.fn(),
42+
reload: vi.fn(),
43+
clear: vi.fn(),
44+
setMessages: vi.fn(),
45+
}),
46+
useAiModels: () => ({ models: [], defaultModelId: undefined }),
47+
};
48+
});
49+
50+
vi.mock('../../../providers/MetadataProvider', async (importOriginal) => {
51+
const actual = await importOriginal<Record<string, unknown>>();
52+
return { ...actual, useMetadata: () => ({ apps: [] }) };
53+
});
54+
vi.mock('../../../providers/AdapterProvider', async (importOriginal) => {
55+
const actual = await importOriginal<Record<string, unknown>>();
56+
return { ...actual, useAdapter: () => null };
57+
});
58+
vi.mock('../../marketplace/marketplaceApi', async (importOriginal) => ({
59+
...(await importOriginal<Record<string, unknown>>()),
60+
cloudConsoleUrl: vi.fn(),
61+
}));
62+
63+
import { I18nProvider } from '@object-ui/i18n';
64+
import type { AgentDescriptor } from '@object-ui/plugin-chatbot';
65+
import { ChatPane } from '../AiChatPage';
66+
import { cloudConsoleUrl } from '../../marketplace/marketplaceApi';
67+
import { initRuntimeConfig, resetRuntimeConfigForTesting } from '../../../runtime-config';
68+
69+
window.matchMedia = ((query: string) => ({
70+
matches: false,
71+
media: query,
72+
onchange: null,
73+
addEventListener: () => {},
74+
removeEventListener: () => {},
75+
addListener: () => {},
76+
removeListener: () => {},
77+
dispatchEvent: () => false,
78+
})) as unknown as typeof window.matchMedia;
79+
80+
const CLOUD = 'https://cloud.example.test';
81+
const UPGRADE = 'https://cloud.example.test/_console/billing?org=acme';
82+
const cloudMock = cloudConsoleUrl as unknown as ReturnType<typeof vi.fn>;
83+
const openMock = vi.fn();
84+
85+
async function serveRuntimeConfig(payload: Record<string, unknown>) {
86+
const realFetch = globalThis.fetch;
87+
globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => payload })) as unknown as typeof fetch;
88+
try {
89+
await initRuntimeConfig();
90+
} finally {
91+
globalThis.fetch = realFetch;
92+
}
93+
}
94+
95+
/** Render the pane and hand back the `onUpgrade` prop it gave the chatbot. */
96+
function renderOnUpgrade(): (() => void) | undefined {
97+
cleanup();
98+
captured = {};
99+
render(
100+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
101+
<MemoryRouter initialEntries={['/ai']}>
102+
<ChatPane
103+
agents={[{ name: 'ask', label: 'Ask' } as unknown as AgentDescriptor]}
104+
agentsLoading={false}
105+
agentsError={undefined}
106+
activeAgent="ask"
107+
chatApi="/api/v1/ai/agents/ask/chat"
108+
apiBase="/api/v1/ai"
109+
conversationId="conv-1"
110+
initialMessages={[]}
111+
pendingFirstMessageRef={{ current: null }}
112+
onSent={vi.fn()}
113+
onShare={vi.fn()}
114+
/>
115+
</MemoryRouter>
116+
</I18nProvider>,
117+
);
118+
expect('onUpgrade' in captured).toBe(true);
119+
return captured.onUpgrade as (() => void) | undefined;
120+
}
121+
122+
beforeEach(() => {
123+
window.localStorage.clear();
124+
vi.clearAllMocks();
125+
vi.stubGlobal('open', openMock);
126+
resetRuntimeConfigForTesting();
127+
cloudMock.mockReturnValue(CLOUD);
128+
});
129+
afterEach(() => {
130+
cleanup();
131+
resetRuntimeConfigForTesting();
132+
vi.unstubAllGlobals();
133+
});
134+
135+
describe('AI chat quota exit — declared upgradeUrl (objectstack#34622)', () => {
136+
it('declared: the exit opens the declared address, not the Cloud origin', async () => {
137+
await serveRuntimeConfig({ cloudUrl: CLOUD, upgradeUrl: UPGRADE });
138+
const onUpgrade = renderOnUpgrade();
139+
expect(onUpgrade).toBeTypeOf('function');
140+
onUpgrade!();
141+
expect(openMock).toHaveBeenCalledTimes(1);
142+
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
143+
});
144+
145+
it('declared on a runtime that names no upstream cloud: the exit is wired, to the declared address', async () => {
146+
cloudMock.mockReturnValue('');
147+
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
148+
const onUpgrade = renderOnUpgrade();
149+
expect(onUpgrade).toBeTypeOf('function');
150+
onUpgrade!();
151+
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
152+
});
153+
154+
// CONTROL — absent, today's exit: the Cloud origin, or no button at all.
155+
it('absent: the exit opens the Cloud origin, as before', async () => {
156+
await serveRuntimeConfig({ cloudUrl: CLOUD });
157+
const onUpgrade = renderOnUpgrade();
158+
expect(onUpgrade).toBeTypeOf('function');
159+
onUpgrade!();
160+
expect(openMock).toHaveBeenCalledWith(CLOUD, '_blank', 'noopener,noreferrer');
161+
});
162+
163+
it('absent on a runtime that names no upstream cloud: no exit (no upgrade button), as before', async () => {
164+
cloudMock.mockReturnValue('');
165+
await serveRuntimeConfig({ singleEnvironment: true });
166+
expect(renderOnUpgrade()).toBeUndefined();
167+
expect(openMock).not.toHaveBeenCalled();
168+
});
169+
});

‎ui/packages/app-shell/src/layout/AiUsageIndicator.tsx‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import { formatNumber, useObjectTranslation } from '@object-ui/i18n';
4040
import { useAgents } from '@object-ui/plugin-chatbot/core';
4141
import { useAiUsage, type AiMeterUsage } from '../hooks/useAiUsage.js';
4242
import { cloudConsoleUrl } from '../console/marketplace/marketplaceApi.js';
43+
import { getUpgradeUrl } from '../runtime-config.js';
4344

4445
/** Fraction at/above which the pool is "running low" (amber + CTA). */
4546
export const NEAR_FULL = 0.8;
@@ -214,9 +215,11 @@ export function AiUsageIndicator({ apiBase, enabled = true, className }: AiUsage
214215
return null;
215216
};
216217

217-
// No upstream cloud named by the runtime ⇒ no control plane to send anyone
218-
// to, so no CTA (objectui#7253).
219-
const showCta = tone !== 'ok' && (pool.upgrade || pool.topUp) && !!cloudConsoleUrl();
218+
// The control plane's declared upgrade entry when served (objectstack#34622),
219+
// else its origin. Neither ⇒ no control plane to send anyone to, so no CTA
220+
// (objectui#7253).
221+
const ctaUrl = getUpgradeUrl() ?? cloudConsoleUrl();
222+
const showCta = tone !== 'ok' && (pool.upgrade || pool.topUp) && !!ctaUrl;
220223
const reset = resetLabel(pool);
221224

222225
return (
@@ -258,7 +261,7 @@ export function AiUsageIndicator({ apiBase, enabled = true, className }: AiUsage
258261
size="sm"
259262
className="mt-1 h-auto p-0 text-xs"
260263
data-testid="ai-usage-cta"
261-
onClick={() => window.open(cloudConsoleUrl(), '_blank', 'noopener,noreferrer')}
264+
onClick={() => window.open(ctaUrl, '_blank', 'noopener,noreferrer')}
262265
>
263266
{pool.upgrade
264267
? t('console.ai.usage.ctaUpgrade', { defaultValue: 'Upgrade to keep going' })

‎ui/packages/app-shell/src/layout/StorageUsageBanner.tsx‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,10 @@
2323
* Only the full banner carries it, as the adjudication orders. It is not gated
2424
* on a plan: the guardrail's refusal envelope for the same verdict declares its
2525
* upgrade flag as the literal `true`, and a plan with no limit never reaches
26-
* `blocked`. It links to {@link cloudConsoleUrl} — the control plane's origin,
27-
* the most specific destination a tenant runtime is told about — and is left
26+
* `blocked`. It links to the control plane's declared upgrade entry
27+
* ({@link getUpgradeUrl}, objectstack#34622) when this runtime serves one: a
28+
* deep address the Cloud console root's landing never redirects. Otherwise it
29+
* links to {@link cloudConsoleUrl} — the control plane's origin — and is left
2830
* out when this runtime names no upstream cloud, the rule the AI usage
2931
* indicator's call to action already follows.
3032
*
@@ -48,7 +50,7 @@ import { useWorkspaceAdminStatus } from '@object-ui/auth';
4850
import { useObjectTranslation, useDisplayLocale, formatDisplayNumber } from '@object-ui/i18n';
4951
import { useStorageUsageReading, classifyStorageUsage } from '../hooks/useStorageUsageReading.js';
5052
import { cloudConsoleUrl } from '../console/marketplace/marketplaceApi.js';
51-
import { isStorageUsageServed } from '../runtime-config.js';
53+
import { getUpgradeUrl, isStorageUsageServed } from '../runtime-config.js';
5254

5355
export interface StorageUsageBannerProps {
5456
/** Override the resolved tenant runtime base (e.g. `/api/v1`). */
@@ -72,7 +74,9 @@ export function StorageUsageBanner({ apiBase, className }: StorageUsageBannerPro
7274
const blocked = view.case === 'blocked';
7375
const used = formatDisplayNumber(view.usedMb, { locale, maximumFractionDigits: 1 });
7476
const limit = formatDisplayNumber(view.limitMb, { locale, maximumFractionDigits: 1 });
75-
const upgradeUrl = blocked ? cloudConsoleUrl() : '';
77+
// The declared upgrade entry when served; absent, today's origin link and
78+
// its no-upstream rule (objectstack#34622).
79+
const upgradeUrl = blocked ? (getUpgradeUrl() ?? cloudConsoleUrl()) : '';
7680

7781
const title = blocked
7882
? t('console.storageUsage.blockedTitle', {

‎ui/packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({
2828
}));
2929
const openMock = vi.fn();
3030
vi.mock('../../console/marketplace/marketplaceApi', () => ({
31-
cloudConsoleUrl: () => 'https://cloud.example',
31+
cloudConsoleUrl: vi.fn(() => 'https://cloud.example'),
3232
}));
3333
vi.mock('../../hooks/useAiUsage', () => ({ useAiUsage: vi.fn() }));
3434
// objectui#11799 — the indicator reads usage only while the agent catalog lists
@@ -41,6 +41,8 @@ vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({
4141

4242
import { useAiUsage } from '../../hooks/useAiUsage';
4343
import { AiUsageIndicator } from '../AiUsageIndicator';
44+
import { cloudConsoleUrl } from '../../console/marketplace/marketplaceApi';
45+
import { initRuntimeConfig, resetRuntimeConfigForTesting } from '../../runtime-config';
4446

4547
// The REAL hook, for the cases that drive a wire payload through the parser
4648
// into the component. Loaded at module scope so its import cost is paid in the
@@ -308,3 +310,79 @@ describe('AiUsageIndicator', () => {
308310
});
309311
});
310312
});
313+
314+
// objectstack#34622 — the call to action opens the control plane's declared
315+
// `upgradeUrl` (served by /api/v1/runtime/config) when the runtime serves one,
316+
// and is unchanged — target and show/hide rule — when it does not. Driven
317+
// through the REAL runtime-config reader: only `fetch` is replaced, for the one
318+
// config request.
319+
describe('AiUsageIndicator — declared upgradeUrl (objectstack#34622)', () => {
320+
const UPGRADE = 'https://cloud.example/_console/billing?org=acme';
321+
const cloudMock = cloudConsoleUrl as unknown as ReturnType<typeof vi.fn>;
322+
323+
async function serveRuntimeConfig(payload: Record<string, unknown>) {
324+
const realFetch = globalThis.fetch;
325+
globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => payload })) as unknown as typeof fetch;
326+
try {
327+
await initRuntimeConfig();
328+
} finally {
329+
globalThis.fetch = realFetch;
330+
}
331+
}
332+
333+
function openCta() {
334+
render(<AiUsageIndicator apiBase="/api/v1/ai" />);
335+
fireEvent.click(screen.getByTestId('ai-usage-indicator'));
336+
return screen.queryByTestId('ai-usage-cta');
337+
}
338+
339+
beforeEach(() => {
340+
vi.clearAllMocks();
341+
vi.stubGlobal('open', openMock);
342+
resetRuntimeConfigForTesting();
343+
});
344+
afterEach(() => {
345+
resetRuntimeConfigForTesting();
346+
cloudMock.mockImplementation(() => 'https://cloud.example');
347+
});
348+
349+
it.each([
350+
['upgrade', { upgrade: true, topUp: false }],
351+
['top-up', { upgrade: false, topUp: true }],
352+
])('declared: the %s CTA opens the declared address, not the Cloud origin', async (_label, flags) => {
353+
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
354+
setUsage({ pool: pool({ fraction: 0.95, ...flags }) });
355+
fireEvent.click(openCta()!);
356+
expect(openMock).toHaveBeenCalledTimes(1);
357+
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
358+
});
359+
360+
it('declared on a runtime that names no upstream cloud: the CTA is drawn, to the declared address', async () => {
361+
cloudMock.mockReturnValue('');
362+
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
363+
setUsage({ pool: pool({ fraction: 0.95, upgrade: true }) });
364+
fireEvent.click(openCta()!);
365+
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
366+
});
367+
368+
it('declared: a pool with headroom still shows no CTA', async () => {
369+
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
370+
setUsage({ pool: pool({ fraction: 0.2, upgrade: true }) });
371+
expect(openCta()).toBeNull();
372+
});
373+
374+
// CONTROL — absent, today's target and today's show/hide rule.
375+
it('absent: the CTA opens the Cloud origin, as before', async () => {
376+
await serveRuntimeConfig({ cloudUrl: 'https://cloud.example' });
377+
setUsage({ pool: pool({ fraction: 0.95, upgrade: true }) });
378+
fireEvent.click(openCta()!);
379+
expect(openMock).toHaveBeenCalledWith('https://cloud.example', '_blank', 'noopener,noreferrer');
380+
});
381+
382+
it('absent on a runtime that names no upstream cloud: no CTA, as before', async () => {
383+
cloudMock.mockReturnValue('');
384+
await serveRuntimeConfig({ singleEnvironment: true });
385+
setUsage({ pool: pool({ fraction: 0.95, upgrade: true }) });
386+
expect(openCta()).toBeNull();
387+
});
388+
});

0 commit comments

Comments
 (0)