Skip to content

Commit 2052c89

Browse files
fix(app-shell): an unset metadata-form switch shows its declared default (#38459)
Fixes #38420 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:管理员在 Studio 打开元数据表单(知识源、智能体、技能、应用、邮件模板、对象能力、仪表盘页眉等)时,未填写且默认开启的开关,编辑与只读两种模式下都显示为「开」,与实际运行一致。 - 为什么做:修复 Studio 知识源表单把默认开启的「可被 AI 智能体搜索」「随记录变更同步」显示成关闭、与帮助文字和实际行为相反的缺陷。 - 出错会怎样:只影响开关的显示,不写入任何值;未改动的条目保存后仍不存这个键,出问题时撤回本次改动即可恢复原显示。 - 要你做什么:无 ## What changes The metadata-form Switch in `SchemaForm` drew every unset boolean as `!!value`, so a key whose served schema says `default: true` read OFF while the runtime treats it as on. It now draws the value in effect: an unset key (the shared `isUnsetFieldValue` definition) draws the schema's declared `default`, a stored boolean draws itself. This is the flow node inspector's existing "show, do not write" boolean rule applied to the generic form: nothing is written until the author toggles, so an untouched item still saves without the key and keeps following the default (the ruling's display-only constraint). The default is read off the served JSON Schema, which already carries it: `aiExposed` and `refresh.onRecordChange` are `z.boolean().default(true).optional()`, and `z.toJSONSchema` emits `default: true` for both. The form declares no default of its own and needs none, so `packages/spec` is untouched. Every boolean row a registered metadata form declares whose derived schema defaults to `true` shares this one Switch; the new test enumerates them from `METADATA_FORM_REGISTRY` and the registered type schemas rather than listing them. At the head of this PR the walk finds rows on nine forms: knowledge source (`aiExposed`, `refresh.onRecordChange`), skill, agent, app and email template (`active`), object (`enable.searchable`, `enable.apiEnabled`, `enable.feeds`, `enable.activities`, `enable.clone`), field (`sortable`), report (`drilldown`, `dateRange.allowCustomRange`) and dashboard (`header.showTitle`, `header.showDescription`, `dateRange.allowCustomRange`). That list is a reading taken once; the test is the instrument that re-derives it. Read first, by risk: 1. `ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx`, the boolean branch of `FieldControl` (the `declaredDefault` line and the `checked` expression): the only behaviour change. 2. `ui/packages/app-shell/src/views/metadata-admin/SchemaForm.declaredBooleanDefault-38420.test.tsx`, the `defaultTrueRows` walker: what "every default-true switch" means here (top-level rows and `composite` sub-rows). Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/views/metadata-admin/SchemaForm.declaredBooleanDefault-38420.test.tsx`, expect 6 passed. ## Tests New `SchemaForm.declaredBooleanDefault-38420.test.tsx`, all against the real spec (the served form and `z.toJSONSchema(getMetadataTypeSchema(type))`, as the `/meta/types` row carries them): - knowledge-source form, edit and read-only: both unset switches report `aria-checked="true"`; - explicit `false` reports `"false"`, explicit `true` reports `"true"`; - an untouched form calls `onChange` zero times; the first click writes `aiExposed: false` and adds no `refresh` key; - every enumerated default-true row renders ON when unset, with a floor (`knowledge_source.aiExposed`, `knowledge_source.refresh.onRecordChange`, `skill.active`) so the walk cannot pass by finding nothing; - CONTROL: a boolean with no declared default, unset, reports `"false"`. Ablation (fix reverted on disk by `scripts/ablation-replace.mjs`, `checked={!!value}`; app-shell is a vitest source alias, so no build sits between): 4 failed, 2 passed, exactly the four unset cases red and the explicit-value and control cases green; restore verified blob equal to HEAD and `git diff HEAD` empty. <details><summary>Readings</summary> - Final head 03896dd, the new file plus the neighbouring suites (`SchemaForm.optionalEnumUnset-29733`, `SchemaForm.requiredMarker-10367`, `SchemaForm.widgetLabelling`, `ResourceEditPage.formBoundObject-37309`): `Test Files 5 passed (5)`, `Tests 104 passed (104)`. - Ablated: `Tests 4 failed | 2 passed (6)`; `ablation-replace: ok restored: blob == HEAD (3095ad6) and git diff HEAD is empty`. - `pnpm --dir ui exec vitest run scripts/` (derived family): `Test Files 1 failed | 171 passed | 2 skipped (174)`; the one failure was `js-comment-mask-returns-interpolation-9424.test.ts` timing out at 15000ms on a contended box (unrelated to this diff); rerun alone: `Tests 8 passed (8)`. </details> ## Acceptance notes - Local `type-check` of `@object-ui/app-shell` was not measured: it needs every `@object-ui/*` dist built (the run reported `Cannot find module '@object-ui/components'` and its siblings before reaching any check of this diff). NOT MEASURED locally, reason: closure not built; `Type Check UI` in CI carries it. The change types against `JsonSchema`, which that file declares as a string-keyed record of any value. - Not verified in a running Studio; the component test drives the real served form and derived schema through `SchemaForm`. - The walker covers top-level rows and `composite` sub-rows. Boolean columns inside repeaters (an object's `fields` rows, for one) render through the same `FieldControl` Switch, so they take the fix, but the pin does not enumerate them. - `dynamic-config`'s schema-driven boolean (`DynamicConfigWidget` in `widgets.tsx`) has the same `Boolean(cur)` shape, but nothing in the tree populates `WidgetContext.dynamicSchemas`, so it has no reachable default-true input today. Noted, not changed. - The dispatch's file surface named `ui/.changeset/*.md`; `ui/AGENTS.md` says new changesets go to the root `.changeset/` and none are added under `ui/.changeset/`, so the changeset is `.changeset/38420-unset-switch-shows-default.md`. ## Verification Local derived gate list (`node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`): 38 families, run at 862c74b, all exit 0 except two. `check:test-source-alias` was red on the new test (it reached `@objectstack/lint` and `@object-ui/plugin-detail` through dynamic imports with no module-top import); 03896dd adds the two imports, and the gate is green there. `vitest run scripts/` had one timeout, which passed when rerun alone. On 03896dd, the families that read the changed test file were rerun, all exit 0: `check:test-source-alias`, `check:undeclared-dep-imports`, `check:cross-package-test-inputs`, `check:nul-bytes`, `check:gitlink-declared`, and ui `check:new-line-citations` (0 new citations). `--ran` reconciliation: `38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED (a DERIVED zero)`. Every family CI runs is read from this PR's check-runs. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d13AraSmVmgVtCvkWk)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent f459c86 commit 2052c89

3 files changed

Lines changed: 205 additions & 1 deletion

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@objectstack/console': patch
4+
---
5+
6+
fix(app-shell): an unset switch on a Studio metadata form shows the default its schema declares
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
A switch on a Studio metadata form drew every unset value as off. Where the schema gives the key a default of `true`, that is the opposite of what runs: a knowledge source that stores neither `aiExposed` nor `refresh.onRecordChange` is searched by AI agents and kept in step with its records, while both switches read off beside help text saying "On by default". Such a switch now draws the default in effect, in edit and in read-only mode. It holds for every boolean row of a form whose schema default is `true`, among them an agent's, skill's, app's and email template's `active`, an object's capability switches such as `enable.apiEnabled`, and a dashboard header's `showTitle`.
12+
13+
Nothing is written for it: an item you open and save without touching the switch still stores no value for the key and keeps following the default. Toggling the switch stores an explicit `true` or `false`, as before. A boolean with no declared default still draws off when unset, and a stored `false` draws off.
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#38420 — an UNSET metadata-form switch shows the default the
5+
* schema declares for it.
6+
*
7+
* The builtin Switch drew `!!value`, so every unset boolean read OFF. On a key
8+
* whose schema says `.default(true)` that is the opposite of what runs: a
9+
* knowledge source that stores neither `aiExposed` nor
10+
* `refresh.onRecordChange` is searched and synced, while both switches said
11+
* off, beside help text saying "On by default".
12+
*
13+
* The rule is "show, do not write" (the flow node inspector's boolean rule):
14+
* the control draws the value in effect, and nothing is written until the
15+
* author toggles.
16+
*
17+
* Pins, all against the real spec — the served form and the schema derived
18+
* from the registered metadata type, as the `/meta/types` row carries them:
19+
* - the knowledge-source form, edit and read-only: both unset switches ON;
20+
* - an explicit `false` draws OFF, an explicit `true` draws ON;
21+
* - an untouched form writes nothing; the first toggle writes an explicit
22+
* boolean;
23+
* - EVERY boolean row a registered form declares whose derived schema
24+
* defaults to `true` draws ON when unset — enumerated here, never listed,
25+
* with a floor so the walk cannot pass by finding nothing;
26+
* - CONTROL: a boolean with no declared default, unset, draws OFF.
27+
*/
28+
29+
import '@testing-library/jest-dom/vitest';
30+
// The source under test reaches these through dynamic imports: their first load is paid at collection.
31+
import '@objectstack/lint';
32+
import '@object-ui/plugin-detail';
33+
import { describe, it, expect, vi, afterEach } from 'vitest';
34+
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
35+
import { z } from 'zod';
36+
import { getMetadataTypeSchema } from '@objectstack/spec/kernel';
37+
import { METADATA_FORM_REGISTRY } from '@objectstack/spec/system';
38+
39+
import { SchemaForm } from './SchemaForm';
40+
import type { FormFieldSpec, FormViewSpec } from './form-spec';
41+
import './register-builtins';
42+
43+
afterEach(cleanup);
44+
45+
type Json = Record<string, unknown>;
46+
47+
/** The schema a `/meta/types` row serves for `type`, derived from the registered spec schema. */
48+
function servedSchema(type: string): Json {
49+
const zodSchema = getMetadataTypeSchema(type);
50+
expect(zodSchema, `no registered schema for ${type}`).toBeDefined();
51+
return z.toJSONSchema(zodSchema!, { unrepresentable: 'any' }) as Json;
52+
}
53+
54+
/** The object node of a property: itself, or the object branch of a union. */
55+
function objectNode(node: unknown): Json | undefined {
56+
if (!node || typeof node !== 'object') return undefined;
57+
const n = node as Json;
58+
if (n.properties && typeof n.properties === 'object') return n;
59+
for (const key of ['anyOf', 'oneOf']) {
60+
const branches = n[key];
61+
if (Array.isArray(branches)) {
62+
const hit = branches.find((b) => b && typeof b === 'object' && (b as Json).properties);
63+
if (hit) return hit as Json;
64+
}
65+
}
66+
return undefined;
67+
}
68+
69+
interface DefaultTrueRow {
70+
type: string;
71+
/** Dotted path of the row, through the composites it sits in. */
72+
path: string;
73+
fieldSpec: FormFieldSpec;
74+
schema: Json;
75+
}
76+
77+
/**
78+
* Every boolean row a form declares whose derived schema defaults to `true`,
79+
* top level and inside `composite` groups (the nesting the form renders as
80+
* sub-rows of one object).
81+
*/
82+
function defaultTrueRows(): DefaultTrueRow[] {
83+
const rows: DefaultTrueRow[] = [];
84+
const walk = (type: string, fields: FormFieldSpec[], parent: Json | undefined, prefix: string) => {
85+
for (const f of fields) {
86+
const prop = (parent?.properties as Json | undefined)?.[f.field] as Json | undefined;
87+
const path = prefix ? `${prefix}.${f.field}` : f.field;
88+
if (f.type === 'composite' && Array.isArray(f.fields)) {
89+
walk(type, f.fields as FormFieldSpec[], objectNode(prop), path);
90+
continue;
91+
}
92+
if (prop && prop.type === 'boolean' && prop.default === true) rows.push({ type, path, fieldSpec: f, schema: prop });
93+
}
94+
};
95+
for (const [type, form] of Object.entries(METADATA_FORM_REGISTRY)) {
96+
if (!getMetadataTypeSchema(type)) continue;
97+
const root = objectNode(servedSchema(type));
98+
for (const section of (form as { sections?: { fields?: FormFieldSpec[] }[] }).sections ?? []) {
99+
walk(type, section.fields ?? [], root, '');
100+
}
101+
}
102+
return rows;
103+
}
104+
105+
const switchNamed = (name: string) => screen.getByRole('switch', { name: new RegExp(`^${name}`) });
106+
107+
describe('an unset metadata-form switch shows the default its schema declares (objectstack#38420)', () => {
108+
const form = METADATA_FORM_REGISTRY.knowledge_source as unknown as FormViewSpec;
109+
const schema = servedSchema('knowledge_source') as never;
110+
const STORED = {
111+
name: 'task_notes',
112+
label: 'Task notes',
113+
source: { kind: 'object', object: 'acme_task', content: ['title'] },
114+
};
115+
116+
it.each([
117+
['edit', false],
118+
['read-only', true],
119+
])('⭐ %s mode: a knowledge source storing neither key draws both switches ON', (_mode, readOnly) => {
120+
render(<SchemaForm schema={schema} form={form} value={STORED} onChange={vi.fn()} readOnly={readOnly} />);
121+
expect(switchNamed('Searchable by AI agents')).toHaveAttribute('aria-checked', 'true');
122+
expect(switchNamed('Sync on record changes')).toHaveAttribute('aria-checked', 'true');
123+
});
124+
125+
it('an explicit false draws OFF and an explicit true draws ON', () => {
126+
const { unmount } = render(
127+
<SchemaForm schema={schema} form={form} value={{ ...STORED, aiExposed: false, refresh: { onRecordChange: false } }} onChange={vi.fn()} />,
128+
);
129+
expect(switchNamed('Searchable by AI agents')).toHaveAttribute('aria-checked', 'false');
130+
expect(switchNamed('Sync on record changes')).toHaveAttribute('aria-checked', 'false');
131+
unmount();
132+
render(
133+
<SchemaForm schema={schema} form={form} value={{ ...STORED, aiExposed: true, refresh: { onRecordChange: true } }} onChange={vi.fn()} />,
134+
);
135+
expect(switchNamed('Searchable by AI agents')).toHaveAttribute('aria-checked', 'true');
136+
expect(switchNamed('Sync on record changes')).toHaveAttribute('aria-checked', 'true');
137+
});
138+
139+
it('display only: an untouched form writes nothing, and the first toggle writes an explicit false', () => {
140+
const onChange = vi.fn();
141+
render(<SchemaForm schema={schema} form={form} value={STORED} onChange={onChange} />);
142+
expect(onChange).not.toHaveBeenCalled();
143+
fireEvent.click(switchNamed('Searchable by AI agents'));
144+
expect(onChange).toHaveBeenCalledTimes(1);
145+
const next = onChange.mock.calls[0][0] as Json;
146+
expect(next.aiExposed).toBe(false);
147+
expect('refresh' in next).toBe(false);
148+
});
149+
150+
it('every boolean row a registered form declares with a true default draws ON when unset', () => {
151+
const rows = defaultTrueRows();
152+
const paths = rows.map((r) => `${r.type}.${r.path}`);
153+
// Floor: the two rows the card names, one nested in a composite, and one on another form.
154+
expect(paths).toEqual(expect.arrayContaining([
155+
'knowledge_source.aiExposed',
156+
'knowledge_source.refresh.onRecordChange',
157+
'skill.active',
158+
]));
159+
for (const row of rows) {
160+
const key = row.fieldSpec.field;
161+
const { unmount } = render(
162+
<SchemaForm
163+
schema={{ type: 'object', properties: { [key]: row.schema } } as never}
164+
form={{ type: 'simple', sections: [{ fields: [row.fieldSpec] }] } as unknown as FormViewSpec}
165+
value={{}}
166+
onChange={vi.fn()}
167+
/>,
168+
);
169+
expect(screen.getByRole('switch'), `${row.type}.${row.path}`).toHaveAttribute('aria-checked', 'true');
170+
unmount();
171+
}
172+
});
173+
174+
it('CONTROL: a boolean with no declared default draws OFF when unset', () => {
175+
render(
176+
<SchemaForm
177+
schema={{ type: 'object', properties: { flag: { type: 'boolean' } } } as never}
178+
value={{}}
179+
onChange={vi.fn()}
180+
/>,
181+
);
182+
expect(screen.getByRole('switch')).toHaveAttribute('aria-checked', 'false');
183+
});
184+
});

‎ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2612,13 +2612,20 @@ function FieldControl({
26122612
// the sub-field as boolean. Without this, capability toggles inside the
26132613
// Object editor's "Capabilities" section fell through to RawJsonEditor
26142614
// and rendered as empty textareas.
2615+
//
2616+
// The switch shows the value IN EFFECT — "show, do not write", the flow
2617+
// node inspector's boolean rule (`FlowNodeConfigField`): an UNSET key draws
2618+
// the schema's declared `default` (a `.default(true)` key is ON), a stored
2619+
// boolean draws itself. Nothing is written until the author toggles, so an
2620+
// untouched item still saves without the key and keeps tracking the default.
26152621
if (effectiveType === 'boolean' || widget === 'switch' || fieldSpec?.type === 'boolean' || fieldSpec?.type === 'toggle') {
2622+
const declaredDefault = effective && 'default' in effective ? effective.default : schema?.default;
26162623
return (
26172624
<Switch
26182625
id={id}
26192626
aria-labelledby={ariaLabelledBy}
26202627
aria-required={ariaRequired}
2621-
checked={!!value}
2628+
checked={isUnsetFieldValue(value) ? declaredDefault === true : !!value}
26222629
onCheckedChange={(c) => onChange(c)}
26232630
disabled={readOnly}
26242631
/>

0 commit comments

Comments
 (0)