diff --git a/.changeset/38692-studio-retrieval-mode-picker.md b/.changeset/38692-studio-retrieval-mode-picker.md new file mode 100644 index 00000000000..8408ce427d8 --- /dev/null +++ b/.changeset/38692-studio-retrieval-mode-picker.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(studio): a knowledge source's retrieval-mode picker offers the modes its store runs + +Clause-②: no +Metadata-protocol: none + +The `source.retrieval.mode` row of the knowledge source form names a new picker, `knowledge-retrieval-mode`. Studio reads the source's store (the one its `adapter` names, else the deployment's) and its modes from the knowledge service's `index_status` answer, offers those modes, and names which mode the blank choice means ("Store default (Hybrid (both))"). A store that reports no modes, such as memory, is said to declare none ("驱动未声明检索方式"), and a mode already written there is kept and flagged. When the store's modes cannot be read (an author who is not a platform administrator, a store not mounted), the picker offers the three modes and the save judges the choice, as before. diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index 75a86d7d7df..9ddb111cf74 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -25,8 +25,14 @@ import { defineMetadataForm } from '../ui/view.zod'; * - `source.affinity` is the JSON editor too: a list of `{ field, caller, * mode, places? }` entries whose cross-key rules (a `field` listed in * `metadataFields`, `places` on a `boost` alone) no list widget states. - * - `source.retrieval.mode` is a select of the three modes, blank for the - * store's default; which modes the store runs is judged at save. + * - `source.retrieval.mode` is the `knowledge-retrieval-mode` picker: Studio + * offers the modes the source's store runs and names its default, or says + * the store declares none. A host whose widget registry lacks that picker + * draws its unregistered-widget face for this row (the JSON editor with its + * notice), not a select: the hint is read before `options`. The three + * `options` stay because the form's generated translations carry their + * labels; no renderer reads them while the hint is set. Which modes the + * store runs is judged at save either way. * * ADR-0161 K5 and K10 rule 5: embedding is egress, so `content` offers named * fields only, and its help says beside it what a build sends and to whom. @@ -88,6 +94,7 @@ export const knowledgeSourceForm = defineMetadataForm({ { field: 'mode', label: 'Retrieval mode', + widget: 'knowledge-retrieval-mode', options: [ { label: 'Vector only (by meaning)', value: 'vector' }, { label: 'Keyword only (by words)', value: 'keyword' }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/KnowledgeRetrievalModeWidget-38692.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/KnowledgeRetrievalModeWidget-38692.test.tsx new file mode 100644 index 00000000000..3269d17b7ba --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/KnowledgeRetrievalModeWidget-38692.test.tsx @@ -0,0 +1,185 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#38692 phase 1a: a knowledge source's `source.retrieval.mode` + * row names the `knowledge-retrieval-mode` picker. It offers the modes the + * source's store runs and names the store's default; a store that reports no + * modes is said to declare none ("驱动未声明"); without the store's answer the + * three modes are offered and the save judges the choice. + */ + +// 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, beforeAll } from 'vitest'; +import { render, screen, fireEvent, cleanup } from '@testing-library/react'; +import { knowledgeSourceForm } from '@objectstack/spec/ai'; +import { WIDGETS, WIDGET_LABELLING, type WidgetContext } from './widgets'; +import { storeRetrievalOf, type KnowledgeStoreRetrieval } from './knowledgeRetrieval'; + +afterEach(cleanup); + +beforeAll(() => { + // Radix Select reads pointer capture and scrolls the open item into view; jsdom has neither. + for (const m of ['hasPointerCapture', 'setPointerCapture', 'releasePointerCapture'] as const) { + if (!(m in Element.prototype)) { + (Element.prototype as unknown as Record)[m] = m === 'hasPointerCapture' ? () => false : () => {}; + } + } + if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = () => {}; +}); + +const Picker = WIDGETS['knowledge-retrieval-mode']; + +function contextOf(store: KnowledgeStoreRetrieval | 'loading' | 'error'): WidgetContext { + return { + conditionScope: 'none', + knowledgeRetrieval: + store === 'loading' + ? { status: 'loading' } + : store === 'error' + ? { status: 'error', message: 'index_status answered 403' } + : { status: 'loaded', data: store }, + }; +} + +function open() { + fireEvent.pointerDown(screen.getByTestId('knowledge-retrieval-mode'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); +} + +const optionNames = () => screen.getAllByRole('option').map((o) => o.textContent); + +describe('the published retrieval-mode row (objectstack#38692)', () => { + it('names the picker, under source.retrieval', () => { + type Row = { field?: string; widget?: string; fields?: Row[] }; + const found: Array<{ path: string; widget?: string }> = []; + const walk = (list: Row[] | undefined, path: string) => { + for (const row of list ?? []) { + const at = path ? `${path}.${row.field}` : String(row.field); + if (row.widget === 'knowledge-retrieval-mode') found.push({ path: at, widget: row.widget }); + walk(row.fields, at); + } + }; + for (const section of (knowledgeSourceForm as { sections?: Array<{ fields?: Row[] }> }).sections ?? []) walk(section.fields, ''); + expect(found).toEqual([{ path: 'source.retrieval.mode', widget: 'knowledge-retrieval-mode' }]); + }); + + it('declares control labelling, so the host label names the trigger', () => { + expect(WIDGET_LABELLING['knowledge-retrieval-mode']).toBe('control'); + }); +}); + +describe('knowledge-retrieval-mode widget (objectstack#38692)', () => { + const turso: KnowledgeStoreRetrieval = { adapter: 'turso', mounted: true, modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }; + + it("offers the store's modes, and names which one its default is", async () => { + render( {}} schema={{}} context={contextOf(turso)} />); + expect(screen.getByTestId('knowledge-retrieval-mode')).toHaveTextContent('Store default (Hybrid (both))'); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual([ + 'Store default (Hybrid (both))', + 'Vector only (by meaning)', + 'Keyword only (by words)', + 'Hybrid (both)', + ]); + }); + + it('offers only the modes a store lists', async () => { + render( + {}} + schema={{}} + context={contextOf({ adapter: 'vec', mounted: true, modes: ['vector'], default: 'vector' })} + />, + ); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual(['Store default (Vector only (by meaning))', 'Vector only (by meaning)']); + }); + + it('a store that reports no modes: the default alone, and the sentence that it declares none', async () => { + render( {}} schema={{}} context={contextOf({ adapter: 'memory', mounted: true })} />); + expect(screen.getByTestId('knowledge-retrieval-mode-undeclared')).toHaveTextContent( + 'The store memory declares no retrieval modes, so leave this blank.', + ); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual(['Store default']); + }); + + it('a stored mode the store does not run is kept as its own option, flagged', async () => { + render( {}} schema={{}} context={contextOf({ adapter: 'memory', mounted: true })} />); + expect(screen.getByTestId('knowledge-retrieval-mode')).toHaveTextContent('Keyword only (by words) (this store does not run it)'); + }); + + it('without the store answer (refused read, unmounted store, no host): the three modes', async () => { + for (const context of [contextOf('error'), contextOf({ adapter: 'pgvector', mounted: false }), undefined]) { + render( {}} schema={{}} context={context} />); + expect(screen.queryByTestId('knowledge-retrieval-mode-undeclared')).toBeNull(); + open(); + await screen.findAllByRole('option'); + expect(optionNames()).toEqual(['Store default', 'Vector only (by meaning)', 'Keyword only (by words)', 'Hybrid (both)']); + cleanup(); + } + }); + + it('a mode writes its name; the default removes the key', async () => { + const onChange = vi.fn(); + render(); + open(); + fireEvent.click(await screen.findByRole('option', { name: 'Keyword only (by words)' })); + expect(onChange).toHaveBeenLastCalledWith('keyword'); + cleanup(); + render(); + open(); + fireEvent.click(await screen.findByRole('option', { name: 'Store default (Hybrid (both))' })); + expect(onChange).toHaveBeenLastCalledWith(undefined); + }); + + it('is disabled while loading and read-only', () => { + render( {}} schema={{}} context={contextOf('loading')} />); + expect(screen.getByDisplayValue('vector')).toBeDisabled(); + cleanup(); + render( {}} schema={{}} readOnly context={contextOf(turso)} />); + expect(screen.getByTestId('knowledge-retrieval-mode')).toBeDisabled(); + }); +}); + +describe('storeRetrievalOf — the store a source binds to, from an index_status answer', () => { + const body = { + success: true, + data: { + ok: true, + details: { + sources: [], + adapters: [ + { id: 'turso', retrieval: { modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' } }, + { id: 'memory' }, + ], + defaultAdapter: 'turso', + }, + }, + }; + + it("the named store, else the deployment's", () => { + expect(storeRetrievalOf(body, 'memory')).toEqual({ adapter: 'memory', mounted: true }); + expect(storeRetrievalOf(body, undefined)).toEqual({ + adapter: 'turso', + mounted: true, + modes: ['vector', 'keyword', 'hybrid'], + default: 'hybrid', + }); + }); + + it('a store not mounted, or none placed, is not mounted', () => { + expect(storeRetrievalOf(body, 'pgvector')).toEqual({ adapter: 'pgvector', mounted: false }); + const unplaced = { success: true, data: { details: { adapters: [] } } }; + expect(storeRetrievalOf(unplaced, undefined)).toEqual({ mounted: false }); + }); + + it('a body with no list of stores is a failed read, never an empty one', () => { + expect(() => storeRetrievalOf({ success: true, data: { details: {} } }, undefined)).toThrow(/no list of stores/); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index 448ab7027ed..7b217ee0ab5 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -111,6 +111,7 @@ import { conditionSubjectsForMetadataType, } from './conditionScope.js'; import { mapLoaded, usePickerLoad } from './loadState.js'; +import { fetchStoreRetrieval, type KnowledgeStoreRetrieval } from './knowledgeRetrieval.js'; import { useCapabilityAudienceLoader } from './useCapabilityAudienceLoader.js'; import { useMetadataClient, @@ -1409,6 +1410,26 @@ function MetadataResourceEditPageImpl({ ), ); + // objectstack#38692 phase 1a — the store a knowledge source binds to (the + // one its `adapter` names, else the deployment's) and the retrieval modes it + // runs, for the `knowledge-retrieval-mode` picker. Loaded only when the form + // on screen declares that widget, and again when the source names another + // store. + const declaresRetrievalMode = formDeclaresWidget( + createMode && config.createSchema ? undefined : entry?.form, + 'knowledge-retrieval-mode', + ); + const draftAdapter = + typeof (draft as { adapter?: unknown } | null)?.adapter === 'string' && (draft as { adapter: string }).adapter.trim() + ? (draft as { adapter: string }).adapter.trim() + : undefined; + const knowledgeRetrievalState = usePickerLoad( + React.useMemo( + () => (declaresRetrievalMode ? () => fetchStoreRetrieval(draftAdapter) : null), + [declaresRetrievalMode, draftAdapter], + ), + ); + // objectstack#34908 — the audience catalog for the `ref-multi:capability` // picker (a list view's or a dashboard's `requiredPermissions`): the // capabilities the environment knows, the permission sets granting each and @@ -1476,8 +1497,18 @@ function MetadataResourceEditPageImpl({ componentIds, permissionSets: permissionSetsState, loadCapabilityAudience, + knowledgeRetrieval: knowledgeRetrievalState, }), - [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState, loadCapabilityAudience], + [ + type, + objectsState, + objectCatalogState, + objectViewsState, + componentIds, + permissionSetsState, + loadCapabilityAudience, + knowledgeRetrievalState, + ], ); // Load layered view + initial draft. diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx index e527aaf8f3d..5b8ca7d9c2e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx @@ -110,6 +110,7 @@ const CONTROL_CASES: WidgetCase[] = [ { widget: 'related-list-entries', control: (c) => c.querySelector('input[type="text"]'), faceName: 'the related-list entry box' }, { widget: 'secret', control: (c) => c.querySelector('input[type="password"]'), faceName: 'the masked credential box' }, { widget: 'field-history', control: (c) => c.querySelector('[role="combobox"]'), faceName: 'the Default / On / Off picker' }, + { widget: 'knowledge-retrieval-mode', control: (c) => c.querySelector('[role="combobox"]'), faceName: 'the retrieval-mode picker' }, ]; /** diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx index d344ccc1f26..eb887e3587b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx @@ -181,6 +181,7 @@ const CASES: Case[] = [ { key: 'code', schema: { type: 'string', title: TITLE }, spec: { language: 'javascript' }, value: 'x = 1' }, { key: 'secret', schema: { type: 'string', title: TITLE }, value: 's3cr3t' }, { key: 'field-history', schema: { type: 'boolean', title: TITLE }, formData: { type: 'json' }, value: false }, + { key: 'knowledge-retrieval-mode', schema: { type: 'string', title: TITLE, enum: ['vector', 'keyword', 'hybrid'] }, value: 'keyword' }, { key: 'dynamic-config', schema: { type: 'object', title: TITLE }, spec: { dependsOn: 'driver' }, formData: { driver: 'pg' }, ctx: { dynamicSchemas: { pg: { properties: { host: { type: 'string' } } } } }, value: {} }, { key: 'dynamic-config', variant: 'unconfigured', schema: { type: 'object', title: TITLE }, spec: { dependsOn: 'driver' }, formData: { driver: '' }, value: {} }, ]; diff --git a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx index bd5cc505e1c..fd68b811bcc 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx @@ -109,6 +109,7 @@ const FAILED_CTX: WidgetContext = { objectViews: failed('views: HTTP 503'), objectActions: failed('actions: HTTP 503'), datasets: failed('datasets: HTTP 503'), + knowledgeRetrieval: failed('index_status: HTTP 403'), }; const LOADED_CTX: WidgetContext = { @@ -118,6 +119,7 @@ const LOADED_CTX: WidgetContext = { objectViews: loaded([{ name: 'account.all', label: 'All' }]), objectActions: loaded([{ name: 'approve' }]), datasets: loaded([{ name: 'sales_metrics', label: 'Sales metrics', dimensions: [], measures: [] }]), + knowledgeRetrieval: loaded({ adapter: 'turso', mounted: true, modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }), }; interface ControlCase { @@ -170,6 +172,8 @@ const CASES: ControlCase[] = [ { key: 'secret', schema: { type: 'string' }, value: 's3cr3t', banner: null }, // No catalog: the one face is the trigger, on every arm. { key: 'field-history', schema: { type: 'boolean' }, value: false, banner: null }, + // A refused store read offers the three modes and lets the save judge: no block. + { key: 'knowledge-retrieval-mode', schema: { type: 'string' }, value: 'keyword', banner: null }, ]; /** diff --git a/ui/packages/app-shell/src/views/metadata-admin/knowledgeRetrieval.ts b/ui/packages/app-shell/src/views/metadata-admin/knowledgeRetrieval.ts new file mode 100644 index 00000000000..2da93bdd350 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/knowledgeRetrieval.ts @@ -0,0 +1,84 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The retrieval modes a knowledge source's store runs, for the Studio form's + * `source.retrieval.mode` picker (objectstack#38692 phase 1a). + * + * The knowledge service answers them on its `index_status` settings action + * (`POST /api/settings/knowledge/index_status`): each mounted store's modes and + * default (`details.adapters`), and the store a source that names none binds + * to (`details.defaultAdapter`). The source on screen binds to the store its + * `adapter` names, else that one. A store that reports no modes (memory) takes + * only a source that leaves the mode out; the picker says so rather than + * offering a mode its save would refuse. + * + * The action is gated on the settings namespace's write permission, so an + * author who is not a platform administrator is refused the read: the picker + * then offers the three modes and the save judges the choice, as before this + * reader existed. + */ + +import { bearerAuthHeaders } from '../../utils/authToken.js'; +import { createAuthenticatedFetch } from '@object-ui/auth'; + +/** The three modes the spec names (`KNOWLEDGE_RETRIEVAL_MODES`), in the form's order. */ +export const RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; +export type RetrievalMode = (typeof RETRIEVAL_MODES)[number]; + +/** The store a source binds to, and the modes it reports. */ +export interface KnowledgeStoreRetrieval { + /** The store's adapter id; absent when the source names none and none is placed. */ + adapter?: string; + /** Whether the service lists the store as mounted. */ + mounted: boolean; + /** The modes it runs; absent: it reports none ("驱动未声明"). */ + modes?: RetrievalMode[]; + /** Its default mode; absent with `modes`. */ + default?: RetrievalMode; +} + +interface IndexStatusDetails { + adapters?: Array<{ id?: unknown; retrieval?: { modes?: unknown; default?: unknown } }>; + defaultAdapter?: unknown; +} + +const isMode = (m: unknown): m is RetrievalMode => typeof m === 'string' && (RETRIEVAL_MODES as readonly string[]).includes(m); + +/** + * The store `adapter` (else the deployment's) and its modes, read from an + * `index_status` answer body (`{ success, data: { details } }`, or the bare + * result). A body that is not that shape throws, so the caller reads a failed + * load, never an empty one. + */ +export function storeRetrievalOf(body: unknown, adapter: string | undefined): KnowledgeStoreRetrieval { + const result = + body && typeof body === 'object' && (body as { success?: unknown }).success === true + ? (body as { data?: unknown }).data + : body; + const details = (result as { details?: IndexStatusDetails } | null | undefined)?.details; + if (!details || !Array.isArray(details.adapters)) { + throw new Error('the knowledge service answered no list of stores'); + } + const bound = adapter ?? (typeof details.defaultAdapter === 'string' ? details.defaultAdapter : undefined); + if (bound === undefined) return { mounted: false }; + const row = details.adapters.find((a) => a?.id === bound); + if (!row) return { adapter: bound, mounted: false }; + const report = row.retrieval; + const modes = Array.isArray(report?.modes) ? report.modes.filter(isMode) : undefined; + if (!modes || modes.length === 0 || !isMode(report?.default)) return { adapter: bound, mounted: true }; + return { adapter: bound, mounted: true, modes, default: report.default }; +} + +const serverUrl = (): string => (import.meta.env?.VITE_SERVER_URL || '').replace(/\/$/, ''); + +/** Read the store `adapter` (else the deployment's) binds to, and its modes. */ +export async function fetchStoreRetrieval(adapter: string | undefined): Promise { + const res = await createAuthenticatedFetch()(`${serverUrl()}/api/settings/knowledge/index_status`, { + method: 'POST', + credentials: 'include', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...bearerAuthHeaders() }, + body: '{}', + }); + if (!res.ok) throw new Error(`index_status answered ${res.status}`); + return storeRetrievalOf(await res.json(), adapter); +} 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 e40a417842f..0c25b04b66a 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 { expressionSource, writeExpressionSource } from './inspectors/expression import { humanizeKey } from './inspectors/json-schema-to-fields.js'; import { datasetSelectOptions } from './inspectors/dataset-picker-options.js'; import type { DatasetCatalogEntry } from './previews/useDatasetCatalog.js'; +import { RETRIEVAL_MODES, type KnowledgeStoreRetrieval } from './knowledgeRetrieval.js'; import { useMonacoFallback } from './useMonacoFallback.js'; import { DraftChip } from '../studio-design/StudioDraftMark.js'; import { ContextPackRelatedEntries, isContextPackEntrySchema } from './ContextPackRelatedEntries.js'; @@ -341,6 +342,14 @@ export interface WidgetContext { * every render. */ loadCapabilityAudience?: () => Promise; + /** + * objectstack#38692 phase 1a — the store the knowledge source on screen binds + * to and the retrieval modes it reports, for the `knowledge-retrieval-mode` + * picker (`knowledgeRetrieval.ts`). `ResourceEditPage` loads it only for a + * form that declares the hint. Absent reads as {@link NOT_ASKED}: the picker + * offers the three modes. + */ + knowledgeRetrieval?: LoadState; } /* Stable empties for the arms that have no catalog to offer yet — `idle` and @@ -843,6 +852,87 @@ function RefDatasetWidget({ id, ariaLabelledBy, required, value, onChange, readO ); } +/* -------------------------------------------------------------------------- */ +/* knowledge-retrieval-mode — a knowledge source's `source.retrieval.mode` */ +/* -------------------------------------------------------------------------- */ + +/** The Select's value for "no mode": Radix refuses an empty-string item. */ +const STORE_DEFAULT = '__store_default__'; + +/** + * The retrieval-mode picker of a knowledge source (objectstack#38692 phase + * 1a). It offers the modes the source's store runs, read from + * `context.knowledgeRetrieval`, and a blank choice that names the store's + * default ("Store default (hybrid)"); the value written is the mode, or + * `undefined` for the default. + * + * - LOADED, the store reports modes — those, in the order it reports them; + * - LOADED, the store reports none (memory) — the default alone, and the + * sentence that the store declares no modes; a mode already written is kept + * as its own option, flagged, so the author sees what the save will refuse; + * - LOADED, the store is not mounted, or the read was refused or failed, or + * no host feeds it — the three modes, and the save judges the choice; + * - LOADING — the stored mode in a disabled control. + */ +function KnowledgeRetrievalModeWidget({ id, ariaLabelledBy, required, value, onChange, readOnly, context }: WidgetProps) { + const locale = useMetadataLocale(); + const state = context?.knowledgeRetrieval ?? NOT_ASKED; + const current = typeof value === 'string' && value ? value : ''; + if (isLoading(state)) { + return ( + + ); + } + const store = state.status === 'loaded' && state.data.mounted ? state.data : undefined; + const undeclared = store !== undefined && store.modes === undefined; + const offered: readonly string[] = undeclared ? [] : (store?.modes ?? RETRIEVAL_MODES); + const modeLabel = (mode: string) => t(`engine.form.retrievalMode.${mode}`, locale); + const defaultLabel = + store?.default !== undefined + ? tFormat('engine.form.retrievalMode.defaultIs', locale, { mode: modeLabel(store.default) }) + : t('engine.form.retrievalMode.default', locale); + const kept = current !== '' && !offered.includes(current); + return ( +
+ + {undeclared && ( +

+ {tFormat('engine.form.retrievalMode.undeclared', locale, { store: store?.adapter ?? '' })} +

+ )} +
+ ); +} + /* -------------------------------------------------------------------------- */ /* ref-multi: — pick declared registry items by name, as a list */ /* -------------------------------------------------------------------------- */ @@ -3820,6 +3910,7 @@ export const WIDGETS = { 'secret': SecretWidget, 'dynamic-config': DynamicConfigWidget, 'field-history': FieldHistoryWidget, + 'knowledge-retrieval-mode': KnowledgeRetrievalModeWidget, } satisfies Record; /** Every key of {@link WIDGETS}, as a literal union. */ @@ -3935,6 +4026,7 @@ export const WIDGET_LABELLING: Record = { 'secret': 'control', 'dynamic-config': 'group', 'field-history': 'control', + 'knowledge-retrieval-mode': 'control', }; /** diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index cf146df04cf..66a931a27c0 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1813,6 +1813,13 @@ const STUDIO_EN: Record = { 'engine.form.invalid': '(invalid)', 'engine.form.notPublished': '(not published)', 'engine.form.flaggedValue': '{value} {flag}', + 'engine.form.retrievalMode.vector': 'Vector only (by meaning)', + 'engine.form.retrievalMode.keyword': 'Keyword only (by words)', + 'engine.form.retrievalMode.hybrid': 'Hybrid (both)', + 'engine.form.retrievalMode.default': 'Store default', + 'engine.form.retrievalMode.defaultIs': 'Store default ({mode})', + 'engine.form.retrievalMode.notRun': '(this store does not run it)', + 'engine.form.retrievalMode.undeclared': 'The store {store} declares no retrieval modes, so leave this blank.', 'engine.form.searchIcons': 'Search icons…', 'engine.form.chooseIcon': 'Choose an icon', // objectstack#35985: the object colour palette in the icon picker. diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index e675999afee..b759c452128 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1608,6 +1608,13 @@ const STUDIO_ZH: Record = { 'engine.form.invalid': '(无效)', 'engine.form.notPublished': '(未发布)', 'engine.form.flaggedValue': '{value}{flag}', + 'engine.form.retrievalMode.vector': '仅向量(按意思)', + 'engine.form.retrievalMode.keyword': '仅关键词(按字词)', + 'engine.form.retrievalMode.hybrid': '混合(两者都用)', + 'engine.form.retrievalMode.default': '存储默认', + 'engine.form.retrievalMode.defaultIs': '存储默认({mode})', + 'engine.form.retrievalMode.notRun': '(此存储不支持)', + 'engine.form.retrievalMode.undeclared': '驱动未声明检索方式({store}),此项请留空。', 'engine.form.searchIcons': '搜索图标…', 'engine.form.chooseIcon': '选择图标', // objectstack#35985: the object colour palette in the icon picker.