Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit b8fa223

Browse files
fix(app-shell): offer Sync objects only on a federation-source datasource (#13321)
Fixes #13318 Clause-②: no ## What changes Setup → Datasources showed **Sync objects** on every datasource row. Since objectstack#24837 (merged as objectstack `72a302a9d`), every Sync door refuses a datasource that is not a federation source with a `400`: a `managed` one, declared or by default, and the platform's `default` datasource by name. On such a row the button opened a dialog that could only show the refusal. `DatasourceResourcePage` now renders the existing button only when `offersSync(row)` holds: the row's `schemaMode`, read from the `GET /api/v1/datasources` payload the page already holds, is `external` or `validate-only`, and the row is not `default`. Nothing else changes: no new widget, dialog, hook, request or locale key. - `DatasourceRow` declares `schemaMode`, typed with the spec's own `SchemaMode` (`@objectstack/spec/data`). - The `default` name is a literal beside a comment naming the server's `DEFAULT_DATASOURCE_NAME`: that constant lives in `@objectstack/service-datasource`, a server package the console does not depend on, and the spec does not export it. ## The card's acceptance, met From the card's **Expected**: > The Sync action is offered only on a row whose `schemaMode` is `external` or `validate-only`, read from the list payload the page already holds. Met: `offersSync` is an allow-list over the row's own `schemaMode`. > A missing `schemaMode` reads as `managed`: the spec's default, and the editor's own reading. Met without a fallback: a missing value is not in the allow-list, so it offers no Sync. (The server's list summary already serves `schemaMode: effective.schemaMode ?? 'managed'` on every row, at objectui's objectstack pin `06cab4849` and at objectstack `origin/main`.) > On a managed row nothing starts a Sync. If the row says anything, it names the remedy the server's refusal names [...] Met by hiding the button: nothing starts a Sync, and the row says nothing. A disabled button with a native tooltip was not chosen: the Button primitive's disabled state sets `pointer-events-none`, so the tooltip would not show without a new wrapper. The remedy stays the editor's existing Schema mode select. > The platform's `default` datasource offers no Sync either; the server already refuses it by name. Met: `offersSync` refuses the name first, whatever its `schemaMode`. > No new widget, dialog or hook: the existing button's visibility or disabled state, and the existing editor. Met: the existing button's visibility only. From the card's **Pins**, in the new `DatasourceResourcePage.syncFederationOnly-13318.test.tsx`: - (a) a row with no `schemaMode` and a `managed` row show no Sync button (both rows render their Test button); - (b) an `external` row and a `validate-only` row show it; - (c) the `default` row shows none, even declared `external`; - (d) CONTROL: on an `external` row, Sync opens the dialog, requests `GET /api/v1/datasources/warehouse/remote-tables`, and lists the remote tables. Fixture triage: the objectui#13207 suite (`DatasourceResourcePage.refusals-13207.test.tsx`) drove Sync on a `managed` row. Its row now declares `external`: its refusal cases pin how a refused introspection is drawn, which still applies to a federation source (an unreachable driver, say), and `managed` was incidental. ## Measured premises - The list payload carries `schemaMode`: `DatasourceAdminService.listDatasources` sets it on every summary, and the contract `DatasourceSummary.schemaMode` is required, at the pin `06cab4849` and at objectstack `origin/main`. No new request. - The pin does not need to move: the console reads the row's own `schemaMode`. `git merge-base --is-ancestor 72a302a9d origin/main` in the objectstack checkout answers exit 0. - The server's guard is `ExternalDatasourceService.assertFederationSource`: the `default` name first, then `isFederationSource` (a declared `schemaMode` that is not `managed`). ## Verification (head `46bd4f4`) - `pnpm exec vitest run packages/app-shell/src/views/metadata-admin/datasource/`: Test Files 4 passed (4), Tests 27 passed (27). - Narrowed app-shell set (the datasource directory, `packages/app-shell/src/__tests__/`, and three tree-wide ratchet/census tests): Test Files 31 passed (31), Tests 488 passed (488). The full app-shell suite (1674 test files) is left to CI. - `pnpm --filter @object-ui/app-shell type-check`: exit 0. `tsc -p tsconfig.test.json --listFiles` lists both datasource test files the diff touches. - Ablation, one run: `{offersSync(ds) && (` replaced with `{true && (` through `ablation-replace.mjs` (anchor 1 to 0, blob `1ef26d74d6e7` to `2c02bcdbca5f`): pins (a) and (c) went red, (b) and (d) stayed green, Tests 2 failed, 25 passed. Restored: blob equals HEAD, `git diff HEAD` empty. - `eslint --no-inline-config` over the datasource directory: 0 errors; 2 warnings, both on lines this diff does not touch. - `check-changeset-presence`, `check-changeset-no-major`, `check:new-line-citations`, `check:control-bytes`, `check:test-path-roots`, the three `check:vi-mock-*`, `check:changeset-claims`, `check:pending-changeset-literals`, `check:spec-symbols`: exit 0 each. `check-governed-queue-guard --test` on the diff: NOT GOVERNED. ## Acceptance notes - The page header still reads "Connect external databases and sync their tables in as objects." It is still true of the page and was left alone. - Changeset: `.changeset/13318-datasource-sync-managed.md`, `@object-ui/app-shell` patch. Implemented in session `https://claude.ai/code/session_019Bd3muSBdHUFdJiKqnsM2W`. --- _Generated by [Claude Code](https://claude.ai/code/session_019Bd3muSBdHUFdJiKqnsM2W)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent cd14d8e commit b8fa223

4 files changed

Lines changed: 178 additions & 4 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
---
4+
5+
Setup → Datasources offers "Sync objects" only on a datasource that can be synced (objectui#13318).
6+
7+
The server refuses every Sync step (listing remote tables, drafting and importing an object) on a datasource whose schema mode is `managed`, with a `400` that names the rule and the remedy. A datasource saved without a schema mode is managed too, and so is the platform's `default` datasource. The page still showed the button on every row, so on such a row it opened a dialog that could only show the refusal.
8+
9+
The button now shows only on a row whose schema mode is `external` or `validate-only`, and never on the `default` row. To sync from a managed datasource, edit it and set its Schema mode to External or Validate only.

‎packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.refusals-13207.test.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ const ok = (data: unknown) => reply(200, { success: true, data });
6464
const refuse = (status: number, message: string) =>
6565
reply(status, { success: false, error: { code: 'DATASOURCE_ADMIN_ERROR', message } });
6666

67-
const ROW = { name: 'warehouse', driver: 'postgres', schemaMode: 'managed', origin: 'runtime', active: true, status: 'unvalidated' };
67+
// `external`: only a federation source offers Sync (objectui#13318).
68+
const ROW = { name: 'warehouse', driver: 'postgres', schemaMode: 'external', origin: 'runtime', active: true, status: 'unvalidated' };
6869

6970
/** The admin door, reduced to the list read plus the one route under test. */
7071
function renderPage(route: (url: string, init?: RequestInit) => Promise<Reply> | Reply | undefined) {
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectui#13318 — Setup → Datasources offers "Sync objects" only on a
5+
* federation source.
6+
*
7+
* Every Sync door (remote tables, object draft, import, catalog refresh)
8+
* refuses a datasource that is not a federation source with a `400`
9+
* (objectstack#24837): a managed one, declared or by default, and the
10+
* platform's primary datasource `default` by name. The page offered the
11+
* button on every row, so on a managed row it opened a dialog that could only
12+
* show the refusal.
13+
*
14+
* What is pinned, over the list payload `GET /api/v1/datasources` serves:
15+
* - (a) a row with no `schemaMode` and a row with `schemaMode: 'managed'`
16+
* show no Sync button;
17+
* - (b) a row with `external` and a row with `validate-only` show it;
18+
* - (c) the `default` row shows none, even declared `external`;
19+
* - (d) CONTROL: on an `external` row, Sync opens the dialog and lists the
20+
* remote tables.
21+
*/
22+
23+
import * as React from 'react';
24+
import { describe, it, expect, vi, afterEach } from 'vitest';
25+
import { render, screen, cleanup, fireEvent, within } from '@testing-library/react';
26+
import { I18nProvider } from '@object-ui/i18n';
27+
28+
type Reply = { ok: boolean; status: number; text: () => Promise<string> };
29+
30+
const state = vi.hoisted(() => ({
31+
fetch: (async () => undefined) as unknown as (url: string, init?: RequestInit) => Promise<unknown>,
32+
// STABLE identity, like the real memoized client.
33+
metadataClient: {},
34+
}));
35+
36+
vi.mock('@object-ui/auth', async (importOriginal) => ({
37+
...(await importOriginal<Record<string, unknown>>()),
38+
createAuthenticatedFetch: () => (url: string, init?: RequestInit) => state.fetch(url, init),
39+
}));
40+
vi.mock('../useMetadata.js', () => ({
41+
useMetadataClient: () => state.metadataClient,
42+
}));
43+
vi.mock('sonner', () => ({
44+
toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn(), message: vi.fn() },
45+
}));
46+
47+
import { DatasourceResourcePage } from './DatasourceResourcePage';
48+
49+
afterEach(() => cleanup());
50+
51+
const reply = (status: number, payload: unknown): Reply => ({
52+
ok: status < 400,
53+
status,
54+
text: async () => JSON.stringify(payload),
55+
});
56+
const ok = (data: unknown) => reply(200, { success: true, data });
57+
58+
type Row = { name: string; schemaMode?: 'managed' | 'external' | 'validate-only' };
59+
60+
/** The admin door: the list read and the one remote-tables read. */
61+
function renderPage(rows: Row[], tables: Record<string, unknown[]> = {}) {
62+
const requested: string[] = [];
63+
state.fetch = (async (url: string, init?: RequestInit) => {
64+
requested.push(`${init?.method ?? 'GET'} ${url}`);
65+
if (url === '/api/v1/datasources') {
66+
return ok({
67+
datasources: rows.map((r) => ({ driver: 'postgres', origin: 'runtime', active: true, status: 'unvalidated', ...r })),
68+
});
69+
}
70+
const m = /^\/api\/v1\/datasources\/([^/]+)\/remote-tables$/.exec(url);
71+
if (m && tables[m[1]]) return ok({ tables: tables[m[1]] });
72+
return reply(404, { success: false, error: { code: 'NOT_FOUND', message: `unexpected ${url}` } });
73+
}) as typeof state.fetch;
74+
render(
75+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
76+
<DatasourceResourcePage />
77+
</I18nProvider>,
78+
);
79+
return requested;
80+
}
81+
82+
/** The list row whose name chip reads `name`. */
83+
async function rowOf(name: string): Promise<HTMLElement> {
84+
const chip = await screen.findByText(name, { selector: 'code' });
85+
const row = chip.closest('div.flex.items-center.gap-3');
86+
if (!(row instanceof HTMLElement)) throw new Error(`no row for ${name}`);
87+
return row;
88+
}
89+
90+
const syncIn = (row: HTMLElement) => within(row).queryByRole('button', { name: /Sync objects/ });
91+
92+
describe('DatasourceResourcePage — Sync is offered only on a federation source (objectui#13318)', () => {
93+
it('(a) a row with no schemaMode and a managed row show no Sync button', async () => {
94+
renderPage([{ name: 'qa_mem' }, { name: 'crm_db', schemaMode: 'managed' }]);
95+
const undeclared = await rowOf('qa_mem');
96+
const managed = await rowOf('crm_db');
97+
// The rows rendered: their Test buttons are there.
98+
expect(within(undeclared).getByRole('button', { name: /Test/ })).toBeTruthy();
99+
expect(within(managed).getByRole('button', { name: /Test/ })).toBeTruthy();
100+
expect(syncIn(undeclared)).toBeNull();
101+
expect(syncIn(managed)).toBeNull();
102+
});
103+
104+
it('(b) an external row and a validate-only row show the Sync button', async () => {
105+
renderPage([{ name: 'warehouse', schemaMode: 'external' }, { name: 'legacy_erp', schemaMode: 'validate-only' }]);
106+
expect(syncIn(await rowOf('warehouse'))).not.toBeNull();
107+
expect(syncIn(await rowOf('legacy_erp'))).not.toBeNull();
108+
});
109+
110+
it('(c) the default row shows no Sync button, even declared external', async () => {
111+
renderPage([{ name: 'default', schemaMode: 'external' }, { name: 'warehouse', schemaMode: 'external' }]);
112+
expect(syncIn(await rowOf('default'))).toBeNull();
113+
expect(syncIn(await rowOf('warehouse'))).not.toBeNull();
114+
});
115+
116+
it('(d) CONTROL: Sync on an external row opens the dialog and lists the remote tables', async () => {
117+
const requested = renderPage(
118+
[{ name: 'warehouse', schemaMode: 'external' }],
119+
{ warehouse: [{ name: 'orders', columnCount: 4 }, { name: 'customers', columnCount: 7 }] },
120+
);
121+
const sync = syncIn(await rowOf('warehouse'));
122+
if (!sync) throw new Error('the external row offers no Sync button');
123+
fireEvent.click(sync);
124+
const dialog = await screen.findByRole('dialog');
125+
expect(await within(dialog).findByText('orders')).toBeTruthy();
126+
expect(within(dialog).getByText('customers')).toBeTruthy();
127+
expect(requested).toContain('GET /api/v1/datasources/warehouse/remote-tables');
128+
});
129+
});

‎packages/app-shell/src/views/metadata-admin/datasource/DatasourceResourcePage.tsx‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
* - **Sync objects**: introspect remote tables (`GET …/remote-tables`), pick
3232
* which to import, generate an object definition for each (`POST …/object-draft`),
3333
* and create it through the normal metadata channel (`MetadataClient.save('object', …)`).
34+
* Offered only on a federation source (`offersSync`, objectui#13318).
3435
* - **Delete** a runtime datasource (`DELETE …/:name`; blocked by the backend
3536
* while objects are still bound).
3637
*
@@ -84,11 +85,17 @@ import { t, useMetadataLocale } from '../i18n.js';
8485
// defence in depth. Importing the spec's type keeps this page's row and that
8586
// client's row incapable of disagreeing.
8687
import type { RemoteTable } from '@objectstack/spec/contracts';
88+
import type { SchemaMode } from '@objectstack/spec/data';
8789

8890
interface DatasourceRow {
8991
name: string;
9092
label?: string;
9193
driver?: string;
94+
/**
95+
* The datasource's `schemaMode`. `GET /datasources` serves it on every row,
96+
* already resolved to `managed` when the record declares none.
97+
*/
98+
schemaMode?: SchemaMode;
9299
/**
93100
* Last connect verdict, from the framework's retained connection state
94101
* (framework#3827): `ok` (live driver registered) | `error` (connect
@@ -174,6 +181,32 @@ const SCHEMA_MODES = [
174181
{ value: 'validate-only', label: 'Validate only' },
175182
];
176183

184+
/**
185+
* The platform's primary datasource, the name the server's
186+
* `DEFAULT_DATASOURCE_NAME` holds. Every Sync door refuses it by name,
187+
* whatever its `schemaMode`.
188+
*/
189+
const PRIMARY_DATASOURCE = 'default';
190+
191+
/** The `schemaMode` values that make a datasource a federation source. */
192+
const FEDERATION_SCHEMA_MODES: ReadonlySet<SchemaMode> = new Set<SchemaMode>(['external', 'validate-only']);
193+
194+
/**
195+
* Does this row offer "Sync objects"? (objectui#13318)
196+
*
197+
* The Sync doors (remote tables, object draft, import) refuse every datasource
198+
* that is not a federation source with a `400` (objectstack#24837): a managed
199+
* one, declared or by default, and the primary datasource by name. ADR-0015
200+
* reserves federation for a datasource whose `schemaMode` is not `managed`, so
201+
* the row offers Sync only when its `schemaMode` is `external` or
202+
* `validate-only`. A row with no `schemaMode` is managed, the spec's default,
203+
* and offers none. The remedy is the editor's own Schema mode select.
204+
*/
205+
function offersSync(row: DatasourceRow): boolean {
206+
if (row.name === PRIMARY_DATASOURCE) return false;
207+
return row.schemaMode !== undefined && FEDERATION_SCHEMA_MODES.has(row.schemaMode);
208+
}
209+
177210
const SERVER = ((import.meta as { env?: Record<string, string> }).env?.VITE_SERVER_URL || '').replace(/\/+$/, '');
178211

179212
const isPassword = (p: JsonProp) => p.format === 'password';
@@ -609,9 +642,11 @@ export function DatasourceResourcePage(_props: { type?: string }): React.ReactEl
609642
<Button variant="ghost" size="sm" disabled={busy === `test:${ds.name}`} onClick={() => void test(ds.name)}>
610643
{busy === `test:${ds.name}` ? <Loader2 className="mr-1.5 h-4 w-4 animate-spin" /> : <Plug className="mr-1.5 h-4 w-4" />} Test
611644
</Button>
612-
<Button variant="secondary" size="sm" onClick={() => void openSync(ds.name)}>
613-
<Boxes className="mr-1.5 h-4 w-4" /> Sync objects
614-
</Button>
645+
{offersSync(ds) && (
646+
<Button variant="secondary" size="sm" onClick={() => void openSync(ds.name)}>
647+
<Boxes className="mr-1.5 h-4 w-4" /> Sync objects
648+
</Button>
649+
)}
615650
{!isCode && (
616651
<>
617652
<Button variant="ghost" size="icon" className="h-8 w-8" title="Edit" disabled={busy === `edit:${ds.name}`} onClick={() => void openEdit(ds)}>

0 commit comments

Comments
 (0)