From 2e4e6f0863ee757001bd7c6e7f0cc3fe85058959 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:30:24 +0000 Subject: [PATCH 1/3] fix(console): show the platform-managed state on hosted storage and AI provider settings Claude-Session: https://claude.ai/code/session_01ADHkmSWkWcHBfKEZ8RmTrv Co-authored-by: Claude --- .changeset/34149-settings-platform-managed.md | 15 ++ .../src/pages/settings/SettingsView.tsx | 86 +++++- ...ettingsView.platformManaged-34149.test.tsx | 253 ++++++++++++++++++ ui/apps/console/src/pages/settings/api.ts | 23 +- .../pages/settings/platformManaged.test.ts | 76 ++++++ .../src/pages/settings/platformManaged.ts | 60 +++++ ui/packages/i18n/src/locales/ar.ts | 3 + ui/packages/i18n/src/locales/de.ts | 3 + ui/packages/i18n/src/locales/en.ts | 3 + ui/packages/i18n/src/locales/es.ts | 3 + ui/packages/i18n/src/locales/fr.ts | 3 + ui/packages/i18n/src/locales/ja.ts | 3 + ui/packages/i18n/src/locales/ko.ts | 3 + ui/packages/i18n/src/locales/pt-BR.ts | 3 + ui/packages/i18n/src/locales/ru.ts | 3 + ui/packages/i18n/src/locales/zh-Hans.ts | 3 + ui/packages/i18n/src/locales/zh-Hant.ts | 3 + 17 files changed, 536 insertions(+), 10 deletions(-) create mode 100644 .changeset/34149-settings-platform-managed.md create mode 100644 ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx create mode 100644 ui/apps/console/src/pages/settings/platformManaged.test.ts create mode 100644 ui/apps/console/src/pages/settings/platformManaged.ts diff --git a/.changeset/34149-settings-platform-managed.md b/.changeset/34149-settings-platform-managed.md new file mode 100644 index 00000000000..fb01d3b48a8 --- /dev/null +++ b/.changeset/34149-settings-platform-managed.md @@ -0,0 +1,15 @@ +--- +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +fix(console): on a cloud-managed environment, Setup's File storage page and the AI provider part of the AI page say the platform manages them + +Clause-②: no +Metadata-protocol: none + +A direct route (a bookmark or a typed URL) to Setup → File storage on a cloud-managed environment used to draw the generic load error, because the server refuses that namespace there. The console now reads that refusal by its declared shape (`409 RESOURCE_CONFLICT` with `error.details.managedBy: 'platform'`) and draws "Managed by the platform" with no form and no retry. A `409` without `managedBy: 'platform'` keeps the error card. + +The AI page is served without its provider, model and credential keys on a cloud-managed environment. When the served auth config says the environment is cloud-managed (`features.cloudManaged`) and the served page carries no `provider` key, the page draws one line saying the platform manages the AI provider; the conversation-title and observability settings stay editable. A save or an action the server refuses as platform-managed (a page loaded earlier) toasts the same managed text instead of the server's sentence. + +Self-hosted environments are unchanged. Three new keys under `console.settingsView` in every `@object-ui/i18n` pack: `platformManagedTitle`, `platformManagedBody`, `aiProviderManaged`. diff --git a/ui/apps/console/src/pages/settings/SettingsView.tsx b/ui/apps/console/src/pages/settings/SettingsView.tsx index 95089b5e639..fc998bd2d42 100644 --- a/ui/apps/console/src/pages/settings/SettingsView.tsx +++ b/ui/apps/console/src/pages/settings/SettingsView.tsx @@ -12,10 +12,11 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import { toast } from 'sonner'; import { ConsolePageHeader } from '@object-ui/app-shell'; -import { Loader2, ArrowLeft, ChevronRight, RotateCcw, ShieldAlert } from 'lucide-react'; +import { Loader2, ArrowLeft, ChevronRight, RotateCcw, ShieldAlert, Cloud } from 'lucide-react'; import { Button, Card, CardContent, Skeleton, Badge, getLazyIcon } from '@object-ui/components'; import { ExpressionEvaluator } from '@object-ui/core'; import { useObjectTranslation } from '@object-ui/i18n'; +import { useAuth } from '@object-ui/auth'; import { SettingsField } from './SettingsField'; import type { MapRefusalAt } from './SettingsMapField'; import { fieldWording, settingsFieldRefusals } from './settingsFieldRefusals'; @@ -28,6 +29,7 @@ import { type JudgedClientAddress, type JudgedClientAddressRoute, } from './api'; +import { AI_PROVIDER_NAMESPACE, aiProviderManagedByPlatform, isPlatformManagedRefusal } from './platformManaged'; import { resolveLabel, type SettingsNamespacePayload, type Specifier } from './types'; import { useSettingsLabel, type SettingsLabelHelpers } from './useSettingsLabel'; import { useUnsavedLeaveGuard } from './useUnsavedLeaveGuard'; @@ -371,7 +373,12 @@ export function SettingsView() { * when it sent one; without one the card shows `console.settingsView.loadError`, * translated at render so the fetch below reads no `t` (objectui#13254). */ - const [error, setError] = useState<{ message?: string } | null>(null); + /** + * The load's failure, or null. `managed` marks the hosted refusal + * (`platformManaged.ts`): the platform provides this page's settings, so the + * page says so instead of drawing an error or a form. + */ + const [error, setError] = useState<{ message?: string; managed?: boolean } | null>(null); /** Live edit map keyed by spec.key. Falls back to resolved value when undefined. */ const [draft, setDraft] = useState>({}); /** @@ -448,7 +455,11 @@ export function SettingsView() { setFieldErrors({}); setCryptoRefusal(null); } catch (err: any) { - setError({ message: err?.message }); + setError( + isPlatformManagedRefusal(err?.status, err?.payload) + ? { managed: true } + : { message: err?.message }, + ); } finally { setLoading(false); } @@ -456,6 +467,35 @@ export function SettingsView() { void loadNamespace(); }, [namespace]); + /** + * The served auth config's `features`, read once per page that can use them: + * the AI page draws one line when the platform manages its provider + * ({@link aiProviderManagedByPlatform}). The auth client holds the config + * sign-in already read, so this asks no new request. The read goes through a + * ref so the effect keys on the namespace alone (AGENTS.md #10). + */ + const { getAuthConfig } = useAuth(); + const getAuthConfigRef = useRef(getAuthConfig); + useEffect(() => { + getAuthConfigRef.current = getAuthConfig; + }); + const [authFeatures, setAuthFeatures] = useState<{ cloudManaged?: unknown } | null>(null); + const readsAuthFeatures = namespace === AI_PROVIDER_NAMESPACE; + useEffect(() => { + if (!readsAuthFeatures) return; + let live = true; + Promise.resolve(getAuthConfigRef.current?.()) + .then((config) => { + if (live) setAuthFeatures(config?.features ?? null); + }) + .catch(() => { + // Unreadable: no line, the page is what it serves. + }); + return () => { + live = false; + }; + }, [readsAuthFeatures]); + /** * The caller's address as the server judges it, on a page that draws it * ({@link CLIENT_ADDRESS_ROUTES}), or null: another page, not read yet, or @@ -529,6 +569,24 @@ export function SettingsView() { ); } + if (error?.managed) { + // No form and no retry: nothing here is the administrator's to set. + return ( +
+ + + + + +
+ ); + } + if (error) { return (
@@ -550,6 +608,7 @@ export function SettingsView() { const Icon = manifest.icon ? getLazyIcon(manifest.icon) : null; const title = labels.title(resolveLabel(manifest.label)); const description = labels.description(manifest.description); + const aiProviderManaged = aiProviderManagedByPlatform(namespace, manifest.specifiers, authFeatures); /** * Read the namespace again after a successful save or action and take the @@ -650,6 +709,10 @@ export function SettingsView() { ? t('console.settingsView.cryptoRefusalToast', { subject: refusal.subject }) : t('console.settingsView.cryptoRefusalToastNoSubject'), ); + } else if (isPlatformManagedRefusal(err?.status, err?.payload)) { + // A page read before the environment became hosted wrote a key the + // platform now manages: nothing was written. + toast.error(t('console.settingsView.platformManagedTitle')); } else { // Per-field rejections render against the inputs that caused them // (objectstack#4224). `extractFieldErrors` reads `details.fields`, so it @@ -731,7 +794,11 @@ export function SettingsView() { toast.error(result.message ?? t('console.settingsView.actionFailed')); } } catch (err: any) { - toast.error(err?.message ?? t('console.settingsView.actionFailed')); + toast.error( + isPlatformManagedRefusal(err?.status, err?.payload) + ? t('console.settingsView.platformManagedTitle') + : (err?.message ?? t('console.settingsView.actionFailed')), + ); } finally { setSaving(false); } @@ -790,6 +857,17 @@ export function SettingsView() {

{manifest.helpText}

) : null} + {aiProviderManaged ? ( + + +

+

+
+
+ ) : null} + {cryptoRefusal ? ( diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx new file mode 100644 index 00000000000..644bd31e8f3 --- /dev/null +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx @@ -0,0 +1,253 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * SettingsView on a cloud-managed environment (objectstack#34149). + * + * The server half (`cloud-managed-settings.ts` in service-settings) refuses the + * hosted `storage` namespace, the writes naming a hidden `ai` key and the + * refused actions with `409 RESOURCE_CONFLICT`, `details.managedBy: + * 'platform'`, and serves `ai` projected (provider, model and credential keys + * left out). A direct route to either page must say the platform manages it, + * not draw an empty form or a generic error. Self-hosted pages are unchanged. + * + * The refusal is read by its code and `details.managedBy`; a 409 carrying + * neither is pinned to today's error card (CONTROL). + */ + +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { I18nProvider } from '@object-ui/i18n'; + +const getSettingsNamespace = vi.fn(); +const saveSettingsNamespace = vi.fn(); +const runSettingsAction = vi.fn(); + +vi.mock('../api', async () => { + const actual = await vi.importActual('../api'); + return { + ...actual, + getSettingsNamespace: (...a: unknown[]) => getSettingsNamespace(...a), + saveSettingsNamespace: (...a: unknown[]) => saveSettingsNamespace(...a), + runSettingsAction: (...a: unknown[]) => runSettingsAction(...a), + }; +}); + +const toastError = vi.fn(); +const toastSuccess = vi.fn(); +vi.mock('sonner', () => ({ + toast: { + error: (...a: unknown[]) => toastError(...a), + success: (...a: unknown[]) => toastSuccess(...a), + }, +})); + +/** The served auth config; each case sets its `features`. */ +let authFeatures: Record | undefined; +const getAuthConfig = vi.fn(async () => ({ features: authFeatures })); +const AUTH = { getAuthConfig }; +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => AUTH, +})); + +import { SettingsView } from '../SettingsView'; + +const MANAGED_TITLE = 'Managed by the platform'; +const AI_LINE = 'The AI provider, its model and credentials are managed by the platform.'; + +/** A failed read as `api.ts`'s `jsonOrThrow` builds it. */ +function rejection(status: number, error: Record) { + const err = new Error(String(error.message)) as Error & { status?: number; payload?: unknown }; + err.status = status; + err.payload = { success: false, error }; + return err; +} + +/** The hosted refusal of `GET /api/settings/storage`, as service-settings answers it. */ +const HOSTED_STORAGE_REFUSAL = () => + rejection(409, { + code: 'RESOURCE_CONFLICT', + message: + 'This environment is cloud-managed: file storage is provided and configured by the hosting platform, so its settings are not shown here.', + details: { namespace: 'storage', managedBy: 'platform' }, + }); + +const STORAGE_PAYLOAD = { + manifest: { + namespace: 'storage', + label: 'File storage', + specifiers: [{ type: 'text', key: 'bucket', label: 'Bucket' }], + }, + values: { bucket: { value: 'uploads', source: 'default' } }, +}; + +/** `ai` as a hosted server serves it: the provider keys and their buttons left out. */ +const AI_PROJECTED = { + manifest: { + namespace: 'ai', + label: 'AI', + specifiers: [ + { type: 'group', label: 'Conversation titles' }, + { type: 'boolean', key: 'title_generation_enabled', label: 'Generate titles' }, + { type: 'group', label: 'Observability' }, + { type: 'boolean', key: 'trace_enabled', label: 'Trace' }, + { type: 'action_button', id: 'flush_traces', label: 'Flush traces' }, + ], + }, + values: { + title_generation_enabled: { value: true, source: 'default' }, + trace_enabled: { value: false, source: 'default' }, + }, +}; + +/** `ai` with its provider served, as a self-hosted server serves it. */ +const AI_FULL = { + manifest: { + namespace: 'ai', + label: 'AI', + specifiers: [ + { type: 'select', key: 'provider', label: 'Provider', options: [{ value: 'openai', label: 'OpenAI' }] }, + { type: 'action_button', id: 'test', label: 'Test connection' }, + { type: 'boolean', key: 'title_generation_enabled', label: 'Generate titles' }, + ], + }, + values: { + provider: { value: 'openai', source: 'default' }, + title_generation_enabled: { value: true, source: 'default' }, + }, +}; + +function renderView(namespace: string) { + return render( + + + + } /> + + + , + ); +} + +beforeEach(() => { + getSettingsNamespace.mockReset(); + saveSettingsNamespace.mockReset(); + runSettingsAction.mockReset(); + toastError.mockReset(); + toastSuccess.mockReset(); + getAuthConfig.mockClear(); + authFeatures = undefined; +}); +afterEach(() => cleanup()); + +describe('the hosted storage page (objectstack#34149)', () => { + it('draws the managed state for a 409 RESOURCE_CONFLICT naming managedBy platform: no form, no retry', async () => { + getSettingsNamespace.mockRejectedValue(HOSTED_STORAGE_REFUSAL()); + const { container } = renderView('storage'); + + const managed = await screen.findByTestId('settings-platform-managed'); + expect(managed.textContent).toContain(MANAGED_TITLE); + // Not the error card: the server's sentence is not drawn. + expect(screen.queryByText(/cloud-managed: file storage/)).toBeNull(); + // No form, no save bar, no retry. + expect(container.querySelector('input, textarea, [role="combobox"]')).toBeNull(); + expect(screen.queryByRole('button', { name: /retry|save/i })).toBeNull(); + expect(getSettingsNamespace).toHaveBeenCalledTimes(1); + }); + + it('CONTROL: a 409 RESOURCE_CONFLICT without managedBy keeps the error card', async () => { + getSettingsNamespace.mockRejectedValue( + rejection(409, { + code: 'RESOURCE_CONFLICT', + message: 'Some other conflict.', + details: { namespace: 'storage' }, + }), + ); + renderView('storage'); + + expect(await screen.findByText('Some other conflict.')).toBeTruthy(); + expect(screen.queryByTestId('settings-platform-managed')).toBeNull(); + }); + + it('CONTROL: a self-hosted storage page renders its form', async () => { + getSettingsNamespace.mockResolvedValue(STORAGE_PAYLOAD); + const { container } = renderView('storage'); + + expect(await screen.findByText('Bucket')).toBeTruthy(); + expect(container.querySelector('input')).not.toBeNull(); + expect(screen.queryByTestId('settings-platform-managed')).toBeNull(); + }); +}); + +describe('the hosted AI page (objectstack#34149)', () => { + it('draws one managed line above the served keys when hosted and the provider was withheld', async () => { + authFeatures = { cloudManaged: true }; + getSettingsNamespace.mockResolvedValue(AI_PROJECTED); + renderView('ai'); + + const line = await screen.findByTestId('settings-ai-provider-managed'); + expect(line.textContent).toBe(AI_LINE); + // The tenant's own preferences stay editable. + expect(screen.getByText('Generate titles')).toBeTruthy(); + expect(screen.getByText('Trace')).toBeTruthy(); + }); + + it('CONTROL: a self-hosted AI page draws no line', async () => { + authFeatures = { cloudManaged: false }; + getSettingsNamespace.mockResolvedValue(AI_FULL); + renderView('ai'); + + expect(await screen.findByText('Provider')).toBeTruthy(); + await waitFor(() => expect(getAuthConfig).toHaveBeenCalled()); + expect(screen.queryByTestId('settings-ai-provider-managed')).toBeNull(); + }); + + it('CONTROL: a hosted server that still serves the provider draws its form and no line', async () => { + authFeatures = { cloudManaged: true }; + getSettingsNamespace.mockResolvedValue(AI_FULL); + renderView('ai'); + + expect(await screen.findByText('Provider')).toBeTruthy(); + await waitFor(() => expect(getAuthConfig).toHaveBeenCalled()); + expect(screen.queryByTestId('settings-ai-provider-managed')).toBeNull(); + }); + + it('an action refused at run time as platform-managed toasts the managed text', async () => { + getSettingsNamespace.mockResolvedValue(AI_FULL); + runSettingsAction.mockRejectedValue( + rejection(409, { + code: 'RESOURCE_CONFLICT', + message: "This environment is cloud-managed: the AI provider, its model and credentials is provided and configured by the hosting platform, so 'test' is not run here.", + details: { namespace: 'ai', managedBy: 'platform', actionId: 'test' }, + }), + ); + renderView('ai'); + + fireEvent.click(await screen.findByRole('button', { name: 'Test connection' })); + await waitFor(() => expect(toastError).toHaveBeenCalledWith(MANAGED_TITLE)); + }); + + it('a save refused as platform-managed toasts the managed text', async () => { + getSettingsNamespace.mockResolvedValue(AI_FULL); + saveSettingsNamespace.mockRejectedValue( + rejection(409, { + code: 'RESOURCE_CONFLICT', + message: "This environment is cloud-managed: … so 'provider' cannot be changed here. Nothing was written.", + details: { namespace: 'ai', managedBy: 'platform', keys: ['provider'] }, + }), + ); + renderView('ai'); + + const toggle = await screen.findByRole('switch'); + fireEvent.click(toggle); + fireEvent.click(await screen.findByRole('button', { name: /save changes/i })); + await waitFor(() => expect(toastError).toHaveBeenCalledWith(MANAGED_TITLE)); + }); +}); diff --git a/ui/apps/console/src/pages/settings/api.ts b/ui/apps/console/src/pages/settings/api.ts index 55abaf1f6ac..d12bee2a3bf 100644 --- a/ui/apps/console/src/pages/settings/api.ts +++ b/ui/apps/console/src/pages/settings/api.ts @@ -8,6 +8,7 @@ import type { SettingsListResponse, SettingsNamespacePayload, } from './types'; +import { isPlatformManagedRefusal } from './platformManaged'; const SERVER_URL = (import.meta.env.VITE_SERVER_URL || '').replace(/\/$/, ''); const BASE = `${SERVER_URL}/api/settings`; @@ -86,15 +87,20 @@ function assertShape(value: unknown, keys: Array, what: str return value as T; } +/** A failed call as the view reads it: the server's sentence, `status`, and the raw body on `payload`. */ +function failureOf(res: Response, detail: any): Error & { status?: number; payload?: any } { + const err = new Error(detail?.error?.message ?? res.statusText) as Error & { status?: number; payload?: any }; + err.status = res.status; + // The raw body, NOT unwrapped: `err.payload.error` is what the view reads + // for the locked key and the per-field rejections (objectstack#4224). + err.payload = detail; + return err; +} + async function jsonOrThrow(res: Response): Promise { if (!res.ok) { const detail = await res.json().catch(() => ({ error: { message: res.statusText } })); - const err = new Error(detail?.error?.message ?? res.statusText) as Error & { status?: number; payload?: any }; - err.status = res.status; - // The raw body, NOT unwrapped: `err.payload.error` is what the view reads - // for the locked key and the per-field rejections (objectstack#4224). - err.payload = detail; - throw err; + throw failureOf(res, detail); } return unwrapEnvelope(await res.json()) as T; } @@ -228,6 +234,11 @@ export async function runSettingsAction( const apiError = (body as { error?: { message?: unknown; details?: unknown } } | null)?.error; if (isActionResult(apiError?.details)) return apiError.details; + // The hosting platform manages what the action exercises (a page loaded + // before the environment became hosted): thrown like a failed read, so the + // view reads it by its shape and draws the managed text, not the sentence. + if (isPlatformManagedRefusal(res.status, body)) throw failureOf(res, body); + // Neither: a crash (`INTERNAL_ERROR`), a 403, or a non-JSON body. Keep the // server's sentence when there is one. const message = typeof apiError?.message === 'string' ? apiError.message : res.statusText; diff --git a/ui/apps/console/src/pages/settings/platformManaged.test.ts b/ui/apps/console/src/pages/settings/platformManaged.test.ts new file mode 100644 index 00000000000..7665da61889 --- /dev/null +++ b/ui/apps/console/src/pages/settings/platformManaged.test.ts @@ -0,0 +1,76 @@ +/** + * The hosted refusal and the AI projection, read by their declared shapes + * (objectstack#34149), and `runSettingsAction` handing the refusal to the view. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { aiProviderManagedByPlatform, isPlatformManagedRefusal } from './platformManaged'; +import { runSettingsAction } from './api'; + +const MANAGED = { + success: false, + error: { + code: 'RESOURCE_CONFLICT', + message: 'This environment is cloud-managed: … so its settings are not shown here.', + details: { namespace: 'storage', managedBy: 'platform' }, + }, +}; + +describe('isPlatformManagedRefusal', () => { + it('reads 409 + RESOURCE_CONFLICT + details.managedBy platform', () => { + expect(isPlatformManagedRefusal(409, MANAGED)).toBe(true); + }); + + it('refuses every other shape', () => { + const withDetails = (details: unknown) => ({ ...MANAGED, error: { ...MANAGED.error, details } }); + expect(isPlatformManagedRefusal(400, MANAGED)).toBe(false); + expect(isPlatformManagedRefusal(409, { ...MANAGED, error: { ...MANAGED.error, code: 'SETTINGS_LOCKED' } })).toBe(false); + expect(isPlatformManagedRefusal(409, withDetails({ namespace: 'storage' }))).toBe(false); + expect(isPlatformManagedRefusal(409, withDetails({ namespace: 'storage', managedBy: 'operator' }))).toBe(false); + expect(isPlatformManagedRefusal(409, withDetails(undefined))).toBe(false); + expect(isPlatformManagedRefusal(409, null)).toBe(false); + expect(isPlatformManagedRefusal(undefined, MANAGED)).toBe(false); + }); +}); + +describe('aiProviderManagedByPlatform', () => { + const projected = [{ key: 'title_generation_enabled' }, {}]; + const full = [{ key: 'provider' }, { key: 'title_generation_enabled' }]; + + it('needs the hosted flag, the ai namespace and a withheld provider', () => { + expect(aiProviderManagedByPlatform('ai', projected, { cloudManaged: true })).toBe(true); + expect(aiProviderManagedByPlatform('ai', full, { cloudManaged: true })).toBe(false); + expect(aiProviderManagedByPlatform('ai', projected, { cloudManaged: false })).toBe(false); + expect(aiProviderManagedByPlatform('ai', projected, { cloudManaged: 'true' })).toBe(false); + expect(aiProviderManagedByPlatform('ai', projected, null)).toBe(false); + expect(aiProviderManagedByPlatform('mail', projected, { cloudManaged: true })).toBe(false); + }); +}); + +describe('runSettingsAction and the hosted refusal', () => { + const fetchMock = vi.fn(); + const answer = (body: unknown, status: number): Response => + ({ ok: status < 300, status, statusText: 'Conflict', json: async () => body }) as unknown as Response; + + beforeEach(() => { + fetchMock.mockReset(); + vi.stubGlobal('fetch', fetchMock); + }); + afterEach(() => vi.unstubAllGlobals()); + + it('throws the refusal with its status and raw body, so the view reads it by shape', async () => { + const body = { ...MANAGED, error: { ...MANAGED.error, details: { namespace: 'ai', managedBy: 'platform', actionId: 'test' } } }; + fetchMock.mockResolvedValue(answer(body, 409)); + const err = await runSettingsAction('ai', 'test').then(() => null, (e) => e); + expect(err).toBeInstanceOf(Error); + expect(err.status).toBe(409); + expect(err.payload).toEqual(body); + }); + + it('CONTROL: another 409 stays a reported verdict with the server sentence', async () => { + fetchMock.mockResolvedValue( + answer({ success: false, error: { code: 'RESOURCE_CONFLICT', message: 'Busy.', details: { namespace: 'ai' } } }, 409), + ); + await expect(runSettingsAction('ai', 'test')).resolves.toEqual({ ok: false, message: 'Busy.' }); + }); +}); diff --git a/ui/apps/console/src/pages/settings/platformManaged.ts b/ui/apps/console/src/pages/settings/platformManaged.ts new file mode 100644 index 00000000000..22b9853c533 --- /dev/null +++ b/ui/apps/console/src/pages/settings/platformManaged.ts @@ -0,0 +1,60 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * What a cloud-managed environment's settings doors tell the console, read by + * their declared shapes (`cloud-managed-settings.ts` in service-settings). + * + * A hosted environment's file storage and its AI provider are provided and + * configured by the hosting platform. The server answers that in two ways: + * + * - a door it refuses (the whole `storage` namespace, a write naming a hidden + * `ai` key, the refused actions) answers `409 RESOURCE_CONFLICT` with + * `error.details.managedBy: 'platform'`; + * - the `ai` namespace is served PROJECTED: its provider, model and + * credential keys are left out, so nothing errors. + * + * ⛔ The refusal is read by its code and `details.managedBy`, never by its + * message: `RESOURCE_CONFLICT` is a shared code, and a 409 without + * `managedBy: 'platform'` stays an ordinary failure. + */ + +/** The `details.managedBy` value that names the hosting platform. */ +const MANAGED_BY_PLATFORM = 'platform'; + +/** + * Whether a failed settings call was refused because the hosting platform + * manages what was asked for. `status` is the HTTP status, `body` the raw + * error body (`{ success: false, error: { code, message, details } }`). + */ +export function isPlatformManagedRefusal(status: number | undefined, body: unknown): boolean { + if (status !== 409 || !body || typeof body !== 'object') return false; + const error = (body as { error?: unknown }).error; + if (!error || typeof error !== 'object') return false; + const { code, details } = error as { code?: unknown; details?: unknown }; + if (code !== 'RESOURCE_CONFLICT' || !details || typeof details !== 'object') return false; + return (details as { managedBy?: unknown }).managedBy === MANAGED_BY_PLATFORM; +} + +/** The namespace whose provider keys a hosted environment withholds. */ +export const AI_PROVIDER_NAMESPACE = 'ai'; +/** The key that names the AI provider; the projection drops it first. */ +const AI_PROVIDER_KEY = 'provider'; + +/** + * Whether the AI page should say its provider is managed by the platform. + * + * Two served facts, both required: the auth config's `features.cloudManaged` + * (plugin-auth answers it from the same `isCloudManaged()` the settings + * projection reads) says this environment is hosted, and the served manifest + * carrying no `provider` key says the projection actually ran. A hosted + * server that still serves the provider draws its form and no line, so the + * line never sits above a provider field it calls managed. + */ +export function aiProviderManagedByPlatform( + namespace: string, + specifiers: ReadonlyArray<{ key?: string }>, + features: { cloudManaged?: unknown } | null | undefined, +): boolean { + if (namespace !== AI_PROVIDER_NAMESPACE || features?.cloudManaged !== true) return false; + return !specifiers.some((s) => s.key === AI_PROVIDER_KEY); +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 2e2bfc3aa9f..26b24f94515 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -2509,6 +2509,9 @@ const ar = { fieldErrorsToast_many: "{{count}} إعدادًا يحتاج إلى مراجعة: {{settings}}", fieldErrorsToast_other: "{{count}} إعداد يحتاج إلى مراجعة: {{settings}}", cryptoRefusalTitle: "لا يمكن لهذا النشر تشفير الأسرار", + platformManagedTitle: "تتم إدارته بواسطة المنصة", + platformManagedBody: "توفر منصة الاستضافة هذا الإعداد وتهيئه لهذه البيئة، لذا لا يُضبط هنا.", + aiProviderManaged: "تتم إدارة مزوّد الذكاء الاصطناعي ونموذجه وبيانات اعتماده بواسطة المنصة.", cryptoRefusalSubjectSuffix: "معلن كمشفَّر، لذلك لم تتم كتابة أي شيء.", cryptoRefusalNoSubject: "تم رفض القيمة المعلنة كمشفَّرة، لذلك لم تتم كتابة أي شيء.", cryptoRefusalToast: "تعذّر تشفير الأسرار: {{subject}}", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index ebca91fe60c..5d90dbcac23 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -2254,6 +2254,9 @@ const de = { fieldErrorsToast_one: "{{count}} Einstellung muss überprüft werden: {{settings}}", fieldErrorsToast_other: "{{count}} Einstellungen müssen überprüft werden: {{settings}}", cryptoRefusalTitle: "Diese Installation kann keine Geheimnisse verschlüsseln", + platformManagedTitle: "Von der Plattform verwaltet", + platformManagedBody: "Die Hosting-Plattform stellt dies für diese Umgebung bereit und konfiguriert es, daher wird es hier nicht eingestellt.", + aiProviderManaged: "Der KI-Anbieter, sein Modell und seine Zugangsdaten werden von der Plattform verwaltet.", cryptoRefusalSubjectSuffix: "ist als verschlüsselt deklariert, daher wurde nichts geschrieben.", cryptoRefusalNoSubject: "Der als verschlüsselt deklarierte Wert wurde abgelehnt, daher wurde nichts geschrieben.", cryptoRefusalToast: "Geheimnisse können nicht verschlüsselt werden: {{subject}}", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index e4a62d59769..ca849227dc0 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2390,6 +2390,9 @@ const en = { // would have left a single translated string among a dozen hardcoded // ones — and deferred them to this card, which converts the screen whole. cryptoRefusalTitle: 'This deployment cannot encrypt secrets', + platformManagedTitle: 'Managed by the platform', + platformManagedBody: 'The hosting platform provides and configures this for this environment, so it is not set here.', + aiProviderManaged: 'The AI provider, its model and credentials are managed by the platform.', // `{{subject}}` is rendered as a `< code >` element by the view, so the // sentence is split around it rather than interpolated. cryptoRefusalSubjectSuffix: 'is declared encrypted, so nothing was written.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 8e20d1a6431..95711bc36e1 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -2320,6 +2320,9 @@ const es = { fieldErrorsToast_many: "{{count}} de ajustes requieren atención: {{settings}}", fieldErrorsToast_other: "{{count}} ajustes requieren atención: {{settings}}", cryptoRefusalTitle: "Esta instalación no puede cifrar secretos", + platformManagedTitle: "Gestionado por la plataforma", + platformManagedBody: "La plataforma de alojamiento proporciona y configura esto para este entorno, por lo que no se ajusta aquí.", + aiProviderManaged: "El proveedor de IA, su modelo y sus credenciales los gestiona la plataforma.", cryptoRefusalSubjectSuffix: "está declarado como cifrado, por lo que no se escribió nada.", cryptoRefusalNoSubject: "El valor declarado como cifrado fue rechazado, por lo que no se escribió nada.", cryptoRefusalToast: "No se pueden cifrar los secretos: {{subject}}", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5b50e54b54f..b2101fc46d0 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -2316,6 +2316,9 @@ const fr = { fieldErrorsToast_many: "{{count}} de paramètres nécessitent votre attention : {{settings}}", fieldErrorsToast_other: "{{count}} paramètres nécessitent votre attention : {{settings}}", cryptoRefusalTitle: "Ce déploiement ne peut pas chiffrer les secrets", + platformManagedTitle: "Géré par la plateforme", + platformManagedBody: "La plateforme d'hébergement fournit et configure ceci pour cet environnement ; il n'est donc pas réglé ici.", + aiProviderManaged: "Le fournisseur d'IA, son modèle et ses identifiants sont gérés par la plateforme.", cryptoRefusalSubjectSuffix: "est déclaré chiffré, aucune écriture n'a donc eu lieu.", cryptoRefusalNoSubject: "La valeur déclarée chiffrée a été refusée, aucune écriture n'a donc eu lieu.", cryptoRefusalToast: "Impossible de chiffrer les secrets : {{subject}}", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 7e62b893b7a..1c01212a433 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -2256,6 +2256,9 @@ const ja = { fieldErrorsToast_one: "{{count}} 件の設定を確認してください:{{settings}}", fieldErrorsToast_other: "{{count}} 件の設定を確認してください:{{settings}}", cryptoRefusalTitle: "このデプロイメントはシークレットを暗号化できません", + platformManagedTitle: "プラットフォームが管理しています", + platformManagedBody: "ホスティングプラットフォームがこの環境向けに提供・設定しているため、ここでは設定しません。", + aiProviderManaged: "AI プロバイダー、モデル、認証情報はプラットフォームが管理しています。", cryptoRefusalSubjectSuffix: "は暗号化対象として宣言されているため、何も書き込まれませんでした。", cryptoRefusalNoSubject: "暗号化対象として宣言された値は拒否され、何も書き込まれませんでした。", cryptoRefusalToast: "シークレットを暗号化できません: {{subject}}", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 0bf0e9b0e39..454ca8aa6ff 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -2254,6 +2254,9 @@ const ko = { fieldErrorsToast_one: "확인이 필요한 설정 {{count}}개: {{settings}}", fieldErrorsToast_other: "확인이 필요한 설정 {{count}}개: {{settings}}", cryptoRefusalTitle: "이 배포는 시크릿을 암호화할 수 없습니다", + platformManagedTitle: "플랫폼에서 관리합니다", + platformManagedBody: "호스팅 플랫폼이 이 환경을 위해 제공하고 구성하므로 여기에서 설정하지 않습니다.", + aiProviderManaged: "AI 공급자, 모델 및 자격 증명은 플랫폼에서 관리합니다.", cryptoRefusalSubjectSuffix: "은(는) 암호화 대상으로 선언되어 아무것도 기록되지 않았습니다.", cryptoRefusalNoSubject: "암호화 대상으로 선언된 값이 거부되어 아무것도 기록되지 않았습니다.", cryptoRefusalToast: "시크릿을 암호화할 수 없습니다: {{subject}}", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 3941b6e8e9e..854b7aed8af 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -2315,6 +2315,9 @@ const pt = { fieldErrorsToast_many: "{{count}} de configurações precisam de atenção: {{settings}}", fieldErrorsToast_other: "{{count}} configurações precisam de atenção: {{settings}}", cryptoRefusalTitle: "Esta implantação não consegue criptografar segredos", + platformManagedTitle: "Gerenciado pela plataforma", + platformManagedBody: "A plataforma de hospedagem fornece e configura isso para este ambiente, por isso não é definido aqui.", + aiProviderManaged: "O provedor de IA, seu modelo e suas credenciais são gerenciados pela plataforma.", cryptoRefusalSubjectSuffix: "está declarado como criptografado, portanto nada foi gravado.", cryptoRefusalNoSubject: "O valor declarado como criptografado foi recusado, portanto nada foi gravado.", cryptoRefusalToast: "Não é possível criptografar segredos: {{subject}}", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 38a5809e915..e2ddd67ae4d 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -2388,6 +2388,9 @@ const ru = { fieldErrorsToast_many: "{{count}} настроек требуют внимания: {{settings}}", fieldErrorsToast_other: "{{count}} настройки требуют внимания: {{settings}}", cryptoRefusalTitle: "Эта установка не может шифровать секреты", + platformManagedTitle: "Управляется платформой", + platformManagedBody: "Хостинг-платформа предоставляет и настраивает это для данной среды, поэтому здесь это не настраивается.", + aiProviderManaged: "Поставщик ИИ, его модель и учётные данные управляются платформой.", cryptoRefusalSubjectSuffix: "объявлен зашифрованным, поэтому ничего не было записано.", cryptoRefusalNoSubject: "Значение, объявленное зашифрованным, было отклонено, поэтому ничего не было записано.", cryptoRefusalToast: "Не удалось зашифровать секреты: {{subject}}", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 369fc882136..9b14fa98973 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -2010,6 +2010,9 @@ const zh = { fieldErrorsToast_one: '{{count}} 项设置需要处理:{{settings}}', fieldErrorsToast_other: '{{count}} 项设置需要处理:{{settings}}', cryptoRefusalTitle: '此部署无法加密机密信息', + platformManagedTitle: '此项由平台托管', + platformManagedBody: '托管平台为此环境提供并配置此项,因此无需在此设置。', + aiProviderManaged: 'AI 提供商、模型与凭据由平台托管。', cryptoRefusalSubjectSuffix: '被声明为加密字段,因此未写入任何内容。', cryptoRefusalNoSubject: '声明为加密的值被拒绝,因此未写入任何内容。', cryptoRefusalToast: '无法加密机密信息:{{subject}}', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 306be5739ae..39dc6b876e9 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -2010,6 +2010,9 @@ const zhHant = { fieldErrorsToast_one: '{{count}} 項設定需要處理:{{settings}}', fieldErrorsToast_other: '{{count}} 項設定需要處理:{{settings}}', cryptoRefusalTitle: '此部署無法加密機密資訊', + platformManagedTitle: '此項由平台託管', + platformManagedBody: '託管平台為此環境提供並配置此項,因此無需在此設定。', + aiProviderManaged: 'AI 提供商、模型與憑據由平台託管。', cryptoRefusalSubjectSuffix: '被宣告為加密欄位,因此未寫入任何內容。', cryptoRefusalNoSubject: '宣告為加密的值被拒絕,因此未寫入任何內容。', cryptoRefusalToast: '無法加密機密資訊:{{subject}}', From f45d6364b990761b605656db0406f60d77445a55 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:34:09 +0000 Subject: [PATCH 2/3] test(console): edit a text key in the hosted save refusal case Claude-Session: https://claude.ai/code/session_01ADHkmSWkWcHBfKEZ8RmTrv Co-authored-by: Claude --- .../SettingsView.platformManaged-34149.test.tsx | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx index 644bd31e8f3..c82ebdc2a4e 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx @@ -235,18 +235,21 @@ describe('the hosted AI page (objectstack#34149)', () => { }); it('a save refused as platform-managed toasts the managed text', async () => { - getSettingsNamespace.mockResolvedValue(AI_FULL); + getSettingsNamespace.mockResolvedValue({ + manifest: { namespace: 'ai', label: 'AI', specifiers: [{ type: 'text', key: 'openai_model', label: 'Model' }] }, + values: { openai_model: { value: 'gpt-4o', source: 'default' } }, + }); saveSettingsNamespace.mockRejectedValue( rejection(409, { code: 'RESOURCE_CONFLICT', - message: "This environment is cloud-managed: … so 'provider' cannot be changed here. Nothing was written.", - details: { namespace: 'ai', managedBy: 'platform', keys: ['provider'] }, + message: "This environment is cloud-managed: … so 'openai_model' cannot be changed here. Nothing was written.", + details: { namespace: 'ai', managedBy: 'platform', keys: ['openai_model'] }, }), ); - renderView('ai'); + const { container } = renderView('ai'); - const toggle = await screen.findByRole('switch'); - fireEvent.click(toggle); + await screen.findByText('Model'); + fireEvent.change(container.querySelector('input') as HTMLInputElement, { target: { value: 'gpt-5' } }); fireEvent.click(await screen.findByRole('button', { name: /save changes/i })); await waitFor(() => expect(toastError).toHaveBeenCalledWith(MANAGED_TITLE)); }); From febd90e868b7091868880e00ff2b6800f52e6c68 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:35:32 +0000 Subject: [PATCH 3/3] test(console): pin the hosted flag on the AI page with a self-hosted control Claude-Session: https://claude.ai/code/session_01ADHkmSWkWcHBfKEZ8RmTrv Co-authored-by: Claude --- .../SettingsView.platformManaged-34149.test.tsx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx index c82ebdc2a4e..7c5a0e18784 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.platformManaged-34149.test.tsx @@ -209,6 +209,16 @@ describe('the hosted AI page (objectstack#34149)', () => { expect(screen.queryByTestId('settings-ai-provider-managed')).toBeNull(); }); + it('CONTROL: a page served without a provider on a self-hosted environment draws no line', async () => { + authFeatures = { cloudManaged: false }; + getSettingsNamespace.mockResolvedValue(AI_PROJECTED); + renderView('ai'); + + expect(await screen.findByText('Generate titles')).toBeTruthy(); + await waitFor(() => expect(getAuthConfig).toHaveBeenCalled()); + expect(screen.queryByTestId('settings-ai-provider-managed')).toBeNull(); + }); + it('CONTROL: a hosted server that still serves the provider draws its form and no line', async () => { authFeatures = { cloudManaged: true }; getSettingsNamespace.mockResolvedValue(AI_FULL);