diff --git a/.changeset/37143-ai-context-studio-form.md b/.changeset/37143-ai-context-studio-form.md new file mode 100644 index 00000000000..065f8f57163 --- /dev/null +++ b/.changeset/37143-ai-context-studio-form.md @@ -0,0 +1,19 @@ +--- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): author context packs (`ai_context`) in Studio — a form for the type, and a related-lists block that picks each list's columns from its own child object + +Clause-②: yes (widening) — one new public export, `aiContextForm` from `@objectstack/spec/ai`, and `/meta/types` now serves a form for `ai_context`; no key is added to what a pack may hold +Metadata-protocol: none + +ADR-0160 D1, clause 2 (runtime authoring). A context pack can now be created and edited in Studio like a skill: Studio's metadata editor lays it out with the new `aiContextForm` (`@objectstack/spec/ai`, registered in `METADATA_FORM_REGISTRY` as `ai_context`), and saving goes through the metadata API, where the pack's author defects are reported at save as before. + +- **Root object and its fields.** The root is picked from the object catalog; `fields` is the generic field picker scoped to that root (`field-multi`, `dependsOn: 'object'`); `body.field` is a single field picker over the root's fields. +- **Related lists.** `related` uses the `related-list-entries` block. Under a pack, whose entries are `{ object, field?, fields? }`, the block offers every reference field of a served object that points at the root (a self-reference and each of a child's several links included) and writes the pick as `{ object, field }`; each entry's columns are picked from that child object's fields. It stops adding at the schema's bounds (3 lists, 10 columns), and an emptied list or column set removes its key. A stored entry the catalog shows no link for is kept and marked; the save-time report judges it. The object form's `relatedLists` keeps its chip face unchanged: the block tells the two apart by the entry schema it is handed. +- **An emptied picker removes its key.** In Studio's metadata editor, removing the last chip of a field list whose schema has `minItems: 1` (a pack's `fields`) now removes the key instead of writing `[]`, and a composite left with no value while its schema requires a key that has no default (a pack's `body` after choosing "None") is removed instead of written as `{ field: '' }`; a composite whose required keys all carry a default (a view's `pagination`, `selection`) keeps `{}`; both were drafts the save refused with no way back in the form. A cleared sub-field of any composite drops its key, as a cleared top-level field already did. +- **The related-lists block waits for the object list.** While the object list loads, or after it failed, no stored entry is marked as unlinked and the add picker says it is loading or could not load. +- No key is added to `AiContextSchema`, and nothing a pack may hold changes. diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 61ded6ad068..43316d31730 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const arMetadataForms: NonNullable = { } }, ai_context: { - label: "حزمة سياق الذكاء الاصطناعي" + label: "حزمة سياق الذكاء الاصطناعي", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index bd9b5d220c8..07b4512dc20 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -18,6 +18,24 @@ */ export const arGeneratedSourceHashes: Readonly> = { + "metadataForms.ai_context.fields.body.field.helpText": "e25b48c15258b83d", + "metadataForms.ai_context.fields.body.field.label": "1b880a5fad37e8a3", + "metadataForms.ai_context.fields.body.helpText": "48e8d6e37b041d39", + "metadataForms.ai_context.fields.body.label": "d1753a024d6a9bed", + "metadataForms.ai_context.fields.fields.helpText": "b6f210cfc6f2f162", + "metadataForms.ai_context.fields.fields.label": "f316ec6025047133", + "metadataForms.ai_context.fields.label.helpText": "a7560b638d2146e7", + "metadataForms.ai_context.fields.label.label": "c680364257b11569", + "metadataForms.ai_context.fields.name.helpText": "41ef86776bba4abf", + "metadataForms.ai_context.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.object.helpText": "d785b8445fac8dfe", + "metadataForms.ai_context.fields.object.label": "d465a03c4dfc1d33", + "metadataForms.ai_context.fields.related.helpText": "135e19ad08da41fd", + "metadataForms.ai_context.fields.related.label": "32c91f670a44397f", + "metadataForms.ai_context.sections.basics.description": "4d638a6cd36c7175", + "metadataForms.ai_context.sections.basics.label": "55562f900da68c5d", + "metadataForms.ai_context.sections.material.description": "b8d9cf447db8cfe1", + "metadataForms.ai_context.sections.material.label": "11b295666d0c7917", "metadataForms.dashboard.fields.dateRange.allowCustomRange.helpText": "1cdc93f55eefade7", "metadataForms.dashboard.fields.dateRange.allowCustomRange.label": "a1fb0e1cf5fe5d8e", "metadataForms.dashboard.fields.dateRange.defaultRange.helpText": "afff2187966a112f", diff --git a/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts index e39dac81a69..24f0fb9b307 100644 --- a/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/bare-type-display-echo-decisions.test.ts @@ -813,16 +813,18 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha it('the BARE predicate splits that population, and is read off the SHAPE not a name list', () => { // Lit. - expect(BARE_TYPES.length).toBe(16); - expect(PANEL_TYPES.length).toBe(17); + // 16 / 17 → 15 / 18: `ai_context` gained its form (ADR-0160 D1 clause 2, + // #37143), so it is a panel type now. + expect(BARE_TYPES.length).toBe(15); + expect(PANEL_TYPES.length).toBe(18); expect(BARE_TYPES.length + PANEL_TYPES.length).toBe(REGISTRY_TYPES.length); - for (const type of ['seed', 'mapping', 'api', 'doc', 'book', 'capability', 'picklist', 'sharing_rule', 'queue', 'assignment_rule', 'object_extension', 'ai_context']) { + for (const type of ['seed', 'mapping', 'api', 'doc', 'book', 'capability', 'picklist', 'sharing_rule', 'queue', 'assignment_rule', 'object_extension']) { expect(BARE_TYPES, `${type} is bare`).toContain(type); } for (const type of AUTHORED_BARE_TYPES) expect(BARE_TYPES, `${type} is bare`).toContain(type); - // 27 leaves: sixteen labels, and a description on the eleven that carry one. - expect(BARE_LEAVES.length).toBe(27); - expect(BARE_LEAVES.filter((l) => l.prop === 'label').length).toBe(16); + // 26 leaves: fifteen labels, and a description on the eleven that carry one. + expect(BARE_LEAVES.length).toBe(26); + expect(BARE_LEAVES.filter((l) => l.prop === 'label').length).toBe(15); expect(BARE_LEAVES.filter((l) => l.prop === 'description').length).toBe(11); expect(BARE_LEAVES.every((l) => ['label', 'description'].includes(l.prop))).toBe(true); }); @@ -904,13 +906,13 @@ describe('#19403 round 7 — the population, DERIVED from the registry and a sha expect(flagged.length).toBe(BARE_LEAVES.length); }); - it('⭐ this class is now DONE — zero of its 27 leaves echoes in all three locales', () => { + it('⭐ this class is now DONE — zero of its 26 leaves echoes in all three locales', () => { const echoing = BARE_LEAVES.filter((l) => TRANSLATED_LOCALES.every(([, forms]) => forms[l.type]?.[l.prop] === l.en), ); expect(echoing.map((l) => `${l.type}.${l.prop}`)).toEqual([]); // Lit — and it really walked the class, which a zero alone would not show. - expect(BARE_LEAVES.length).toBe(27); + expect(BARE_LEAVES.length).toBe(26); }); }); diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 703282d86f7..2418140afd6 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const deMetadataForms: NonNullable = { } }, ai_context: { - label: "KI-Kontextpaket" + label: "KI-Kontextpaket", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 34168249337..284a4e2c27e 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -23,6 +23,24 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.action.fields.refusals.status.label": "64a420165247654b", "metadataForms.agent.fields.avatar.label": "0f06369995b69b8b", "metadataForms.agent.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.body.field.helpText": "e25b48c15258b83d", + "metadataForms.ai_context.fields.body.field.label": "1b880a5fad37e8a3", + "metadataForms.ai_context.fields.body.helpText": "48e8d6e37b041d39", + "metadataForms.ai_context.fields.body.label": "d1753a024d6a9bed", + "metadataForms.ai_context.fields.fields.helpText": "b6f210cfc6f2f162", + "metadataForms.ai_context.fields.fields.label": "f316ec6025047133", + "metadataForms.ai_context.fields.label.helpText": "a7560b638d2146e7", + "metadataForms.ai_context.fields.label.label": "c680364257b11569", + "metadataForms.ai_context.fields.name.helpText": "41ef86776bba4abf", + "metadataForms.ai_context.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.object.helpText": "d785b8445fac8dfe", + "metadataForms.ai_context.fields.object.label": "d465a03c4dfc1d33", + "metadataForms.ai_context.fields.related.helpText": "135e19ad08da41fd", + "metadataForms.ai_context.fields.related.label": "32c91f670a44397f", + "metadataForms.ai_context.sections.basics.description": "4d638a6cd36c7175", + "metadataForms.ai_context.sections.basics.label": "55562f900da68c5d", + "metadataForms.ai_context.sections.material.description": "b8d9cf447db8cfe1", + "metadataForms.ai_context.sections.material.label": "11b295666d0c7917", "metadataForms.api.fields.name.label": "5274417ff1ccaf01", "metadataForms.app.fields.branding.label": "ec6e391065514b64", "metadataForms.app.fields.name.label": "5274417ff1ccaf01", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 8fce3c60e77..44c4749a0ef 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const enMetadataForms: NonNullable = { } }, ai_context: { - label: "AI Context Pack" + label: "AI Context Pack", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index d1e41269b53..bb66aea373d 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const esESMetadataForms: NonNullable = } }, ai_context: { - label: "Paquete de contexto de IA" + label: "Paquete de contexto de IA", + sections: { + basics: { + label: "Datos básicos", + description: "La identidad del paquete y el objeto cuyos registros lee." + }, + material: { + label: "Contenido", + description: "Qué parte del registro se entrega al modelo. Cada selector ofrece los campos del objeto raíz, o del objeto propio de la lista relacionada." + } + }, + fields: { + name: { + label: "Nombre", + helpText: "Identificador único (snake_case). La clave context de una habilidad y la herramienta get_record_context nombran el paquete con él." + }, + label: { + label: "Etiqueta", + helpText: "Nombre visible, el encabezado de la respuesta de la herramienta. Un paquete no tiene descripción: escriba aquí su propósito." + }, + object: { + label: "Objeto raíz", + helpText: "El objeto raíz: el paquete lee un registro de él." + }, + fields: { + label: "Campos", + helpText: "Los campos del objeto raíz que se entregan al modelo, en orden (como máximo 30). Una búsqueda entre ellos se responde con el nombre del registro al que apunta." + }, + related: { + label: "Listas relacionadas", + helpText: "Listas hijas que apuntan al registro, un solo nivel (como máximo 3). Cada lista indica su objeto hijo, el campo de referencia que apunta a la raíz y las columnas que se leen en cada fila (como máximo 10); sin columnas, cada fila se lee por su nombre." + }, + body: { + label: "Cuerpo", + helpText: "El único campo de texto largo que se lee como cuerpo del registro." + }, + "body.field": { + label: "Campo del cuerpo", + helpText: "Un campo de texto largo del objeto raíz (textarea, markdown, html, richtext). Cualquier otro campo se informa al guardar el paquete, y entonces el paquete no lleva cuerpo." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 01d10f22669..06130d95ac2 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const frMetadataForms: NonNullable = { } }, ai_context: { - label: "Pack de contexte IA" + label: "Pack de contexte IA", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 8f57769c317..50c90b529e7 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -30,6 +30,24 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.agent.fields.avatar.label": "0f06369995b69b8b", "metadataForms.agent.fields.instructions.label": "ed1cc73e669573d0", "metadataForms.agent.fields.surface.label": "5f41277948ff2598", + "metadataForms.ai_context.fields.body.field.helpText": "e25b48c15258b83d", + "metadataForms.ai_context.fields.body.field.label": "1b880a5fad37e8a3", + "metadataForms.ai_context.fields.body.helpText": "48e8d6e37b041d39", + "metadataForms.ai_context.fields.body.label": "d1753a024d6a9bed", + "metadataForms.ai_context.fields.fields.helpText": "b6f210cfc6f2f162", + "metadataForms.ai_context.fields.fields.label": "f316ec6025047133", + "metadataForms.ai_context.fields.label.helpText": "a7560b638d2146e7", + "metadataForms.ai_context.fields.label.label": "c680364257b11569", + "metadataForms.ai_context.fields.name.helpText": "41ef86776bba4abf", + "metadataForms.ai_context.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.object.helpText": "d785b8445fac8dfe", + "metadataForms.ai_context.fields.object.label": "d465a03c4dfc1d33", + "metadataForms.ai_context.fields.related.helpText": "135e19ad08da41fd", + "metadataForms.ai_context.fields.related.label": "32c91f670a44397f", + "metadataForms.ai_context.sections.basics.description": "4d638a6cd36c7175", + "metadataForms.ai_context.sections.basics.label": "55562f900da68c5d", + "metadataForms.ai_context.sections.material.description": "b8d9cf447db8cfe1", + "metadataForms.ai_context.sections.material.label": "11b295666d0c7917", "metadataForms.api.fields.type.label": "901bb552898b2cab", "metadataForms.app.fields.active.label": "eee107cf4e466779", "metadataForms.app.fields.description.label": "779a4342c8eb6707", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index f342fa0bf07..23261e71d45 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const jaJPMetadataForms: NonNullable = } }, ai_context: { - label: "AI コンテキストパック" + label: "AI コンテキストパック", + sections: { + basics: { + label: "基本情報", + description: "パックの識別情報と、レコードを読み取るオブジェクト。" + }, + material: { + label: "内容", + description: "レコードのどの内容をモデルに渡すか。各ピッカーはルートオブジェクトのフィールド、または関連リスト自身のオブジェクトのフィールドを表示します。" + } + }, + fields: { + name: { + label: "名前", + helpText: "一意の識別子(snake_case)。スキルの context キーと get_record_context ツールはこの名前でパックを指定します。" + }, + label: { + label: "表示名", + helpText: "表示名。ツールの回答の見出しになります。パックには説明がないため、目的はここに書きます。" + }, + object: { + label: "ルートオブジェクト", + helpText: "ルートオブジェクト:パックはそのレコードを 1 件読み取ります。" + }, + fields: { + label: "フィールド", + helpText: "モデルに渡すルートオブジェクトのフィールド(順序どおり、最大 30 個)。参照フィールドは参照先レコードの名前で答えます。" + }, + related: { + label: "関連リスト", + helpText: "このレコードを指す子リスト(1 階層のみ、最大 3 個)。各リストは子オブジェクト、ルートを指す参照フィールド、各行で読み取る列(最大 10 列)を指定します。列がなければ各行は名前だけを読み取ります。" + }, + body: { + label: "本文", + helpText: "レコードの本文として読み取る、ただ 1 つの長文テキストフィールド。" + }, + "body.field": { + label: "本文フィールド", + helpText: "ルートオブジェクトの長文テキストフィールド(textarea、markdown、html、richtext)。それ以外のフィールドは保存時に報告され、パックは本文を持ちません。" + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 8b82296b999..700890fea29 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const koMetadataForms: NonNullable = { } }, ai_context: { - label: "AI 컨텍스트 팩" + label: "AI 컨텍스트 팩", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index 3ca85eeb5aa..8275f417b7a 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -18,6 +18,24 @@ */ export const koGeneratedSourceHashes: Readonly> = { + "metadataForms.ai_context.fields.body.field.helpText": "e25b48c15258b83d", + "metadataForms.ai_context.fields.body.field.label": "1b880a5fad37e8a3", + "metadataForms.ai_context.fields.body.helpText": "48e8d6e37b041d39", + "metadataForms.ai_context.fields.body.label": "d1753a024d6a9bed", + "metadataForms.ai_context.fields.fields.helpText": "b6f210cfc6f2f162", + "metadataForms.ai_context.fields.fields.label": "f316ec6025047133", + "metadataForms.ai_context.fields.label.helpText": "a7560b638d2146e7", + "metadataForms.ai_context.fields.label.label": "c680364257b11569", + "metadataForms.ai_context.fields.name.helpText": "41ef86776bba4abf", + "metadataForms.ai_context.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.object.helpText": "d785b8445fac8dfe", + "metadataForms.ai_context.fields.object.label": "d465a03c4dfc1d33", + "metadataForms.ai_context.fields.related.helpText": "135e19ad08da41fd", + "metadataForms.ai_context.fields.related.label": "32c91f670a44397f", + "metadataForms.ai_context.sections.basics.description": "4d638a6cd36c7175", + "metadataForms.ai_context.sections.basics.label": "55562f900da68c5d", + "metadataForms.ai_context.sections.material.description": "b8d9cf447db8cfe1", + "metadataForms.ai_context.sections.material.label": "11b295666d0c7917", "metadataForms.dashboard.fields.dateRange.allowCustomRange.helpText": "1cdc93f55eefade7", "metadataForms.dashboard.fields.dateRange.allowCustomRange.label": "a1fb0e1cf5fe5d8e", "metadataForms.dashboard.fields.dateRange.defaultRange.helpText": "afff2187966a112f", diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 57510808959..f70ef6712b1 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1329,7 +1329,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // authored in all three locales. // 828 since #36949: the dashboard form declares the `dateRange` // children — three row labels, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(828); + // 837 since #37143: the `ai_context` form (ADR-0160 D1 clause 2) — two + // section labels and seven row labels, authored in all three locales. + expect(translated.length, `${locale} positive control`).toBe(837); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 0fe982739d2..473a97654d0 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const ptBRMetadataForms: NonNullable = } }, ai_context: { - label: "Pacote de contexto de IA" + label: "Pacote de contexto de IA", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index 37989ebabde..bc05572759b 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -21,6 +21,24 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.action.fields.patch.label": "815f68570a78eba1", "metadataForms.action.fields.refusals.status.label": "64a420165247654b", "metadataForms.agent.fields.avatar.label": "0f06369995b69b8b", + "metadataForms.ai_context.fields.body.field.helpText": "e25b48c15258b83d", + "metadataForms.ai_context.fields.body.field.label": "1b880a5fad37e8a3", + "metadataForms.ai_context.fields.body.helpText": "48e8d6e37b041d39", + "metadataForms.ai_context.fields.body.label": "d1753a024d6a9bed", + "metadataForms.ai_context.fields.fields.helpText": "b6f210cfc6f2f162", + "metadataForms.ai_context.fields.fields.label": "f316ec6025047133", + "metadataForms.ai_context.fields.label.helpText": "a7560b638d2146e7", + "metadataForms.ai_context.fields.label.label": "c680364257b11569", + "metadataForms.ai_context.fields.name.helpText": "41ef86776bba4abf", + "metadataForms.ai_context.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.object.helpText": "d785b8445fac8dfe", + "metadataForms.ai_context.fields.object.label": "d465a03c4dfc1d33", + "metadataForms.ai_context.fields.related.helpText": "135e19ad08da41fd", + "metadataForms.ai_context.fields.related.label": "32c91f670a44397f", + "metadataForms.ai_context.sections.basics.description": "4d638a6cd36c7175", + "metadataForms.ai_context.sections.basics.label": "55562f900da68c5d", + "metadataForms.ai_context.sections.material.description": "b8d9cf447db8cfe1", + "metadataForms.ai_context.sections.material.label": "11b295666d0c7917", "metadataForms.dashboard.fields.dateRange.allowCustomRange.helpText": "1cdc93f55eefade7", "metadataForms.dashboard.fields.dateRange.allowCustomRange.label": "a1fb0e1cf5fe5d8e", "metadataForms.dashboard.fields.dateRange.defaultRange.helpText": "afff2187966a112f", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 96aa2440533..62e6b87e23e 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const ruMetadataForms: NonNullable = { } }, ai_context: { - label: "Пакет контекста ИИ" + label: "Пакет контекста ИИ", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 66dcfefbfdb..1c0e0ea0ef2 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -18,6 +18,24 @@ */ export const ruGeneratedSourceHashes: Readonly> = { + "metadataForms.ai_context.fields.body.field.helpText": "e25b48c15258b83d", + "metadataForms.ai_context.fields.body.field.label": "1b880a5fad37e8a3", + "metadataForms.ai_context.fields.body.helpText": "48e8d6e37b041d39", + "metadataForms.ai_context.fields.body.label": "d1753a024d6a9bed", + "metadataForms.ai_context.fields.fields.helpText": "b6f210cfc6f2f162", + "metadataForms.ai_context.fields.fields.label": "f316ec6025047133", + "metadataForms.ai_context.fields.label.helpText": "a7560b638d2146e7", + "metadataForms.ai_context.fields.label.label": "c680364257b11569", + "metadataForms.ai_context.fields.name.helpText": "41ef86776bba4abf", + "metadataForms.ai_context.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.object.helpText": "d785b8445fac8dfe", + "metadataForms.ai_context.fields.object.label": "d465a03c4dfc1d33", + "metadataForms.ai_context.fields.related.helpText": "135e19ad08da41fd", + "metadataForms.ai_context.fields.related.label": "32c91f670a44397f", + "metadataForms.ai_context.sections.basics.description": "4d638a6cd36c7175", + "metadataForms.ai_context.sections.basics.label": "55562f900da68c5d", + "metadataForms.ai_context.sections.material.description": "b8d9cf447db8cfe1", + "metadataForms.ai_context.sections.material.label": "11b295666d0c7917", "metadataForms.dashboard.fields.dateRange.allowCustomRange.helpText": "1cdc93f55eefade7", "metadataForms.dashboard.fields.dateRange.allowCustomRange.label": "a1fb0e1cf5fe5d8e", "metadataForms.dashboard.fields.dateRange.defaultRange.helpText": "afff2187966a112f", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 02056cb73a6..dee1da3bbb2 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const zhCNMetadataForms: NonNullable = } }, ai_context: { - label: "AI 上下文包" + label: "AI 上下文包", + sections: { + basics: { + label: "基本信息", + description: "资料包的标识,以及它读取哪个对象的记录。" + }, + material: { + label: "资料内容", + description: "把记录的哪些内容交给模型。每个选择器列出根对象的字段,或该关联列表自身对象的字段。" + } + }, + fields: { + name: { + label: "名称", + helpText: "唯一标识(snake_case)。技能的 context 键和 get_record_context 工具都按它指名资料包。" + }, + label: { + label: "显示名称", + helpText: "显示名称,即工具回答的标题。资料包没有描述:用途写在这里。" + }, + object: { + label: "根对象", + helpText: "根对象:资料包读取它的一条记录。" + }, + fields: { + label: "字段", + helpText: "交给模型的根对象字段,按顺序(最多 30 个)。其中的查找字段以它指向的记录名称作答。" + }, + related: { + label: "关联列表", + helpText: "指向这条记录的子列表,只读一层(最多 3 个)。每个列表指明子对象、指向根对象的引用字段,以及每行读取的列(最多 10 列);不选列时每行只读取其名称。" + }, + body: { + label: "正文", + helpText: "作为记录正文读取的那一个长文本字段。" + }, + "body.field": { + label: "正文字段", + helpText: "根对象的一个长文本字段(textarea、markdown、html、richtext)。选其他字段会在保存时报告,资料包也就不带正文。" + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 44aa701392d..b1851fb0e28 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -3161,6 +3161,46 @@ export const zhHantMetadataForms: NonNullable } }, ai_context: { - label: "AI 上下文包" + label: "AI 上下文包", + sections: { + basics: { + label: "Basics", + description: "The pack's identity and the object whose records it reads." + }, + material: { + label: "Material", + description: "What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list's own object." + } + }, + fields: { + name: { + label: "Name", + helpText: "Unique identifier (snake_case). A skill's context key and the get_record_context tool name the pack by it." + }, + label: { + label: "Label", + helpText: "Display name, the header of the tool answer. A pack has no description: write its purpose here." + }, + object: { + label: "Root object", + helpText: "The root object: the pack reads one record of it." + }, + fields: { + label: "Fields", + helpText: "The root object's fields handed to the model, in order (at most 30). A lookup among them is answered with the name of the record it points at." + }, + related: { + label: "Related lists", + helpText: "Child lists that point at the record, one level deep (at most 3). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most 10); with no columns a row is read by its name." + }, + body: { + label: "Body", + helpText: "The one long-text field read as the record's body." + }, + "body.field": { + label: "Body field", + helpText: "A long-text field of the root object (textarea, markdown, html, richtext). Any other field is reported when the pack is saved, and the pack then carries no body." + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index 1bfc1357355..2631dfc2a38 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -18,6 +18,24 @@ */ export const zhHantGeneratedSourceHashes: Readonly> = { + "metadataForms.ai_context.fields.body.field.helpText": "e25b48c15258b83d", + "metadataForms.ai_context.fields.body.field.label": "1b880a5fad37e8a3", + "metadataForms.ai_context.fields.body.helpText": "48e8d6e37b041d39", + "metadataForms.ai_context.fields.body.label": "d1753a024d6a9bed", + "metadataForms.ai_context.fields.fields.helpText": "b6f210cfc6f2f162", + "metadataForms.ai_context.fields.fields.label": "f316ec6025047133", + "metadataForms.ai_context.fields.label.helpText": "a7560b638d2146e7", + "metadataForms.ai_context.fields.label.label": "c680364257b11569", + "metadataForms.ai_context.fields.name.helpText": "41ef86776bba4abf", + "metadataForms.ai_context.fields.name.label": "5274417ff1ccaf01", + "metadataForms.ai_context.fields.object.helpText": "d785b8445fac8dfe", + "metadataForms.ai_context.fields.object.label": "d465a03c4dfc1d33", + "metadataForms.ai_context.fields.related.helpText": "135e19ad08da41fd", + "metadataForms.ai_context.fields.related.label": "32c91f670a44397f", + "metadataForms.ai_context.sections.basics.description": "4d638a6cd36c7175", + "metadataForms.ai_context.sections.basics.label": "55562f900da68c5d", + "metadataForms.ai_context.sections.material.description": "b8d9cf447db8cfe1", + "metadataForms.ai_context.sections.material.label": "11b295666d0c7917", "metadataForms.dashboard.fields.dateRange.allowCustomRange.helpText": "1cdc93f55eefade7", "metadataForms.dashboard.fields.dateRange.allowCustomRange.label": "a1fb0e1cf5fe5d8e", "metadataForms.dashboard.fields.dateRange.defaultRange.helpText": "afff2187966a112f", diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index c354fd6bd65..f67eba6156f 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -267,6 +267,7 @@ "VectorStoreProviderSchema (const)", "VectorStoreSchema (const)", "agentForm (const)", + "aiContextForm (const)", "defineAgent (function)", "defineSkill (function)", "defineSolutionBlueprint (function)", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 89026a3c44b..9f409af680e 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -264,6 +264,7 @@ "VectorStoreProviderSchema": "src/ai/embedding.zod.ts#VectorStoreProviderSchema (const)", "VectorStoreSchema": "src/ai/embedding.zod.ts#VectorStoreSchema (const)", "agentForm": "src/ai/agent.form.ts#agentForm (const)", + "aiContextForm": "src/ai/ai-context.form.ts#aiContextForm (const)", "defineAgent": "src/ai/agent.zod.ts#defineAgent (function)", "defineSkill": "src/ai/skill.zod.ts#defineSkill (function)", "defineSolutionBlueprint": "src/ai/solution-blueprint.zod.ts#defineSolutionBlueprint (function)", diff --git a/packages/spec/src/ai/ai-context.form.test.ts b/packages/spec/src/ai/ai-context.form.test.ts new file mode 100644 index 00000000000..35fcf7db268 --- /dev/null +++ b/packages/spec/src/ai/ai-context.form.test.ts @@ -0,0 +1,40 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The context pack form (`ai_context`, ADR-0160 D1 clause 2): registered for + * Studio's generic metadata editor, and every field picker scoped by the + * pack's root object (card #37143). That the form names only keys + * `AiContextSchema` accepts, and offers every one, is the registry-wide + * reconciliation in `system/metadata-form-zod-reconciliation.test.ts`. + */ + +import { describe, it, expect } from 'vitest'; + +import { aiContextForm } from './ai-context.form'; +import { METADATA_FORM_REGISTRY } from '../system/metadata-form-registry'; + +type Row = { field?: string; widget?: string; dependsOn?: string; required?: boolean; fields?: Row[] }; + +function rows(): Row[] { + return (aiContextForm.sections ?? []).flatMap((s) => (s.fields ?? []) as Row[]); +} +const row = (field: string) => rows().find((r) => r.field === field); + +describe('ai_context form (ADR-0160 D1, #37143)', () => { + it('is the registry\'s form for the type', () => { + expect(METADATA_FORM_REGISTRY.ai_context).toBe(aiContextForm); + }); + + it('picks the root from the object catalog and requires the identity rows', () => { + expect(row('object')).toMatchObject({ widget: 'ref:object', required: true }); + expect(row('name')?.required).toBe(true); + expect(row('label')?.required).toBe(true); + }); + + it('scopes every field picker by the root object', () => { + expect(row('fields')).toMatchObject({ widget: 'field-multi', dependsOn: 'object' }); + expect(row('related')).toMatchObject({ widget: 'related-list-entries', dependsOn: 'object' }); + const body = row('body'); + expect(body?.fields?.find((r) => r.field === 'field')).toMatchObject({ widget: 'field-ref', dependsOn: 'object' }); + }); +}); diff --git a/packages/spec/src/ai/ai-context.form.ts b/packages/spec/src/ai/ai-context.form.ts new file mode 100644 index 00000000000..cf06d86e062 --- /dev/null +++ b/packages/spec/src/ai/ai-context.form.ts @@ -0,0 +1,60 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { defineForm } from '../ui/view.zod'; +import { AI_CONTEXT_BODY_FIELD_TYPES, AI_CONTEXT_MAX_FIELDS, AI_CONTEXT_MAX_RELATED, AI_CONTEXT_MAX_RELATED_FIELDS } from './ai-context.zod'; + +/** + * Context Pack (`ai_context`) Metadata Form — ADR-0160 D1, clause 2 (runtime + * authoring). + * + * The form Studio's generic metadata editor lays a context pack out with: the + * root object, its fields, the child lists and their columns, the body field. + * Every field picker is scoped by the pack's own root: + * + * - `fields` is the generic `field-multi` block with `dependsOn: 'object'` + * (the `page.form.ts` precedent): it offers the root object's fields. + * - `related` is the `related-list-entries` block (the `object.form.ts` + * precedent). Under a pack its entries are `{ object, field?, fields? }`, + * so the block offers the relationships that point at the root and, for + * each entry, that child object's fields as its columns. + * - `body.field` is a single field picker over the root object's fields. + * + * The form judges nothing. A name the stack does not define, a related entry + * with no link to the root, or a body that is not long text is reported when + * the pack is saved (`validateAiContext` on the runtime publish door) and by + * `os validate`; the bounds are refused by `AiContextSchema` at parse. + */ +export const aiContextForm = defineForm({ + schemaId: 'ai_context', + type: 'simple', + sections: [ + { + name: 'basics', + label: 'Basics', + description: 'The pack\'s identity and the object whose records it reads.', + columns: 2, + fields: [ + { field: 'name', required: true, immutable: true, colSpan: 1, helpText: 'Unique identifier (snake_case). A skill\'s context key and the get_record_context tool name the pack by it.' }, + { field: 'label', required: true, colSpan: 1, helpText: 'Display name, the header of the tool answer. A pack has no description: write its purpose here.' }, + { field: 'object', label: 'Root object', widget: 'ref:object', required: true, colSpan: 2, helpText: 'The root object: the pack reads one record of it.' }, + ], + }, + { + name: 'material', + label: 'Material', + description: 'What of the record is handed to the model. Each picker offers the fields of the root object, or of the related list\'s own object.', + fields: [ + { field: 'fields', widget: 'field-multi', dependsOn: 'object', helpText: `The root object's fields handed to the model, in order (at most ${AI_CONTEXT_MAX_FIELDS}). A lookup among them is answered with the name of the record it points at.` }, + { field: 'related', label: 'Related lists', widget: 'related-list-entries', dependsOn: 'object', helpText: `Child lists that point at the record, one level deep (at most ${AI_CONTEXT_MAX_RELATED}). Each list names its child object, the reference field that points at the root, and the columns read for each row (at most ${AI_CONTEXT_MAX_RELATED_FIELDS}); with no columns a row is read by its name.` }, + { + field: 'body', + type: 'composite', + helpText: 'The one long-text field read as the record\'s body.', + fields: [ + { field: 'field', label: 'Body field', widget: 'field-ref', dependsOn: 'object', helpText: `A long-text field of the root object (${AI_CONTEXT_BODY_FIELD_TYPES.join(', ')}). Any other field is reported when the pack is saved, and the pack then carries no body.` }, + ], + }, + ], + }, + ], +}); diff --git a/packages/spec/src/ai/index.ts b/packages/spec/src/ai/index.ts index 78499daa774..4c23c418f45 100644 --- a/packages/spec/src/ai/index.ts +++ b/packages/spec/src/ai/index.ts @@ -32,6 +32,7 @@ export * from './tool.zod'; export { toolForm } from './tool.form'; export * from './skill.zod'; export { skillForm } from './skill.form'; +export { aiContextForm } from './ai-context.form'; export * from './conversation.zod'; export * from './model-registry.zod'; export * from './embedding.zod'; diff --git a/packages/spec/src/system/metadata-form-registry.ts b/packages/spec/src/system/metadata-form-registry.ts index 9d128951671..1d58e087ae6 100644 --- a/packages/spec/src/system/metadata-form-registry.ts +++ b/packages/spec/src/system/metadata-form-registry.ts @@ -44,7 +44,7 @@ import { } from '../ui'; import { positionForm } from '../identity'; import { permissionForm } from '../security'; -import { agentForm, toolForm, skillForm } from '../ai'; +import { agentForm, toolForm, skillForm, aiContextForm } from '../ai'; import { flowForm } from '../automation'; import { emailTemplateForm } from './email-template.form'; @@ -84,6 +84,7 @@ export const METADATA_FORM_REGISTRY: Readonly> = Object agent: agentForm, tool: toolForm, skill: skillForm, + ai_context: aiContextForm, flow: flowForm, permission: permissionForm, email_template: emailTemplateForm, diff --git a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts index a4d0d766f5d..81a9efff4f1 100644 --- a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts +++ b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts @@ -120,6 +120,7 @@ const OBJECTS_READERS: Record = { }, 'packages/app-shell/src/views/metadata-admin/PositionHoldersSection.tsx': { kind: 'off', why: 'the metadata admin' }, 'packages/app-shell/src/views/metadata-admin/AssignedUsersSection.tsx': { kind: 'off', why: 'the metadata admin' }, + 'packages/app-shell/src/views/metadata-admin/ContextPackRelatedEntries.tsx': { kind: 'off', why: "the metadata admin's context-pack related lists (objectstack#37143)" }, 'packages/app-shell/src/views/setup/RecycleBinPage.tsx': { kind: 'off', why: 'Setup → Recycle Bin, not mounted on an app object-list open' }, 'packages/app-shell/src/views/setup/PublicFormsSetupPage.tsx': { kind: 'off', why: 'Setup → Public forms, not mounted on an app object-list open (objectstack#36444)' }, 'packages/app-shell/src/views/metadata-admin/previews/ScreenPreview.tsx': { kind: 'off', why: "the metadata admin's form-screen preview" }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/ContextPackRelatedEntries-37143.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ContextPackRelatedEntries-37143.test.tsx new file mode 100644 index 00000000000..c33c5dc19c8 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ContextPackRelatedEntries-37143.test.tsx @@ -0,0 +1,276 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37143 — the `related-list-entries` block under a context pack + * (`ai_context`, ADR-0160 D1). The pack's `related` entries are + * `{ object, field?, fields? }`: the add picker offers the relationships that + * point at the pack's root, each entry's columns come from THAT child object, + * and every value the block writes parses as a pack (`AiContextSchema`). + */ + +// The source under test reaches these through dynamic imports: their first load is paid at collection. +import '@objectstack/formula'; +import '@objectstack/lint'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup, within } from '@testing-library/react'; +import { z } from 'zod'; +import { AiContextSchema, aiContextForm } from '@objectstack/spec/ai'; +import { getMetadataTypeSchema } from '@objectstack/spec/kernel'; + +/** The console's served objects: two children point at `policy`, one of them twice. */ +const OBJECTS = [ + { name: 'policy', label: 'Policy', fields: { title: { type: 'text', label: 'Title' }, parent: { type: 'lookup', reference: 'policy', label: 'Parent policy' } } }, + { name: 'policy_revision', label: 'Policy revision', fields: { version: { type: 'text', label: 'Version' }, published_at: { type: 'datetime', label: 'Published' }, policy: { type: 'master_detail', reference: 'policy', label: 'Policy' } } }, + { + name: 'acknowledgement', + label: 'Acknowledgement', + fields: [ + { name: 'signed_on', type: 'date', label: 'Signed on' }, + { name: 'policy', type: 'lookup', reference: 'policy', label: 'Policy' }, + { name: 'superseded_policy', type: 'lookup', reference: 'policy', label: 'Superseded policy' }, + ], + }, + { name: 'account', label: 'Account', fields: { name: { type: 'text' } } }, +]; + +/** The object list's load status, as the metadata context reports it (`getTypeStatus('object')`). */ +const CATALOG = vi.hoisted(() => ({ status: 'ready' as string })); + +vi.mock('@object-ui/react', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadata: () => ({ objects: CATALOG.status === 'ready' ? OBJECTS : [], getTypeStatus: () => CATALOG.status }), +})); + +/** Each child's own fields, as the draft-overlaid object read serves them. */ +vi.mock('./previews/useObjectFields.js', () => ({ + useObjectFields: (name: string | undefined) => { + const object = OBJECTS.find((o) => o.name === name); + const raw = object?.fields ?? []; + const fields = (Array.isArray(raw) ? raw : Object.entries(raw).map(([n, d]) => ({ name: n, ...(d as object) }))) as Array<{ name: string; label?: string; type: string }>; + return { fields: fields.map((f) => ({ name: f.name, label: f.label ?? f.name, type: f.type, hidden: false })), loading: false, error: null }; + }, +})); + +import { WIDGETS } from './widgets'; +import { compositeWith } from './SchemaForm'; +import { contextPackLinks, isContextPackEntrySchema } from './ContextPackRelatedEntries'; + +afterEach(() => { + cleanup(); + CATALOG.status = 'ready'; +}); + +const Entries = WIDGETS['related-list-entries']; + +/** + * The JSON Schema `/meta/types` serves for a type: the OUTPUT derivation + * (`z.toJSONSchema(schema, { unrepresentable: 'any' })`, the call + * `toJsonSchemaSafe` makes first), where a key with `.default()` is listed as + * required and carries its `default`. + */ +function served(type: string): Record { + return z.toJSONSchema(getMetadataTypeSchema(type)!, { unrepresentable: 'any' }) as Record; +} + +/** One top-level key's node in a served schema: through `$ref`s, and through the union branch that declares it. */ +function servedNode(type: string, key: string): Record | undefined { + const root = served(type); + const defs = (root.$defs ?? {}) as Record; + const deref = (n: any): any => (n?.$ref ? deref(defs[String(n.$ref).split('/').pop()!]) : n); + const find = (n: any, depth: number): any => { + n = deref(n); + if (!n || depth > 4) return undefined; + if (n.properties?.[key]) return deref(n.properties[key]); + for (const b of n.anyOf ?? n.oneOf ?? []) { + const hit = find(b, depth + 1); + if (hit) return hit; + } + return undefined; + }; + return find(root, 0); +} + +/** The pack's top-level nodes, as served. */ +const PACK_SCHEMA = served('ai_context').properties as Record; +const RELATED_SCHEMA = PACK_SCHEMA.related; + +function relatedRow(): Record | undefined { + for (const section of aiContextForm.sections ?? []) { + for (const f of section.fields ?? []) if ((f as { field?: string }).field === 'related') return f as never; + } + return undefined; +} + +function renderBlock(value: unknown, onChange = vi.fn(), root: string | null = 'policy') { + render( + , + ); + return onChange; +} + +async function openAddList(): Promise { + fireEvent.keyDown(screen.getByTestId('context-pack-add-list'), { key: 'ArrowDown' }); + return await screen.findByRole('listbox'); +} + +/** The pack the block's value makes, judged by the spec's own parse. */ +function parsesAsPack(related: unknown): boolean { + const pack = { name: 'policy_document', label: 'Policy document', object: 'policy', ...(related === undefined ? {} : { related }) }; + return AiContextSchema.safeParse(pack).success; +} + +describe('context pack related lists (objectstack#37143)', () => { + it('the served entry schema selects the pack face; the object form\'s does not', () => { + expect(isContextPackEntrySchema(RELATED_SCHEMA)).toBe(true); + expect(isContextPackEntrySchema({ type: 'array', items: { anyOf: [{ type: 'string' }, { type: 'object', properties: { list: {} } }] } })).toBe(false); + expect(isContextPackEntrySchema({})).toBe(false); + }); + + it('offers every reference field that points at the root, a self-reference and both links of one child included', async () => { + expect(contextPackLinks('policy', OBJECTS).map((l) => `${l.object}.${l.field}`)).toEqual([ + 'policy.parent', + 'policy_revision.policy', + 'acknowledgement.policy', + 'acknowledgement.superseded_policy', + ]); + renderBlock(undefined); + const offered = within(await openAddList()).getAllByRole('option').map((o) => o.textContent); + expect(offered).toHaveLength(4); + expect(offered.some((t) => t?.includes('Account'))).toBe(false); + }); + + it('a picked relationship is written as { object, field }, and the value parses as a pack', async () => { + const onChange = renderBlock(undefined); + fireEvent.click(within(await openAddList()).getByRole('option', { name: /acknowledgement\.superseded_policy/ })); + expect(onChange).toHaveBeenLastCalledWith([{ object: 'acknowledgement', field: 'superseded_policy' }]); + expect(parsesAsPack(onChange.mock.lastCall![0])).toBe(true); + }); + + it('a related entry\'s columns are its child object\'s fields, not the root\'s', async () => { + const onChange = renderBlock([{ object: 'policy_revision', field: 'policy', fields: ['version'] }]); + fireEvent.keyDown(screen.getByTestId('context-pack-add-column-policy_revision'), { key: 'ArrowDown' }); + const offered = within(await screen.findByRole('listbox')).getAllByRole('option').map((o) => o.textContent); + expect(offered.some((t) => t?.includes('published_at'))).toBe(true); + expect(offered.some((t) => t?.includes('title'))).toBe(false); + fireEvent.click(within(screen.getByRole('listbox')).getByRole('option', { name: /published_at/ })); + expect(onChange).toHaveBeenLastCalledWith([{ object: 'policy_revision', field: 'policy', fields: ['version', 'published_at'] }]); + expect(parsesAsPack(onChange.mock.lastCall![0])).toBe(true); + }); + + it('removing the last column removes the key; removing the last list removes `related`', () => { + const onChange = renderBlock([{ object: 'policy_revision', field: 'policy', fields: ['version'] }]); + fireEvent.click(screen.getByRole('button', { name: 'Remove version' })); + expect(onChange).toHaveBeenLastCalledWith([{ object: 'policy_revision', field: 'policy' }]); + expect(parsesAsPack(onChange.mock.lastCall![0])).toBe(true); + fireEvent.click(screen.getByRole('button', { name: 'Remove policy_revision' })); + expect(onChange).toHaveBeenLastCalledWith(undefined); + expect(parsesAsPack(onChange.mock.lastCall![0])).toBe(true); + }); + + it('a stored entry the catalog shows no link for is kept and marked, and a listed link is not offered again', async () => { + renderBlock([{ object: 'account' }, { object: 'policy_revision' }]); + expect(screen.getByTestId('context-pack-unlinked-account')).toBeInTheDocument(); + expect(screen.queryByTestId('context-pack-unlinked-policy_revision')).toBeNull(); + const offered = within(await openAddList()).getAllByRole('option').map((o) => o.textContent); + expect(offered.some((t) => t?.includes('policy_revision.policy'))).toBe(false); + }); + + it('stops adding at the schema\'s bound, and without a root offers nothing', () => { + renderBlock([{ object: 'policy', field: 'parent' }, { object: 'policy_revision' }, { object: 'acknowledgement', field: 'policy' }]); + expect(screen.getByTestId('context-pack-add-list')).toBeDisabled(); + cleanup(); + renderBlock(undefined, vi.fn(), null); + expect(screen.getByTestId('context-pack-add-list')).toBeDisabled(); + }); + + it('the add picker carries the host\'s id, so the row label names it', () => { + renderBlock(undefined); + expect(screen.getByTestId('context-pack-add-list')).toHaveAttribute('id', 'related'); + }); + + it('while the object list loads, or after it failed, no stored entry is marked unlinked and the picker says why it is empty', () => { + for (const status of ['loading', 'idle', 'error']) { + CATALOG.status = status; + renderBlock([{ object: 'policy_revision', field: 'policy' }, { object: 'account' }]); + expect(screen.queryByTestId('context-pack-unlinked-account')).toBeNull(); + expect(screen.queryByTestId('context-pack-unlinked-policy_revision')).toBeNull(); + expect(screen.getByTestId('context-pack-add-list')).toBeDisabled(); + expect(screen.getByTestId('context-pack-add-list').textContent).not.toContain('No reference field'); + expect(screen.queryByTestId('context-pack-catalog-failed') !== null).toBe(status === 'error'); + cleanup(); + } + CATALOG.status = 'ready'; + renderBlock([{ object: 'account' }]); + expect(screen.getByTestId('context-pack-unlinked-account')).toBeInTheDocument(); + }); +}); + +/** + * The two other pickers of the form, emptied: a pack whose `fields` is `[]` or + * whose `body` is `{ field: '' }` is refused at save with no way back in the + * form, so an emptied value removes its key (L2 review S1 on #37315). + */ +describe('an emptied root picker removes its key (objectstack#37143)', () => { + const FieldMulti = WIDGETS['field-multi']; + const loaded = { status: 'loaded', data: [{ name: 'title', label: 'Title', type: 'text' }] } as never; + + it('removing the last root field of a pack writes no `fields`, and the pack parses', () => { + expect(PACK_SCHEMA.fields.minItems).toBe(1); + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Remove title' })); + expect(onChange).toHaveBeenLastCalledWith(undefined); + expect(AiContextSchema.safeParse({ name: 'p', label: 'P', object: 'policy', fields: onChange.mock.lastCall![0] }).success).toBe(true); + }); + + it('an array its schema lets be empty still writes []', () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button', { name: 'Remove title' })); + expect(onChange).toHaveBeenLastCalledWith([]); + }); + + it('choosing "None" for the body field removes `body`; a composite requiring nothing keeps {}', () => { + expect(PACK_SCHEMA.body.required).toEqual(['field']); + expect('default' in PACK_SCHEMA.body.properties.field).toBe(false); + const body = compositeWith({ field: 'summary' }, 'field', '', PACK_SCHEMA.body); + expect(body).toBeUndefined(); + expect(AiContextSchema.safeParse({ name: 'p', label: 'P', object: 'policy', body }).success).toBe(true); + expect(compositeWith({ field: 'summary' }, 'field', 'notes', PACK_SCHEMA.body)).toEqual({ field: 'notes' }); + expect(compositeWith({ a: 'x' }, 'a', undefined, { type: 'object', properties: { a: {} } })).toEqual({}); + expect(compositeWith({ a: 'x', b: 1 }, 'a', '', PACK_SCHEMA.body)).toEqual({ b: 1 }); + }); +}); + +/** + * L2 review S3 on #37315: the served derivation lists a defaulted key as + * required, so "requires a key" alone would drop a legal `{}` whose presence the + * renderer reads. Only a required key with no default makes `{}` no value. + * Swept over every composite row of the registered forms against the served + * derivation: these are the view's, the two the review confirmed and a third. + */ +describe('a composite whose required keys all carry a default keeps {} (objectstack#37143)', () => { + it.each([ + ['pagination', { pageSize: 25 }, 'pageSize'], + ['selection', { type: 'multiple' }, 'type'], + ['gallery', { coverFit: 'contain' }, 'coverFit'], + ])('view `%s`: clearing its last key leaves {}', (key, stored, sub) => { + const node = servedNode('view', key)!; + expect(node.required).toContain(sub); + expect('default' in node.properties[sub]).toBe(true); + expect(compositeWith(stored, sub, undefined, node as never)).toEqual({}); + }); + + it('view `kanban` (a required key with no default) is still removed when emptied', () => { + const node = servedNode('view', 'kanban')!; + expect(node.required).toContain('groupByField'); + expect(compositeWith({ groupByField: 'status' }, 'groupByField', undefined, node as never)).toBeUndefined(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ContextPackRelatedEntries.tsx b/ui/packages/app-shell/src/views/metadata-admin/ContextPackRelatedEntries.tsx new file mode 100644 index 00000000000..39a896fea95 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ContextPackRelatedEntries.tsx @@ -0,0 +1,409 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `related-list-entries` block under a context pack (`ai_context`, + * objectstack ADR-0160 D1, card #37143): the pack's child lists. + * + * An object's `relatedLists` entry is a bare name or `{ list, label?, columns? }`; + * a pack's `related` entry is `{ object, field?, fields? }` — the child object, + * its reference field that points at the pack's root, and the columns read for + * each row. The block tells the two apart by the entry schema it is handed + * ({@link isContextPackEntrySchema}), never by the metadata type's name, and + * this component draws the pack's shape: + * + * - The add picker offers every relationship that points at the root: each + * reference field (`REFERENCE_VALUE_TYPES`, resolved by the spec's own + * `referenceTargetOf`) of every object the console serves whose target is + * the root — the link the save-time judge (`validateAiContext`) resolves. + * A picked relationship is written `{ object, field }`: naming the field + * keeps the entry resolvable if the child later gains a second link. + * - Each entry's columns are picked from THAT child object's fields + * (`useObjectFields`, draft-overlaid), never the root's. + * - A stored entry keeps every key it carries; a write changes only what the + * author touched. An entry whose link the catalog does not show is kept and + * marked: the save-time report is the one judge of it. + * - The bounds the schema refuses at parse are bounds of the controls: no + * add past `maxItems` lists or columns, and an emptied list or column set + * removes its key (both arrays are `minItems: 1`). + */ + +import * as React from 'react'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@object-ui/components'; +import { useMetadata } from '@object-ui/react'; +import { REFERENCE_VALUE_TYPES, referenceTargetOf } from '@objectstack/spec/data'; +import { t, tFormat, useMetadataLocale } from './i18n.js'; +import { useObjectFields } from './previews/useObjectFields.js'; + +/** One stored `related` entry of a context pack, as far as the editor reads it. */ +export interface ContextPackRelatedEntry { + object: string; + field?: string; + fields?: string[]; + [key: string]: unknown; +} + +/** One relationship that points at the root: a reference field of a child object. */ +export interface ContextPackLink { + object: string; + objectLabel: string; + field: string; + fieldLabel: string; +} + +type AnyRec = Record; + +/** + * Whether a `related-list-entries` block is editing a context pack's `related`: + * its entries are objects that declare an `object` key (the pack's entry + * schema), not the object form's names or `{ list, … }` entries. + */ +export function isContextPackEntrySchema(schema: Record | undefined): boolean { + const props = schema?.items?.properties; + return !!props && typeof props === 'object' && 'object' in props && !('list' in props); +} + +/** The `maxItems` a JSON Schema array node declares, if any. */ +export function maxItemsOf(schema: Record | undefined): number | undefined { + const max = schema?.maxItems; + return typeof max === 'number' && Number.isFinite(max) ? max : undefined; +} + +/** A field map in either served shape (name-keyed record or array of `{ name }`). */ +function fieldEntriesOf(object: AnyRec): Array<[string, AnyRec]> { + const raw = object.fields; + if (Array.isArray(raw)) { + return raw + .filter((f): f is AnyRec => !!f && typeof f === 'object' && typeof (f as AnyRec).name === 'string') + .map((f) => [f.name as string, f]); + } + if (raw && typeof raw === 'object') { + return Object.entries(raw as Record).filter( + (e): e is [string, AnyRec] => !!e[1] && typeof e[1] === 'object', + ); + } + return []; +} + +function labelOf(def: AnyRec, fallback: string): string { + return typeof def.label === 'string' && def.label.trim() ? def.label : fallback; +} + +/** The object a reference field points at, or `undefined` for any other field. */ +function targetOf(def: AnyRec): string | undefined { + if (typeof def.type !== 'string' || !REFERENCE_VALUE_TYPES.has(def.type)) return undefined; + try { + return referenceTargetOf(def); + } catch { + // An unreadable carrier links nowhere here; the save-time report names it. + return undefined; + } +} + +/** + * Every relationship that points at `root` in `objects`, in catalog order: + * one per reference field whose target is the root (a self-reference counts). + */ +export function contextPackLinks(root: string | undefined, objects: readonly unknown[]): ContextPackLink[] { + if (!root) return []; + const out: ContextPackLink[] = []; + for (const o of objects) { + if (!o || typeof o !== 'object') continue; + const object = o as AnyRec; + const name = typeof object.name === 'string' ? object.name : ''; + if (!name) continue; + for (const [field, def] of fieldEntriesOf(object)) { + if (targetOf(def) !== root) continue; + out.push({ object: name, objectLabel: labelOf(object, name), field, fieldLabel: labelOf(def, field) }); + } + } + return out; +} + +/** The stored entries read as pack entries; anything else is kept as it is. */ +function entriesOf(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +function isPackEntry(entry: unknown): entry is ContextPackRelatedEntry { + return !!entry && typeof entry === 'object' && !Array.isArray(entry) && typeof (entry as AnyRec).object === 'string'; +} + +/** Whether a stored entry names `link`: the same child, and the same field or none. */ +export function entryNamesLink(entry: unknown, link: ContextPackLink): boolean { + if (!isPackEntry(entry) || entry.object !== link.object) return false; + return entry.field === undefined || entry.field === link.field; +} + +/** The link a stored entry resolves to, the way the save-time judge resolves it. */ +function resolvedLink(entry: ContextPackRelatedEntry, links: readonly ContextPackLink[]): ContextPackLink | undefined { + const ofChild = links.filter((l) => l.object === entry.object); + if (entry.field !== undefined) return ofChild.find((l) => l.field === entry.field); + return ofChild.length === 1 ? ofChild[0] : undefined; +} + +/** `entry` with `fields` replaced; an empty column set removes the key. */ +export function withColumns(entry: ContextPackRelatedEntry, columns: readonly string[]): ContextPackRelatedEntry { + const { fields: _drop, ...rest } = entry; + return columns.length > 0 ? { ...rest, fields: [...columns] } : (rest as ContextPackRelatedEntry); +} + +const ADD_NONE = ''; + +function linkKey(link: Pick): string { + return `${link.object}.${link.field}`; +} + +/** One entry's columns: the child object's fields, picked in order. */ +function EntryColumns({ + entry, + maxColumns, + readOnly, + onChange, +}: { + entry: ContextPackRelatedEntry; + maxColumns: number | undefined; + readOnly?: boolean; + onChange: (next: ContextPackRelatedEntry) => void; +}) { + const locale = useMetadataLocale(); + const { fields, loading, error } = useObjectFields(entry.object); + const columns = Array.isArray(entry.fields) ? entry.fields.filter((c): c is string => typeof c === 'string') : []; + const labelFor = (name: string) => fields.find((f) => f.name === name)?.label || name; + const remaining = fields.filter((f) => !columns.includes(f.name)); + const full = maxColumns !== undefined && columns.length >= maxColumns; + const placeholder = error + ? t('engine.form.optionsLoadFailedTitle', locale) + : loading + ? t('engine.form.loadingOptions', locale) + : full + ? tFormat('engine.form.contextPack.columnsFull', locale, { max: String(maxColumns) }) + : remaining.length + ? t('engine.form.contextPack.addColumn', locale) + : t('engine.form.allFieldsAdded', locale); + return ( +
+ {columns.length === 0 ? ( +

{t('engine.form.contextPack.columnsDefault', locale)}

+ ) : ( +
+ {columns.map((col) => ( + + {labelFor(col)} + {col} + {!readOnly && ( + + )} + + ))} +
+ )} + {!readOnly && ( + + )} +
+ ); +} + +/** What the object catalog behind the link list can say: an answer, not yet, or nothing. */ +export type ContextPackCatalogState = 'ready' | 'loading' | 'error'; + +/** The metadata context's per-type status, read as the catalog's state (absent = ready). */ +export function catalogStateOf(status: string | undefined): ContextPackCatalogState { + if (status === undefined || status === 'ready') return 'ready'; + return status === 'error' ? 'error' : 'loading'; +} + +export interface ContextPackRelatedEntriesProps { + /** The naming props of the block's primary control (the host's `controlNaming`). */ + naming: { id?: string; 'aria-labelledby'?: string; 'aria-required'?: true }; + /** The `related` array's JSON Schema node (its `maxItems`, its entry's `fields.maxItems`). */ + schema: Record; + /** The pack's root object (the draft's `object`). */ + root: string | undefined; + value: unknown; + onChange: (v: unknown) => void; + readOnly?: boolean; +} + +export function ContextPackRelatedEntries({ naming, schema, root, value, onChange, readOnly }: ContextPackRelatedEntriesProps) { + const locale = useMetadataLocale(); + const metadata = useMetadata(); + const objects = metadata.objects; + // The link catalog is only an answer once the object list has loaded: while + // it is in flight, or after it failed, "nothing links here" would be false, + // so no stored entry is marked unlinked and the add picker says why it is + // empty. Read after `objects`, whose getter starts the load. A context with + // no `getTypeStatus` is always ready (the field's own contract). + const catalog = catalogStateOf(metadata.getTypeStatus?.('object')); + const links = React.useMemo( + () => (catalog === 'ready' ? contextPackLinks(root, Array.isArray(objects) ? objects : []) : []), + [root, objects, catalog], + ); + const entries = entriesOf(value); + const maxLists = maxItemsOf(schema); + const maxColumns = maxItemsOf(schema?.items?.properties?.fields); + const offered = links.filter((l) => !entries.some((e) => entryNamesLink(e, l))); + const full = maxLists !== undefined && entries.length >= maxLists; + + const write = (next: unknown[]) => onChange(next.length > 0 ? next : undefined); + const add = (key: string) => { + const link = links.find((l) => linkKey(l) === key); + if (!link || full) return; + write([...entries, { object: link.object, field: link.field }]); + }; + const replaceAt = (i: number, entry: ContextPackRelatedEntry) => { + const next = entries.slice(); + next[i] = entry; + write(next); + }; + const removeAt = (i: number) => { + const next = entries.slice(); + next.splice(i, 1); + write(next); + }; + + const placeholder = !root + ? t('engine.form.contextPack.chooseRootFirst', locale) + : catalog === 'loading' + ? t('engine.form.loadingOptions', locale) + : catalog === 'error' + ? t('engine.form.optionsLoadFailedTitle', locale) + : full + ? tFormat('engine.form.contextPack.listsFull', locale, { max: String(maxLists) }) + : links.length === 0 + ? t('engine.form.contextPack.noLinks', locale) + : offered.length === 0 + ? t('engine.form.contextPack.allListed', locale) + : t('engine.form.contextPack.addList', locale); + + return ( +
+ {catalog === 'error' && ( +
+
{t('engine.form.optionsLoadFailedTitle', locale)}
+

{t('engine.form.optionsLoadFailedDesc', locale)}

+
+ )} + {entries.map((raw, i) => { + if (!isPackEntry(raw)) { + // Not a pack entry at all: kept as stored, removable, judged at save. + return ( +
+ {JSON.stringify(raw)} + {!readOnly && ( + + )} +
+ ); + } + const link = resolvedLink(raw, links); + return ( +
+
+ + {link?.objectLabel ?? raw.object} + {raw.object} + {link ? ( + + {tFormat('engine.form.contextPack.via', locale, { field: link.fieldLabel })} + + ) : catalog !== 'ready' ? null : ( + + {t('engine.form.contextPack.notLinked', locale)} + + )} + + {!readOnly && ( + + )} +
+ replaceAt(i, next)} + /> +
+ ); + })} + {/* The block's primary control, rendered in every state (disabled when it + cannot add) so the host's label always names a labelable element. */} + +
+ ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx index cd3033f2d1f..f8fbbf345ca 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.tsx @@ -2711,6 +2711,42 @@ function summariseComposite(obj: Record, specs: FormFieldSpec[] return parts.join(' · '); } +/** + * The composite's next value after one sub-field's change (objectstack#37143). + * A cleared sub-field (`undefined` or `''`) drops its key, as `setField` does at + * the top level; and a composite left empty while its schema requires a key + * that has NO default is no value at all, so it is removed rather than written + * as `{}` or `{ field: '' }` (a context pack's `body` after "None"), which the + * save door refuses with no way back in the form. + * + * ⚠️ Only a required key without a `default` counts. `/meta/types` serves the + * OUTPUT derivation, where a key with `.default()` is listed as required; `{}` + * is legal there and the key's presence is read (a view's `pagination: {}` is + * the pager at its default size, `selection: {}` the default selection), so + * such a composite keeps `{}`. + */ +export function compositeWith( + obj: Record, + key: string, + v: unknown, + schema: JsonSchema | undefined, +): Record | undefined { + const next: Record = { ...obj, [key]: v }; + if (v === undefined || v === '') delete next[key]; + if (Object.keys(next).length === 0 && emptyObjectRefused(schema)) return undefined; + return next; +} + +/** True when an object node refuses `{}`: a required key whose property node carries no `default`. */ +export function emptyObjectRefused(schema: JsonSchema | undefined): boolean { + const required = Array.isArray(schema?.required) ? (schema!.required as unknown[]) : []; + const props = (schema?.properties ?? {}) as Record; + return required.some((k) => { + const node = typeof k === 'string' ? props[k] : undefined; + return !(node && typeof node === 'object' && 'default' in (node as object)); + }); +} + function CompositeField({ value, fields, @@ -2758,7 +2794,7 @@ function CompositeField({ fieldSpec={spec} widgetContext={widgetContext} formData={obj} - onChange={(v) => onChange({ ...obj, [spec.field]: v })} + onChange={(v) => onChange(compositeWith(obj, spec.field, v, schema))} /> ); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts index 60bede55bc6..10a5127ab05 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts @@ -704,6 +704,18 @@ export const ZH_CN_SPEC_FORMS: NonNullable = { 'triggerConditions.value': { label: '值' }, }, }, + ai_context: { + label: 'AI 上下文包', + fields: { + name: { label: '名称' }, + label: { label: '显示名称' }, + object: { label: '根对象' }, + fields: { label: '字段' }, + related: { label: '关联列表' }, + body: { label: '正文' }, + 'body.field': { label: '正文字段' }, + }, + }, flow: { label: '流程', fields: { diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index 3e4ce379606..71e8293c608 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -68,6 +68,7 @@ import { datasetSelectOptions } from './inspectors/dataset-picker-options.js'; import type { DatasetCatalogEntry } from './previews/useDatasetCatalog.js'; import { useMonacoFallback } from './useMonacoFallback.js'; import { DraftChip } from '../studio-design/StudioDraftMark.js'; +import { ContextPackRelatedEntries, isContextPackEntrySchema } from './ContextPackRelatedEntries.js'; import { type LoadState, isLoading, @@ -1766,7 +1767,31 @@ function relatedListEntryChipName(entry: unknown): string | undefined { * chip shows its title and columns beside the name. Those are edited in * Studio's object settings (Record page tabs), which reads the relationships. */ -function RelatedListEntriesWidget({ +function RelatedListEntriesWidget(props: WidgetProps) { + // objectstack#37143 — the same block edits a context pack's `related` + // (`{ object, field?, fields? }` entries, ADR-0160 D1). Told apart by the + // entry schema it is handed, never by the type's name; the pack's root is + // the row its `dependsOn` names (`object`). + const { schema, fieldSpec, formData } = props; + if (isContextPackEntrySchema(schema)) { + const dep = (Array.isArray(fieldSpec?.dependsOn) ? fieldSpec!.dependsOn![0] : fieldSpec?.dependsOn) || 'object'; + const rootValue = formData?.[dep]; + return ( + + ); + } + return ; +} + +/** The object form's `relatedLists` face: names and `{ list, … }` entries as chips. */ +function RelatedListNameEntries({ id, ariaLabelledBy, required, @@ -2181,13 +2206,19 @@ function ViewRefWidget({ id, ariaLabelledBy, required, value, onChange, readOnly ); } +/** True when the array's JSON Schema refuses an empty array (`minItems` of 1 or more). */ +export function emptyArrayRefused(schema: unknown): boolean { + const min = (schema as { minItems?: unknown } | undefined)?.minItems; + return typeof min === 'number' && min >= 1; +} + /** * Ordered multi object-field picker. Used for props that reference a list of * fields (kanban card `columns`, gallery `visibleFields`, chart * `yAxisFields`, `searchableFields`, …). Preserves order; supports reorder * and removal; values outside the catalog are retained. */ -function FieldRefMultiWidget({ value, onChange, readOnly, context, ariaLabelledBy, copilotAdded }: WidgetProps) { +function FieldRefMultiWidget({ value, onChange, readOnly, context, ariaLabelledBy, copilotAdded, schema }: WidgetProps) { const locale = useMetadataLocale(); const fieldsState = context?.objectFields ?? NOT_ASKED; // objectui#5228 — the failure is decided here, before the catalog is read: @@ -2211,7 +2242,10 @@ function FieldRefMultiWidget({ value, onChange, readOnly, context, ariaLabelledB const removeAt = (i: number) => { const next = selected.slice(); next.splice(i, 1); - onChange(next); + // objectstack#37143 — an array its schema bounds below (`minItems: 1`, a + // context pack's `fields`) has no empty value: removing the last chip + // removes the key, never writes `[]` the save door refuses. + onChange(next.length === 0 && emptyArrayRefused(schema) ? undefined : next); }; const move = (i: number, dir: -1 | 1) => { const j = i + dir; diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index a7511184640..f335a94f0de 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1834,6 +1834,21 @@ const STUDIO_EN: Record = { 'engine.form.addFieldPlain': 'Add field', 'engine.form.searchFields': 'Search fields…', 'engine.form.allFieldsAdded': 'All fields added', + // objectstack#37143 — a context pack's related lists (the `related-list-entries` + // block under `ai_context`): the add picker, one entry's link and columns. + // `{max}` is the schema's bound, `{field}` a reference field's label, `{list}` + // the child object's name. + 'engine.form.contextPack.addList': 'Add related list…', + 'engine.form.contextPack.chooseRootFirst': 'Choose the root object first', + 'engine.form.contextPack.noLinks': 'No object has a reference field that points at the root object', + 'engine.form.contextPack.allListed': 'Every related list is added', + 'engine.form.contextPack.listsFull': 'A pack reads at most {max} related lists', + 'engine.form.contextPack.via': 'via {field}', + 'engine.form.contextPack.notLinked': 'No reference field to the root: reported when saved', + 'engine.form.contextPack.columnsDefault': 'No columns: each row is read by its name.', + 'engine.form.contextPack.addColumn': 'Add column…', + 'engine.form.contextPack.addColumnTo': 'Add a column to {list}', + 'engine.form.contextPack.columnsFull': 'A related list reads at most {max} columns', // objectui#12126 — the `ref-multi:permission` picker's add control: its // accessible name, its placeholder, and the placeholder once every declared // permission set is picked. diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index dc375195bce..c518bc540dc 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1628,6 +1628,18 @@ const STUDIO_ZH: Record = { 'engine.form.addFieldPlain': '添加字段', 'engine.form.searchFields': '搜索字段…', 'engine.form.allFieldsAdded': '已添加全部字段', + // objectstack#37143 — 资料包的关联列表(`ai_context` 下的 `related-list-entries`)。 + 'engine.form.contextPack.addList': '添加关联列表…', + 'engine.form.contextPack.chooseRootFirst': '请先选择根对象', + 'engine.form.contextPack.noLinks': '没有对象的引用字段指向根对象', + 'engine.form.contextPack.allListed': '关联列表已全部添加', + 'engine.form.contextPack.listsFull': '一个资料包最多读取 {max} 个关联列表', + 'engine.form.contextPack.via': '经由 {field}', + 'engine.form.contextPack.notLinked': '没有指向根对象的引用字段:保存时会报告', + 'engine.form.contextPack.columnsDefault': '未选列:每行只读取其名称。', + 'engine.form.contextPack.addColumn': '添加列…', + 'engine.form.contextPack.addColumnTo': '为 {list} 添加列', + 'engine.form.contextPack.columnsFull': '一个关联列表最多读取 {max} 列', // objectui#12126 — zh half of the `ref-multi:permission` add control. 'engine.form.addPermissionSetPlain': '添加权限集', 'engine.form.addPermissionSet': '添加权限集…',