Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/34622-upgrade-links-declared-url.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@object-ui/app-shell': patch
---

fix(app-shell): the upgrade links open the runtime's declared `upgradeUrl`

Clause-②: no
Metadata-protocol: none

`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.

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:

- the storage-full banner's "Upgrade to continue";
- the AI usage indicator's call to action;
- the AI chat's quota upgrade button.

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.
14 changes: 7 additions & 7 deletions ui/packages/app-shell/src/console/ai/AiChatPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ import {
publishPlanApprovalPending,
subscribeMetadataRefresh,
} from '../../assistant/assistantBus.js';
import { getRuntimeConfig, isAiStudioEnabled } from '../../runtime-config.js';
import { getRuntimeConfig, getUpgradeUrl, isAiStudioEnabled } from '../../runtime-config.js';
import { makerConvergedOnBuild, makerVisibleAgents } from '../../hooks/surfaceAgent.js';
import { useCanAuthorMetadata } from '../../hooks/useCanAuthorMetadata.js';
import { useHomePath } from '../../hooks/useHomePath.js';
Expand Down Expand Up @@ -2935,13 +2935,13 @@ export function ChatPane({
>
<ChatbotEnhanced
className="min-h-0 flex-1 bg-background md:max-w-5xl"
// The paywall exit. Wired only when this runtime named an upstream
// cloud — an undefined `onUpgrade` renders NO upgrade button, which is
// the honest state for a runtime with no control plane behind it
// (objectui#7253).
// The paywall exit: the control plane's declared upgrade entry when
// served (objectstack#34622), else its origin. Neither ⇒ an undefined
// `onUpgrade` renders NO upgrade button, which is the honest state for
// a runtime with no control plane behind it (objectui#7253).
onUpgrade={
cloudConsoleUrl()
? () => window.open(cloudConsoleUrl(), '_blank', 'noopener,noreferrer')
(getUpgradeUrl() ?? cloudConsoleUrl())
? () => window.open(getUpgradeUrl() ?? cloudConsoleUrl(), '_blank', 'noopener,noreferrer')
: undefined
}
onOpenBuilder={openBuilder}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#34622 — the AI chat's quota exit (`onUpgrade`, the paywall
* button `ChatbotEnhanced` draws) opens the control plane's declared
* `upgradeUrl` when this runtime serves one: a deep address, which the Cloud
* console root's landing never redirects back into the environment.
*
* Absent, it is today's exit unchanged: the Cloud origin from
* `cloudConsoleUrl()`, and NO button (`onUpgrade` undefined) on a runtime that
* names no upstream cloud (objectui#7253).
*
* The pane is rendered for real with `ChatbotEnhanced` replaced by a prop
* recorder, because the `onUpgrade` prop ChatPane hands down is the contract
* under assertion. The runtime config is the REAL reader, fed one payload
* through a replaced `fetch`.
*/

import '@testing-library/jest-dom/vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import React from 'react';

/** Props of the last `ChatbotEnhanced` render. */
let captured: Record<string, unknown> = {};

vi.mock('@object-ui/plugin-chatbot', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return {
...actual,
ChatbotEnhanced: (props: Record<string, unknown>) => {
captured = props;
return null;
},
useObjectChat: () => ({
messages: [],
isLoading: false,
error: undefined,
sendMessage: vi.fn(),
stop: vi.fn(),
reload: vi.fn(),
clear: vi.fn(),
setMessages: vi.fn(),
}),
useAiModels: () => ({ models: [], defaultModelId: undefined }),
};
});

vi.mock('../../../providers/MetadataProvider', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return { ...actual, useMetadata: () => ({ apps: [] }) };
});
vi.mock('../../../providers/AdapterProvider', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
return { ...actual, useAdapter: () => null };
});
vi.mock('../../marketplace/marketplaceApi', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
cloudConsoleUrl: vi.fn(),
}));

import { I18nProvider } from '@object-ui/i18n';
import type { AgentDescriptor } from '@object-ui/plugin-chatbot';
import { ChatPane } from '../AiChatPage';
import { cloudConsoleUrl } from '../../marketplace/marketplaceApi';
import { initRuntimeConfig, resetRuntimeConfigForTesting } from '../../../runtime-config';

window.matchMedia = ((query: string) => ({
matches: false,
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
})) as unknown as typeof window.matchMedia;

const CLOUD = 'https://cloud.example.test';
const UPGRADE = 'https://cloud.example.test/_console/billing?org=acme';
const cloudMock = cloudConsoleUrl as unknown as ReturnType<typeof vi.fn>;
const openMock = vi.fn();

async function serveRuntimeConfig(payload: Record<string, unknown>) {
const realFetch = globalThis.fetch;
globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => payload })) as unknown as typeof fetch;
try {
await initRuntimeConfig();
} finally {
globalThis.fetch = realFetch;
}
}

/** Render the pane and hand back the `onUpgrade` prop it gave the chatbot. */
function renderOnUpgrade(): (() => void) | undefined {
cleanup();
captured = {};
render(
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
<MemoryRouter initialEntries={['/ai']}>
<ChatPane
agents={[{ name: 'ask', label: 'Ask' } as unknown as AgentDescriptor]}
agentsLoading={false}
agentsError={undefined}
activeAgent="ask"
chatApi="/api/v1/ai/agents/ask/chat"
apiBase="/api/v1/ai"
conversationId="conv-1"
initialMessages={[]}
pendingFirstMessageRef={{ current: null }}
onSent={vi.fn()}
onShare={vi.fn()}
/>
</MemoryRouter>
</I18nProvider>,
);
expect('onUpgrade' in captured).toBe(true);
return captured.onUpgrade as (() => void) | undefined;
}

beforeEach(() => {
window.localStorage.clear();
vi.clearAllMocks();
vi.stubGlobal('open', openMock);
resetRuntimeConfigForTesting();
cloudMock.mockReturnValue(CLOUD);
});
afterEach(() => {
cleanup();
resetRuntimeConfigForTesting();
vi.unstubAllGlobals();
});

describe('AI chat quota exit — declared upgradeUrl (objectstack#34622)', () => {
it('declared: the exit opens the declared address, not the Cloud origin', async () => {
await serveRuntimeConfig({ cloudUrl: CLOUD, upgradeUrl: UPGRADE });
const onUpgrade = renderOnUpgrade();
expect(onUpgrade).toBeTypeOf('function');
onUpgrade!();
expect(openMock).toHaveBeenCalledTimes(1);
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
});

it('declared on a runtime that names no upstream cloud: the exit is wired, to the declared address', async () => {
cloudMock.mockReturnValue('');
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
const onUpgrade = renderOnUpgrade();
expect(onUpgrade).toBeTypeOf('function');
onUpgrade!();
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
});

// CONTROL — absent, today's exit: the Cloud origin, or no button at all.
it('absent: the exit opens the Cloud origin, as before', async () => {
await serveRuntimeConfig({ cloudUrl: CLOUD });
const onUpgrade = renderOnUpgrade();
expect(onUpgrade).toBeTypeOf('function');
onUpgrade!();
expect(openMock).toHaveBeenCalledWith(CLOUD, '_blank', 'noopener,noreferrer');
});

it('absent on a runtime that names no upstream cloud: no exit (no upgrade button), as before', async () => {
cloudMock.mockReturnValue('');
await serveRuntimeConfig({ singleEnvironment: true });
expect(renderOnUpgrade()).toBeUndefined();
expect(openMock).not.toHaveBeenCalled();
});
});
11 changes: 7 additions & 4 deletions ui/packages/app-shell/src/layout/AiUsageIndicator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { formatNumber, useObjectTranslation } from '@object-ui/i18n';
import { useAgents } from '@object-ui/plugin-chatbot/core';
import { useAiUsage, type AiMeterUsage } from '../hooks/useAiUsage.js';
import { cloudConsoleUrl } from '../console/marketplace/marketplaceApi.js';
import { getUpgradeUrl } from '../runtime-config.js';

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

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

return (
Expand Down Expand Up @@ -258,7 +261,7 @@ export function AiUsageIndicator({ apiBase, enabled = true, className }: AiUsage
size="sm"
className="mt-1 h-auto p-0 text-xs"
data-testid="ai-usage-cta"
onClick={() => window.open(cloudConsoleUrl(), '_blank', 'noopener,noreferrer')}
onClick={() => window.open(ctaUrl, '_blank', 'noopener,noreferrer')}
>
{pool.upgrade
? t('console.ai.usage.ctaUpgrade', { defaultValue: 'Upgrade to keep going' })
Expand Down
12 changes: 8 additions & 4 deletions ui/packages/app-shell/src/layout/StorageUsageBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
* Only the full banner carries it, as the adjudication orders. It is not gated
* on a plan: the guardrail's refusal envelope for the same verdict declares its
* upgrade flag as the literal `true`, and a plan with no limit never reaches
* `blocked`. It links to {@link cloudConsoleUrl} — the control plane's origin,
* the most specific destination a tenant runtime is told about — and is left
* `blocked`. It links to the control plane's declared upgrade entry
* ({@link getUpgradeUrl}, objectstack#34622) when this runtime serves one: a
* deep address the Cloud console root's landing never redirects. Otherwise it
* links to {@link cloudConsoleUrl} — the control plane's origin — and is left
* out when this runtime names no upstream cloud, the rule the AI usage
* indicator's call to action already follows.
*
Expand All @@ -48,7 +50,7 @@ import { useWorkspaceAdminStatus } from '@object-ui/auth';
import { useObjectTranslation, useDisplayLocale, formatDisplayNumber } from '@object-ui/i18n';
import { useStorageUsageReading, classifyStorageUsage } from '../hooks/useStorageUsageReading.js';
import { cloudConsoleUrl } from '../console/marketplace/marketplaceApi.js';
import { isStorageUsageServed } from '../runtime-config.js';
import { getUpgradeUrl, isStorageUsageServed } from '../runtime-config.js';

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

const title = blocked
? t('console.storageUsage.blockedTitle', {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({
}));
const openMock = vi.fn();
vi.mock('../../console/marketplace/marketplaceApi', () => ({
cloudConsoleUrl: () => 'https://cloud.example',
cloudConsoleUrl: vi.fn(() => 'https://cloud.example'),
}));
vi.mock('../../hooks/useAiUsage', () => ({ useAiUsage: vi.fn() }));
// objectui#11799 — the indicator reads usage only while the agent catalog lists
Expand All @@ -41,6 +41,8 @@ vi.mock('@object-ui/plugin-chatbot/core', async (importOriginal) => ({

import { useAiUsage } from '../../hooks/useAiUsage';
import { AiUsageIndicator } from '../AiUsageIndicator';
import { cloudConsoleUrl } from '../../console/marketplace/marketplaceApi';
import { initRuntimeConfig, resetRuntimeConfigForTesting } from '../../runtime-config';

// The REAL hook, for the cases that drive a wire payload through the parser
// into the component. Loaded at module scope so its import cost is paid in the
Expand Down Expand Up @@ -308,3 +310,79 @@ describe('AiUsageIndicator', () => {
});
});
});

// objectstack#34622 — the call to action opens the control plane's declared
// `upgradeUrl` (served by /api/v1/runtime/config) when the runtime serves one,
// and is unchanged — target and show/hide rule — when it does not. Driven
// through the REAL runtime-config reader: only `fetch` is replaced, for the one
// config request.
describe('AiUsageIndicator — declared upgradeUrl (objectstack#34622)', () => {
const UPGRADE = 'https://cloud.example/_console/billing?org=acme';
const cloudMock = cloudConsoleUrl as unknown as ReturnType<typeof vi.fn>;

async function serveRuntimeConfig(payload: Record<string, unknown>) {
const realFetch = globalThis.fetch;
globalThis.fetch = vi.fn(async () => ({ ok: true, json: async () => payload })) as unknown as typeof fetch;
try {
await initRuntimeConfig();
} finally {
globalThis.fetch = realFetch;
}
}

function openCta() {
render(<AiUsageIndicator apiBase="/api/v1/ai" />);
fireEvent.click(screen.getByTestId('ai-usage-indicator'));
return screen.queryByTestId('ai-usage-cta');
}

beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal('open', openMock);
resetRuntimeConfigForTesting();
});
afterEach(() => {
resetRuntimeConfigForTesting();
cloudMock.mockImplementation(() => 'https://cloud.example');
});

it.each([
['upgrade', { upgrade: true, topUp: false }],
['top-up', { upgrade: false, topUp: true }],
])('declared: the %s CTA opens the declared address, not the Cloud origin', async (_label, flags) => {
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
setUsage({ pool: pool({ fraction: 0.95, ...flags }) });
fireEvent.click(openCta()!);
expect(openMock).toHaveBeenCalledTimes(1);
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
});

it('declared on a runtime that names no upstream cloud: the CTA is drawn, to the declared address', async () => {
cloudMock.mockReturnValue('');
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
setUsage({ pool: pool({ fraction: 0.95, upgrade: true }) });
fireEvent.click(openCta()!);
expect(openMock).toHaveBeenCalledWith(UPGRADE, '_blank', 'noopener,noreferrer');
});

it('declared: a pool with headroom still shows no CTA', async () => {
await serveRuntimeConfig({ upgradeUrl: UPGRADE });
setUsage({ pool: pool({ fraction: 0.2, upgrade: true }) });
expect(openCta()).toBeNull();
});

// CONTROL — absent, today's target and today's show/hide rule.
it('absent: the CTA opens the Cloud origin, as before', async () => {
await serveRuntimeConfig({ cloudUrl: 'https://cloud.example' });
setUsage({ pool: pool({ fraction: 0.95, upgrade: true }) });
fireEvent.click(openCta()!);
expect(openMock).toHaveBeenCalledWith('https://cloud.example', '_blank', 'noopener,noreferrer');
});

it('absent on a runtime that names no upstream cloud: no CTA, as before', async () => {
cloudMock.mockReturnValue('');
await serveRuntimeConfig({ singleEnvironment: true });
setUsage({ pool: pool({ fraction: 0.95, upgrade: true }) });
expect(openCta()).toBeNull();
});
});
Loading
Loading