Skip to content

Commit a73edb3

Browse files
fix(settings)!: offer the knowledge settings only where the knowledge service is mounted (#36975)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8S6QzYsi5mhv88KLVu7efbx)_ Fixes #33933 Supersedes #34223: the same change, carried to a branch this session can push, with `origin/main` merged in (two conflicts resolved, one new pin adjusted; see Verification). Its earlier park on objectstack-ai/cloud#4569 is lifted by reading, not by that card: claim comment 7131785382 on #33933. Clause-②: no (narrowing) — on a deployment that does not mount `KnowledgeServicePlugin` (every stock boot), `GET` / `PUT /api/settings/knowledge` and `POST /api/settings/knowledge/test` answer `404 UNKNOWN_NAMESPACE`; a write of an `ai.embedder_*` key answers `400 UNKNOWN_KEY`; `POST /api/settings/ai/test_embedder` answers `400 SETTINGS_ACTION_FAILED` (no handler registered); the hub list drops `knowledge` and the Setup sidebar drops `nav_settings_knowledge`. Metadata-protocol: none Skills-docs: none — no skill under `skills/**` teaches the knowledge settings page or the `ai.embedder_*` keys; `skills/objectstack-ai` teaches wiring `KnowledgeServicePlugin`, which is unchanged. **BREAKING** for a deployment that does not mount the knowledge service: the Knowledge page, the AI page's Embedder section, their two test buttons and the Setup entry are no longer offered by default. They come back, unchanged, when `KnowledgeServicePlugin` is mounted beside `SettingsServicePlugin`. Stored `knowledge.*` / `ai.embedder_*` rows are untouched. The changeset carries the ADR-0087 not-required marker (no-migration-prescription). ## 维护者速读 - 改了什么:知识库设置页、AI 页的「Embedder」分区、两个测试按钮和 Setup 菜单项,改为只在挂载知识库服务时出现;默认部署不再显示。 - 为什么改:知识库不是默认能力,以前每个部署都显示一个背后没有服务的知识库页面和测试按钮,误导管理员。 - 风险与回滚:未挂载知识库服务的部署,这些设置接口改为返回 404 / 400;已存的值仍在库里,挂载服务后照常回来。回滚即还原本 PR。 - 先看:`packages/services/service-knowledge/src/knowledge-settings-contribution.ts`(注册逻辑,尤其 ai 分区只并入内置 ai 清单那段)、`packages/services/service-settings/src/manifests/ai.manifest.ts`(Embedder 分区拆出)、`packages/services/service-knowledge/src/knowledge-service-plugin.ts`(optionalDependencies 保证设置插件先初始化)。 - 两分钟验证:`pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-settings-contribution.test.ts`,预期 7 个用例全绿(挂载有、不挂载无)。 - 托管环境:已读 cloud `main` `16b444e`。托管的向量化器读不到 `ai.embedder_*` 时按「未配置」处理,不建、不报错;托管环境没有挂载知识库,也没有地方用向量化器。所以不再等 cloud#4569。 - 需要你做的:复核(L1 + L2 契约复核)通过后,批准合并。 ## What changes - `@objectstack/service-settings` - `builtinSettingsManifests` drops `knowledgeSettingsManifest` (10 → 9). - `aiSettingsManifest` drops its embedder section; the section is exported as `aiEmbedderSettingsSpecifiers`, with `withAiEmbedderSection(manifest)` to join it (idempotent). - The default `actionHandlers` map no longer registers `knowledge.test` or `ai.test_embedder`. - The package entry exports `knowledgeSettingsManifest`, `knowledgeTestActionHandler`, `aiSettingsManifest`, `aiEmbedderSettingsSpecifiers`, `withAiEmbedderSection`, `aiTestEmbedderActionHandler`. - `settings.ai.description` no longer names the knowledge base, in all 11 bundled locales. - `@objectstack/service-knowledge` - New `contributeKnowledgeSettings(ctx, version)`, called from `KnowledgeServicePlugin.init()`. It registers the `knowledge` manifest and `knowledge.test`, and joins the embedder section plus `ai.test_embedder` to the `ai` namespace. It joins them only when the served `ai` page is the bundled one, or already declares the embedder keys. A host's own `ai` manifest is left untouched, and the plugin logs a warning saying why. It also registers the `nav_settings_knowledge` Setup entry as a `navigationContributions` bundle through the `manifest` service. - The embedder section joins only the bundled `ai` page, recognised as that very declaration object (`isBundledAiManifest`). A host `ai` page that differs in any way (scope, permission, default, option table), or one served through an option source, is left as registered and the plugin logs a warning. - `optionalDependencies` names `com.objectstack.service.settings` (literal, ADR-0116), so "no settings service" at init is a fact of the composition. - Depends on `@objectstack/service-settings`; devDependency `@objectstack/platform-objects` for the merged-Setup-tree test. - `@objectstack/platform-objects`: the static `nav_settings_knowledge` entry leaves `SETUP_NAV_CONTRIBUTIONS`. Its label stays keyed in the Setup bundles. - `docs/qa/platform-checklist/areas/platform-core.json`: `builtin-apps-nav-render` (rev 16) and `settings-hub-roundtrip` (rev 9) restated for 9 builtins and the knowledge page's new source. ## Tests - New `service-settings/src/knowledge-settings-default-absent.pin.test.ts` pins the default boot (8 cases, refusals by status + `error.code`): - no `knowledge` in the aggregate or the hub list; - `GET knowledge` answers 404 `UNKNOWN_NAMESPACE`; - no embedder key or button on the served `ai` page; - `PUT ai {embedder_provider}` answers 400 `UNKNOWN_KEY`; - `POST ai/test_embedder` answers 400 `SETTINGS_ACTION_FAILED`, judged against the hub's own no-handler answer, and `POST knowledge/test` answers 404 `UNKNOWN_NAMESPACE`; - no knowledge Setup entry; - no locale's AI description names the knowledge base. - New `service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts` uses a LiteKernel with `KnowledgeServicePlugin` deliberately `use`d BEFORE `SettingsServicePlugin`, against a bare control kernel (7 cases): - the namespace, the embedder keys and both actions are there with the service and absent without it. The actions are judged equal to their handler's own answer. - on the merged Setup tree (ObjectQL registry fold), `nav_settings_knowledge` appears exactly once with the service and never without it; - the two HTTP-door cases moved here from `settings-default-action-handlers.pin.test.ts`. - New `service-knowledge/src/__tests__/knowledge-settings-host-ai.test.ts` (7 cases, on a real `SettingsService`): the bundled page is joined; a page served through an option source is not; host pages with the bundled keys and a different scope, read permission, option table or default are left as the host's own object, with one warning; a host page that already declares the embedder keys keeps its declaration and gets the button handler; no settings service ⇒ nothing offered, no throw. Ablation: with the old key-set recognition put back, 3 of the host cases go red (scope, permission, default). - Updated: - `cloud-managed-settings.pin.test.ts` (landed on main after this PR was first written, #33891): `boot()` registers the `ai` manifest through `withAiEmbedderSection`, the page a knowledge-mounting deployment serves, and the key-classification case reads that joined page. The hosted projection is still judged over every key it hides, the embedder keys included. - `packages/cli/test/connect-agent-both-halves-wire.pin.test.ts`: main's count (37) less the knowledge entry, 36; the comment's history line extended. - `ai.manifest.test.ts`: the embedder describe reads the exported section; a joined-parse and idempotence case is added. - `settings-default-action-handlers.pin.test.ts`: the population excludes the two moved buttons. - `settings-visibility-declaration.pin.test.ts` and `settings-translation-coverage.test.ts`: the corpus keeps the knowledge declarations, so the measured 10 manifests and 90 predicates and the copy coverage still hold. ## Acceptance notes - Acceptance 3 (a mounting app): no app in this repository mounts `KnowledgeServicePlugin`. The test kernel above stands in for one, as ruled; `examples/app-todo` is unchanged. - **Hosted embedder: answered by reading cloud `main` `16b444e`.** `packages/service-ai/src/plugin.ts` `applyEmbedder` (L1785–1813) reads `settings.getNamespace('ai')`; with no `embedder_*` key declared, `buildEmbedderFromValues` (L576–577) reads the provider as `'none'` and returns `null`, so no embedder is built and nothing throws. Its `settings.registerAction('ai', 'test_embedder', …)` (L1818) does not throw either: `registerAction` refuses only an unknown namespace (`settings-service.ts` L1964–1968). No hosted runtime mounts `KnowledgeServicePlugin` or consumes `EMBEDDER_SERVICE` (only `packages/knowledge-turso`, which nothing mounts). The hosted hide list (`cloud-managed-settings.ts`, #33891) keeps the `embedder_*` keys and `test_embedder`, so a hosted runtime that later mounts the knowledge service still hides them. - **Cloud tests at the next framework pin move:** `packages/objectos-runtime/src/env-settings-door-namespace-coverage.test.ts` and `apps/cloud/test/settings-cross-org-doors.test.ts` still count `knowledge` in the default registry and go red at the pin move that first includes this PR; no hosted behaviour changes. Carried by objectstack-ai/cloud#4959 (`Blocked-by:` this PR). - **Accepted nits from the contract review (comments 7132371555, 7132488363, 7132537690):** N1, the AI page and its Setup entry keep the title "AI & Embedder" / 「AI 与向量化」 where no embedder section shows (the card asks only for the section and the description; a rename is the maintainer's pick). N3, the `@objectstack/embedder-openai` install hint left the AI page's description with the section. N6, on the option-source branch the warning says the page "is not the bundled one"; no composition reaches that branch. - The refusal codes at the HTTP door are `UNKNOWN_NAMESPACE` / `UNKNOWN_KEY` (the route envelope's spelling of the service's `UnknownNamespaceError` / `UnknownKeyError`). - Surface deviations, both required by the approved dependency: - `packages/services/service-settings/src/index.ts`: the package entry exports the six symbols listed under What changes. - `packages/services/service-knowledge/vitest.config.ts`: src aliases for `service-settings`, `types` and `platform-objects`, as `check:test-source-alias` requires. - The two corpus tests (`settings-visibility-declaration.pin.test.ts`, `settings-translation-coverage.test.ts`) were outside the listed files too. They are measurement pins over this package's declarations, updated so they keep measuring the same declarations. ## Verification All verify runs go through `scripts/pm/os-verify-lock.sh` and quote the lock's `VERDICT command-exit 0` line. <details open><summary>On this PR's final head 5023298</summary> Commits on this branch: #34223's head `ba9ec457d9`, a merge of `origin/main` `144d368eac` (`a0cf1e359b`), the hosted-projection pin adjustment (`8ac823aa64`), the contract review's S1/S2 fixes (`c654ad07b7`), and its S3 fix (`5023298063`). - Merge conflicts, both resolved by hand: - `docs/qa/platform-checklist/areas/platform-core.json`: main's revisions 17–19 of `builtin-apps-nav-render` kept; this change re-applied as revision 20 (10 namespaces; 46 Setup destinations, main's 47 less Knowledge). - `packages/cli/test/connect-agent-both-halves-wire.pin.test.ts`: main's 37 less Knowledge = 36; `SETUP_NAV_CONTRIBUTIONS` 29 → 28. - **Dogfood battery, full, on `5023298063`** (the PR checks do not run it: `ci.yml`'s dogfood job skips `pull_request` events, so it was run here). Closure built with `pnpm --filter '@objectstack/dogfood^...' build` (exit 0), then `pnpm --filter @objectstack/dogfood test` under the lock, no shard, no path: `VERDICT command-exit 0 · held the lock 2043s`; Test Files 487 passed, 3 skipped (490); Tests 4127 passed, 68 skipped (4195). An earlier full run on `c654ad07b7` read the same counts (`VERDICT command-exit 0 · held the lock 2604s`). - GitHub check-runs on `5023298063`: 61 success, 9 expected skip, 0 failed (read with `scripts/pm/pr-state.mjs --pr 36975`). - `@objectstack/service-settings` test: Test Files 77 passed (77), Tests 1523 passed (1523), on `8ac823aa64`; the later commits do not touch the package. - `@objectstack/service-knowledge` test on `5023298063`: Test Files 6 passed (6), Tests 64 passed (64); typecheck exit 0. - `@objectstack/service-settings` typecheck: exit 0. `@objectstack/cli` `test/connect-agent-both-halves-wire.pin.test.ts`: 2 passed. `@objectstack/plugin-auth`, the 5 files that read `builtinSettingsManifests`: Tests 133 passed (133). - `node scripts/check-platform-checklist.mjs --changed-from origin/main`: OK, 8 anchors judged, 0 lost. - Contract review at `CONTRACT_REVIEW_TIER`: PASS on `8ac823aa64` (comment 7132371555, S1 and S2 should-fix), PASS on `c654ad07b7` (7132488363, S1 and S2 closed, S3 should-fix), PASS on `5023298063` (7132537690, S3 closed, nits only). </details> Earlier readings on #34223's own heads, kept for the ablation record: <details><summary>Package tests and typecheck on the final head f27aef7</summary> - `@objectstack/service-settings` test: Test Files 76 passed (76), Tests 1484 passed (1484); typecheck exit 0. - `@objectstack/service-knowledge` test: Test Files 5 passed (5), Tests 56 passed (56); typecheck exit 0. - `@objectstack/platform-objects` test: Test Files 122 passed (122), Tests 2007 passed (2007). - Direct readers of the moved surface, at `334f6da447`: - `@objectstack/plugin-auth`: the 5 files that read `builtinSettingsManifests`, Tests 133 passed (133). - `@objectstack/spec`: `settings-manifest.test.ts`, Tests 86 passed (86). - `@objectstack/platform-objects` typecheck: exit 0. </details> <details><summary>Dogfood battery (narrowing): green at 1b210ee</summary> - Closure built with `pnpm --filter '@objectstack/dogfood^...' build` (exit 0). Then `pnpm --filter @objectstack/dogfood test` under the lock, with no shard and no path: Test Files 467 passed, 3 skipped (470); Tests 3962 passed, 42 skipped (4004); exit 0. - The only commit after that run is the merge of `origin/main`, which brings main's own commits; CI runs the battery on the merge. - An earlier attempt ran on a partial closure: the build stopped at `driver-turso`, because a dependency arrived with a merge before `pnpm install`. That run is discarded and is not counted. </details> <details><summary>Ablation of every pin (on-disk mutation via scripts/ablation-replace.mjs, WRAP restore, restore proven blob == HEAD and git diff HEAD empty)</summary> Tests are src-aliased, so no dist leg is needed. - A1, knowledge manifest back in `builtinSettingsManifests`: red, 5 failed. - Absent pin: aggregate/hub list, `GET knowledge` 404, both test-button doors. - Default-action-handlers pin: the population, and "every declared action reaches a handler". - The first A1 attempt was a no-op, refused by the tool because its replacement contained the anchor. It was redone as A1b. - A2, embedder section back on the served `ai` page: red, 4 failed (no embedder key/button; `PUT embedder_provider` 400; population; handler reach). - A3, static `nav_settings_knowledge` back: red in the absent pin (stock nav) and in the knowledge suite (the merged tree holds the entry twice when mounted, once when bare). - A4, `en` AI description naming the knowledge base again: red, 1 failed (locale description). - A5, default `actionHandlers` registering `ai.test_embedder` again: - First run: GREEN. No pin covered an extra handler, so the door pin "neither test button reaches a handler" was added. - A5b after the pin: red, 1 failed. - A6, `contributeKnowledgeSettings` not called: red, 6 of 7 failed (only the bare-hub non-vacuity case stays green). - A7, `com.objectstack.service.settings` dropped from `optionalDependencies`: red, 6 of 7 failed. `use` order alone does not put settings first. - Every leg: `ablation-replace: ok restored: blob == HEAD`, and `_DIFF_HEAD_LINES=0` at the end. </details> <details><summary>Gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands` at `1b210ee4f6`: 90 families, all exit 0. `--ran`: 90 derived, 90 run, 0 NOT-MEASURED (a derived zero). - At `f27aef7db8` (91 families, `check:adr-anchors` added): `check:i18n` first read exit 1 on a `platform-objects` dist built before the merge. After `pnpm --filter '@objectstack/platform-objects...' build` it read exit 0 ("all bundles in sync"). The other families were read as recorded in the report. - `node scripts/check-platform-checklist.mjs --changed-from origin/main`: OK, 9 anchors judged, 0 lost. - `node scripts/check-nul-bytes.mjs`: OK. eslint `--no-inline-config` on the changed `.ts` files: exit 0. - `git merge-tree --write-tree origin/main HEAD`: exit 0. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbZWBDHDjKnpVLP5aCQ <!-- signed: repo:cloud#1 · os-warren · session_01JQwxbZWBDHDjKnpVLP5aCQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5727092 commit a73edb3

34 files changed

Lines changed: 953 additions & 212 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/service-settings': patch
3+
'@objectstack/service-knowledge': patch
4+
'@objectstack/platform-objects': patch
5+
---
6+
7+
fix(settings)!: the knowledge settings page and the AI page's embedder section appear only where the knowledge service is mounted
8+
9+
Clause-②: no (narrowing) — narrowed: on a deployment that does not mount `KnowledgeServicePlugin` (every stock boot), `GET` / `PUT /api/settings/knowledge` and `POST /api/settings/knowledge/test` now answer `404 UNKNOWN_NAMESPACE`, where they served the Knowledge page; a write of an `ai.embedder_*` key (`embedder_provider`, `embedder_api_key`, `embedder_model`, `embedder_base_url`, `embedder_dimensions`, `embedder_batch_size`) now answers `400 UNKNOWN_KEY`, and `POST /api/settings/ai/test_embedder` answers that no handler is registered; the hub list no longer carries `knowledge`, and the Setup sidebar no longer carries `nav_settings_knowledge`. `builtinSettingsManifests` drops `knowledgeSettingsManifest`, and `aiSettingsManifest` drops its embedder section.
10+
Metadata-protocol: none
11+
Skills-docs: none — no skill under `skills/**` teaches the knowledge settings page or the `ai.embedder_*` keys; `skills/objectstack-ai` teaches wiring `KnowledgeServicePlugin`, which is unchanged.
12+
13+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed, renamed or re-shaped: settings manifests are runtime registrations, not authorable metadata. The moved answers are settings doors that a deployment without the knowledge service no longer serves; a deployment that mounts it serves them exactly as before, and stored rows are untouched, so there is nothing for a migration to rewrite. -->
14+
15+
**BREAKING** for a deployment that does not mount the knowledge service: the knowledge base is not a default capability, so its settings are no longer offered by default. The Knowledge page, the AI page's Embedder section, their "Test connection" / "Test embedder" buttons and the Setup entry are now contributed by `@objectstack/service-knowledge` when `KnowledgeServicePlugin` is mounted beside `SettingsServicePlugin`, and only then. Values already stored under `knowledge.*` or `ai.embedder_*` stay in the database and are served again as soon as the service is mounted.
16+
17+
The AI page's description no longer names the knowledge base, in every bundled locale.
18+
19+
`@objectstack/service-settings` now exports `knowledgeSettingsManifest`, `knowledgeTestActionHandler`, `aiSettingsManifest`, `aiEmbedderSettingsSpecifiers`, `withAiEmbedderSection` and `aiTestEmbedderActionHandler` from its package entry, and its default `actionHandlers` map no longer registers `knowledge.test` or `ai.test_embedder`. `@objectstack/service-knowledge` depends on `@objectstack/service-settings` and declares the settings plugin in `optionalDependencies`, so the kernel inits it first.
20+
21+
What to do: nothing, unless you configure an embedder or a knowledge backend from Setup. Then mount `KnowledgeServicePlugin` from `@objectstack/service-knowledge` (with a knowledge adapter plugin) beside `SettingsServicePlugin`; the page, the embedder section and the Setup entry come back with it. A host that passed its own `ai` manifest to `SettingsServicePlugin({ manifests })` adds `aiEmbedderSettingsSpecifiers` to it (or wraps it with `withAiEmbedderSection`) to keep the embedder keys. The embedder section joins only the bundled `ai` page, recognised as that very declaration; a host's own `ai` page (or one served through an option source) is left as it is, and the plugin logs a warning saying so. A host that passes its own `actionHandlers` to `SettingsServicePlugin` keeps a `knowledge` entry there only beside the knowledge manifest: without it the settings plugin refuses to register the handler for an unknown namespace at boot.
22+
23+
Stored credentials: on a deployment that does not mount the knowledge service, `ai.embedder_api_key`, `knowledge.turso_auth_token` and `knowledge.ragflow_api_key` stay stored (as `sys_secret` handles) but no settings door serves, edits or clears them, and the AI page's reset clears declared keys only. To remove them, mount `KnowledgeServicePlugin` once and clear the keys from Setup, or delete their rows from `sys_platform_setting` (the `knowledge` namespace and the `ai.embedder_*` keys) and the `sys_secret` rows whose `id` those rows hold in `value_enc` (a `sec_` handle); until then the `sys_secret` orphan report may list them.

‎docs/qa/platform-checklist/areas/platform-core.json‎

Lines changed: 20 additions & 9 deletions
Large diffs are not rendered by default.

‎packages/cli/test/connect-agent-both-halves-wire.pin.test.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', (
264264
// The Setup tree the platform admin is served BY THIS COMPOSITION: 9
265265
// authored groups less `group_approvals` and `group_integrations`,
266266
// which nothing in it contributes into and the filter collapses, plus
267-
// the 29 entries `SETUP_NAV_CONTRIBUTIONS` carries, plus the MCP one.
267+
// the 28 entries `SETUP_NAV_CONTRIBUTIONS` carries, plus the MCP one.
268268
// (25 until #25098 moved the unfiltered Packages entry to Studio; 24
269269
// until #30204 removed the Feature Flags entry with its namespace; 32
270270
// until #30895 moved the MCP entry out of `group_integrations`, the
@@ -280,20 +280,24 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', (
280280
// the public forms entry, `nav_public_forms`, joined it, #36444; 35
281281
// until objectstack#36834 gave Setup its Packages entry,
282282
// `nav_packages`, in `group_apps`, so that group is served again:
283-
// +2, `group_apps` and `nav_packages`.)
283+
// +2, `group_apps` and `nav_packages`; 37 until #33933 moved the
284+
// Knowledge entry, `nav_settings_knowledge`, to
285+
// `@objectstack/service-knowledge`, which contributes it only where the
286+
// knowledge service is mounted.)
284287
// `nav_settings_branding` is not among them, and not because of a
285288
// tenancy wall (this harness boots none): since #24766 it is
286289
// contributed by `@objectstack/service-settings` together with the
287290
// `branding` namespace, offered only where no organization wall stands,
288291
// and this harness composes platform-objects and the MCP bundle alone.
289-
expect(allowedIds).toHaveLength(37);
292+
expect(allowedIds).toHaveLength(36);
290293
expect(allowedIds).toContain('nav_packages');
291294
expect(groupChildren(setupAllowed.body?.item, 'group_apps')).toEqual(['nav_packages']);
292295
expect(allowedIds).toContain('nav_public_forms');
293296
expect(allowedIds).toContain('nav_work_calendars');
294297
expect(allowedIds).toContain('nav_work_calendar_exceptions');
295298
expect(allowedIds).not.toContain('nav_packaged_actions');
296299
expect(allowedIds).toContain('nav_settings_access_policy');
300+
expect(allowedIds).not.toContain('nav_settings_knowledge');
297301
expect(allowedIds).toContain('nav_recycle_bin');
298302
expect(allowedIds).toContain('nav_units_of_measure');
299303
expect(allowedIds).not.toContain('nav_settings_branding');
@@ -318,8 +322,8 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', (
318322
expect(withAccountHalf.statusCode).toBe(200);
319323
expect(withoutAccountHalf.statusCode).toBe(200);
320324
expect(navIds(withAccountHalf.body?.item)).toEqual(navIds(withoutAccountHalf.body?.item));
321-
// 37: the composition the count in the test above states.
322-
expect(navIds(withAccountHalf.body?.item)).toHaveLength(37);
325+
// 36: the composition the count in the test above states.
326+
expect(navIds(withAccountHalf.body?.item)).toHaveLength(36);
323327

324328
// The mechanism behind the invariance, asserted rather than assumed:
325329
// the bundle aims exactly one contribution at `setup` and one at

‎packages/platform-objects/src/apps/setup-nav.contributions.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,9 @@ export const SETUP_NAV_CONTRIBUTIONS: NavigationContribution[] = [
190190
// entry is not drawn. `features` is a root every nav entry binds.
191191
{ id: 'nav_settings_storage', type: 'url', label: 'File Storage', url: '/apps/setup/system/settings/storage', icon: 'hard-drive', requiredPermissions: ['manage_platform_settings'], visible: 'features.cloudManaged != true' },
192192
{ id: 'nav_settings_ai', type: 'url', label: 'AI & Embedder', url: '/apps/setup/system/settings/ai', icon: 'sparkles', requiredPermissions: ['manage_platform_settings'] },
193-
{ id: 'nav_settings_knowledge', type: 'url', label: 'Knowledge', url: '/apps/setup/system/settings/knowledge', icon: 'book-open', requiredPermissions: ['manage_platform_settings'] },
193+
// `nav_settings_knowledge` is contributed by `@objectstack/service-knowledge`
194+
// with the `knowledge` namespace, which is offered only where that
195+
// service is mounted — so the entry lives and dies with it.
194196
// `lifecycle` is `@objectstack/objectql`'s manifest (ADR-0057), offered
195197
// wherever a settings service is mounted, like the entries above.
196198
{ id: 'nav_settings_lifecycle', type: 'url', label: 'Data Lifecycle', url: '/apps/setup/system/settings/lifecycle', icon: 'timer', requiredPermissions: ['manage_platform_settings'] },

‎packages/services/service-knowledge/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,12 @@
2727
},
2828
"dependencies": {
2929
"@objectstack/core": "workspace:*",
30+
"@objectstack/service-settings": "workspace:*",
3031
"@objectstack/spec": "workspace:*"
3132
},
3233
"devDependencies": {
3334
"@objectstack/objectql": "workspace:*",
35+
"@objectstack/platform-objects": "workspace:*",
3436
"@types/node": "^26.6.5",
3537
"tsx": "^4.23.15",
3638
"typescript": "^6.0.3",
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The knowledge settings live and die with the knowledge service (#33933).
5+
*
6+
* A kernel that mounts `KnowledgeServicePlugin` beside `SettingsServicePlugin`
7+
* offers the knowledge page, the `ai` embedder section, both test actions and
8+
* the Setup entry; the same kernel without it offers none of them. This kernel
9+
* stands in for an app that mounts the service (none in this repository does):
10+
* the knowledge plugin is `use`d BEFORE the settings plugin on purpose, so the
11+
* pins also prove that its `optionalDependencies` declaration orders the
12+
* settings plugin ahead rather than the `use` order doing it by luck.
13+
*
14+
* The Setup entry is judged on the merged Setup tree the console reads (the
15+
* stock contributions plus every bundle registered through the `manifest`
16+
* service, folded by the ObjectQL registry), and against the hub list: the
17+
* knowledge page has exactly one sidebar entry exactly when the hub lists it.
18+
*/
19+
20+
import { describe, it, expect } from 'vitest';
21+
import { LiteKernel } from '@objectstack/core';
22+
import type { Plugin, PluginContext } from '@objectstack/core';
23+
import { ObjectQL } from '@objectstack/objectql';
24+
import { SETUP_APP, SETUP_NAV_CONTRIBUTIONS } from '@objectstack/platform-objects';
25+
import type { IHttpRequest, IHttpResponse, IHttpServer, RouteHandler } from '@objectstack/spec/contracts';
26+
import {
27+
SettingsServicePlugin,
28+
registerSettingsRoutes,
29+
aiEmbedderSettingsSpecifiers,
30+
aiTestEmbedderActionHandler,
31+
knowledgeTestActionHandler,
32+
type SettingsService,
33+
} from '@objectstack/service-settings';
34+
import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js';
35+
36+
const EMBEDDER_KEYS = aiEmbedderSettingsSpecifiers.map((s) => s.key).filter((k): k is string => !!k);
37+
const SETTINGS_PAGE = /^\/apps\/setup\/system\/settings\/([a-z_]+)$/;
38+
39+
interface NavItem { id?: string; type?: string; url?: string; children?: NavItem[] }
40+
41+
/** The `manifest` service ObjectQL provides, reduced to a recorder. */
42+
class FakeManifestPlugin implements Plugin {
43+
name = 'test.fake.manifest';
44+
version = '1.0.0';
45+
type = 'standard' as const;
46+
providesServices = ['manifest'];
47+
constructor(private readonly registered: unknown[]) {}
48+
async init(ctx: PluginContext): Promise<void> {
49+
ctx.registerService('manifest', { register: (m: unknown) => { this.registered.push(m); } });
50+
}
51+
}
52+
53+
async function boot(withKnowledge: boolean) {
54+
const registered: unknown[] = [];
55+
const kernel = new LiteKernel();
56+
kernel.use(new FakeManifestPlugin(registered));
57+
if (withKnowledge) kernel.use(new KnowledgeServicePlugin({ enableEventSync: false }));
58+
kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false }));
59+
await kernel.bootstrap();
60+
const settings = kernel.getService<SettingsService>('settings');
61+
return { kernel, settings, registered };
62+
}
63+
64+
/** The Configuration group of the merged Setup tree. */
65+
function configurationEntries(registered: unknown[]): NavItem[] {
66+
const engine = new ObjectQL();
67+
engine.registry.logLevel = 'silent';
68+
engine.registerApp({
69+
id: 'com.objectstack.test.setup-shell', namespace: 'sys', version: '0.0.0', type: 'plugin', scope: 'system',
70+
name: 'Setup shell (fixture)', apps: [SETUP_APP], navigationContributions: SETUP_NAV_CONTRIBUTIONS,
71+
} as any);
72+
for (const m of registered) engine.registerApp(m as any);
73+
const navigation = (engine.registry.getApp('setup') as { navigation?: NavItem[] } | undefined)?.navigation ?? [];
74+
return navigation.find((item) => item.id === 'group_configuration')?.children ?? [];
75+
}
76+
77+
const knowledgeEntries = (registered: unknown[]) =>
78+
configurationEntries(registered).filter((i) => i.type === 'url' && SETTINGS_PAGE.exec(i.url ?? '')?.[1] === 'knowledge');
79+
80+
async function namespaceValues(settings: SettingsService, ns: string): Promise<Record<string, unknown>> {
81+
const payload = await settings.getNamespace(ns);
82+
return Object.fromEntries(Object.entries(payload.values).map(([k, v]) => [k, (v as { value?: unknown }).value]));
83+
}
84+
85+
describe('#33933 — knowledge settings are contributed by the mounted knowledge service', async () => {
86+
const mounted = await boot(true);
87+
const bare = await boot(false);
88+
89+
it('reads two real hubs: both serve the default slate', () => {
90+
for (const { settings } of [mounted, bare]) {
91+
expect(settings.listManifests().map((m) => m.namespace)).toEqual(expect.arrayContaining(['ai', 'storage', 'mail']));
92+
}
93+
});
94+
95+
it('the knowledge page is offered with the service, and only with it', () => {
96+
expect(mounted.settings.listManifests().map((m) => m.namespace)).toContain('knowledge');
97+
expect(bare.settings.listManifests().map((m) => m.namespace)).not.toContain('knowledge');
98+
});
99+
100+
it('the ai page carries the embedder section with the service, and only with it', () => {
101+
const keysOf = (s: SettingsService) =>
102+
(s.getManifest('ai').specifiers as Array<{ key?: string; id?: string }>).map((x) => x.key ?? x.id);
103+
expect(EMBEDDER_KEYS.length).toBeGreaterThanOrEqual(6);
104+
expect(keysOf(mounted.settings)).toEqual(expect.arrayContaining([...EMBEDDER_KEYS, 'embedder', 'test_embedder']));
105+
const bareKeys = keysOf(bare.settings);
106+
expect(bareKeys).toContain('provider');
107+
for (const key of [...EMBEDDER_KEYS, 'embedder', 'test_embedder']) expect(bareKeys, key).not.toContain(key);
108+
});
109+
110+
it('both test buttons reach their handlers when the service is mounted', async () => {
111+
// "Reached" is judged by the handler's own answer for the same inputs,
112+
// never by message text: the no-handler answer is a different result.
113+
const knowledgeValues = await namespaceValues(mounted.settings, 'knowledge');
114+
expect(await mounted.settings.runAction('knowledge', 'test', {})).toEqual(
115+
await knowledgeTestActionHandler({ namespace: 'knowledge', actionId: 'test', values: knowledgeValues, payload: {}, ctx: {} }),
116+
);
117+
const aiValues = await namespaceValues(mounted.settings, 'ai');
118+
const embedder = await mounted.settings.runAction('ai', 'test_embedder', {});
119+
expect(embedder).toEqual(
120+
await aiTestEmbedderActionHandler({ namespace: 'ai', actionId: 'test_embedder', values: aiValues, payload: {}, ctx: {} }),
121+
);
122+
expect(embedder.severity).toBe('warning');
123+
});
124+
125+
it('the Setup sidebar opens the knowledge page exactly once with the service, and never without it', () => {
126+
const entries = knowledgeEntries(mounted.registered);
127+
expect(entries).toHaveLength(1);
128+
expect(entries[0].id).toBe('nav_settings_knowledge');
129+
expect(knowledgeEntries(bare.registered)).toHaveLength(0);
130+
// Non-vacuity: the bare tree is a real Setup tree with its AI entry.
131+
expect(configurationEntries(bare.registered).some((i) => i.id === 'nav_settings_ai')).toBe(true);
132+
});
133+
});
134+
135+
class MockHttp implements IHttpServer {
136+
routes = new Map<string, RouteHandler>();
137+
private add(method: string, path: string, handler: RouteHandler) {
138+
this.routes.set(`${method} ${path}`, handler);
139+
}
140+
get(path: string, h: RouteHandler) { this.add('GET', path, h); return this as any; }
141+
post(path: string, h: RouteHandler) { this.add('POST', path, h); return this as any; }
142+
put(path: string, h: RouteHandler) { this.add('PUT', path, h); return this as any; }
143+
delete(path: string, h: RouteHandler) { this.add('DELETE', path, h); return this as any; }
144+
patch(path: string, h: RouteHandler) { this.add('PATCH', path, h); return this as any; }
145+
use() { return this as any; }
146+
listen() { return Promise.resolve(); }
147+
close() { return Promise.resolve(); }
148+
getInstance() { return null; }
149+
}
150+
151+
async function post(http: MockHttp, namespace: string, actionId: string, body: unknown) {
152+
const req = { params: { namespace, actionId }, query: {}, body, headers: {}, method: 'POST', path: '/' } as IHttpRequest;
153+
const state: { status: number; body?: any } = { status: 200 };
154+
const res = {
155+
json: (data: unknown) => { state.body = data; },
156+
send: () => {},
157+
status: (code: number) => { state.status = code; return res; },
158+
header: () => res,
159+
} as unknown as IHttpResponse;
160+
await http.routes.get('POST /api/settings/:namespace/:actionId')!(req, res);
161+
return state;
162+
}
163+
164+
/**
165+
* The two buttons #24769 measured, at the HTTP door — moved here from
166+
* `@objectstack/service-settings`' `settings-default-action-handlers.pin.test.ts`
167+
* with #33933, because the composition that serves them is now the one that
168+
* mounts the knowledge service.
169+
*/
170+
describe('[#24769] the two buttons the knowledge service contributes, at the HTTP door', async () => {
171+
// A platform admin: both namespaces gate reads and writes (and so actions) on
172+
// `manage_platform_settings`.
173+
const admin = () => ({ enforced: true, permissions: ['manage_platform_settings'], userId: 'usr_admin' });
174+
const { settings } = await boot(true);
175+
const http = new MockHttp();
176+
registerSettingsRoutes(http, settings, { contextFromRequest: admin });
177+
178+
it('POST /api/settings/ai/test_embedder is answered by the embedder check (200, not 400)', async () => {
179+
const answer = await post(http, 'ai', 'test_embedder', {
180+
values: { embedder_provider: 'openai', embedder_api_key: 'sk-test', embedder_model: 'text-embedding-3-small' },
181+
});
182+
expect(answer.status).toBe(200);
183+
expect(answer.body?.data?.ok).toBe(true);
184+
expect(answer.body?.data?.message).toContain('text-embedding-3-small');
185+
});
186+
187+
it('POST /api/settings/knowledge/test is answered by the adapter check (200, not 400)', async () => {
188+
const answer = await post(http, 'knowledge', 'test', {
189+
values: { adapter: 'ragflow', ragflow_base_url: 'http://localhost:9380', ragflow_api_key: 'k' },
190+
});
191+
expect(answer.status).toBe(200);
192+
expect(answer.body?.data?.ok).toBe(true);
193+
expect(answer.body?.data?.message).toContain('localhost:9380');
194+
});
195+
});

0 commit comments

Comments
 (0)