Skip to content

Commit 4fae0be

Browse files
feat(service-messaging): serve the notification topics and channels a preference or template can name (#31004)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6Jao43VDBgUgyKRgCUkw33nkQN)_ Clause-②: yes (widening) Metadata-protocol: none Refs #30208 (row 6, server half). Ruling E on #30527 (record 6670386759), execution step 1 of comment 6670396132. The card stays open: the ui dropdowns (step 2) follow after this merges, quiet hours (step 3) is its own ui card, and row 5 is not in this PR. ## 维护者速读 - 改了什么:新增只读接口 `GET /api/v1/messaging/preference-options`,返回通知偏好与通知模板可选的「主题」和「渠道」清单(`*` 排第一;主题来自平台固定主题、本环境流程通知步骤里写明的主题、本组织已发过的通知主题;渠道列出所有已知渠道,未配置服务的标「未配置」);三个字段声明下拉控件提示;渠道帮助文字补上 push(十一种语言)。 - 为什么改:管理员在 通知偏好 里只能凭记忆手打主题和渠道的机器名,打错一个字母就静默失效;按 #30527 裁决 E,服务端先给出清单,控制台下一张卡据此画「可选可填」的下拉。 - 风险与回滚:字段仍是文本、`*` 照存、不新增任何拒绝,已存数据不动;新接口只读、仅限已登录成员,且每个组织只看得到自己组织的已存主题。回滚即撤销本 PR,控件提示在控制台注册前本来就退化为文本框。 - 先看:`packages/services/service-messaging/src/preference-options.ts`(三个主题来源与组织边界的 `organization_id` 条件)、`src/preference-options-routes.ts`(拒绝顺序:身份→受限登录→匿名→查询参数)、`src/messaging-service-plugin.ts` 的挂载段。 - 两分钟验证:`pnpm --filter @objectstack/service-messaging exec vitest run src/preference-options-routes.integration.test.ts`,预期 8 个用例全过(含「B 组织的主题不会出现在 A 组织」)。 - 需要你做的:无,席位落地。 ## What changes - **A read-only list route, mounted by service-messaging itself** (route B in the seat's claim 6688765720): `registerPreferenceOptionsRoutes` (`src/preference-options-routes.ts`) mounts `GET /api/v1/messaging/preference-options` on `http-server` at `kernel:ready`, as service-settings / service-print / service-storage mount theirs. The sibling `/api/v1/notifications` routes live in `packages/runtime` behind `INotificationService` (a spec contract), so a runtime face would have needed a spec card; this PR touches neither `packages/runtime` nor `packages/spec`. A kernel with no HTTP server logs one `warn` naming what is not mounted. - **Who may ask** (the posture of `/api/v1/notifications`): any signed-in member. The caller is resolved by the one composition (`resolveRequestExecutionContext`, session or API key); an authorization-store outage and an API key lifecycle refusal are relayed as declared; a held sign-in is `403` with the policy's code; anonymous is `401 UNAUTHENTICATED`; the closed query set is empty, so any query parameter is `400 VALIDATION_ERROR` naming it. All of these answer before any source is read. - **What it serves** (`src/preference-options.ts`), response `{ success: true, data: { topics, channels } }`: - `topics: Array<{ value: string; wildcard: boolean; sources: Array<'platform' | 'flow' | 'stored'> }>`: `{ value: '*', wildcard: true, sources: [] }` first, then sorted and de-duplicated, each with every source naming it: `PLATFORM_NOTIFICATION_TOPICS` (15 fixed topics measured from their send/template sites in plugin-approvals, plugin-audit, plugin-security, plugin-auth); every `notify` step's own string `topic` in this environment's flows (`protocol.getMetaItems({ type: 'flow' })`), and `notify` for a step that names none (the node's own default); the distinct `sys_notification.topic` values of the caller's organization (one `aggregate` grouped by `topic`, `where: { organization_id }`, under a named system context `PREFERENCE_OPTIONS_SYSTEM_CONTEXT`; a caller with no organization gets no stored topic). - `channels: Array<{ value: string; wildcard: boolean; configured: boolean }>`: `*` first, then `MessagingService.getKnownChannels()` (new): directly registered channels, then each lazy provider, `configured: false` when its transport is absent ("not configured"). - A source that cannot be read answers `500 INTERNAL_ERROR` with the door's sentence and the error in the fault log, never a partial list. - **The fields**: `sys_notification_preference.topic` declares `widget: 'notification-topic'`, `.channel` declares `widget: 'notification-channel'`, `sys_notification_template.topic` declares `widget: 'notification-topic'`. `FieldSchema.widget` is an existing free `z.string()`, so no spec value is added; an unregistered widget degrades to the text box. The template's `channel` keeps `channel_renders_template` and declares nothing. - **The help**: the preference channel help names `push` (registered as a lazy provider since #29041), in the English source and all ten translated bundles; `en` regenerated by `check-i18n-bundles --write`. - **Ledger**: `src/messaging-route-ledger.ts` (one `server-only` row) with its package-local conformance test, and the three wiring lines the claim names: the live-mount parity dogfood test imports the ledger, and `scripts/cross-package-test-inputs.mjs` / `turbo.json` declare it as that test's input. - **Envelope guard**: `scripts/check-route-envelope.mjs` declares the new door in `MODULES` at `{ responses: 0, ok: 0, err: 0 }` beside the print door (every body goes through the shared `sendOk` / `sendError` / `sendServerFault`). The claim was widened to this path for it. ## Tests - `src/preference-options-routes.integration.test.ts` (new, 8 cases), real resolver over a fake auth service, real `ObjectQL` over `SqlDriver` (better-sqlite3) holding `org_a` and `org_b` on the `isolated` posture: the full list and its sources; cross-organization isolation (a topic stored in `org_b` never listed for `org_a`, and the reverse); no protocol means no flow topic; anonymous `401`, held sign-in `403 PASSWORD_EXPIRED`, query parameter `400` naming it, each asserting by envelope (ApiError parse + code + status) and that no source was read; a failing source `500`, no data. - `src/messaging-route-ledger.conformance.test.ts` (new): registrar enumeration against the ledger, both directions. - `src/objects/notification-preference-topic-channel-help.test.ts` re-pinned: the built channel ids are `['inbox', 'email', 'sms', 'push']` (push factory added to the enumeration) and the help names exactly those; `push` left the "named but not implemented" list; a new case pins the three widget hints, the template topic's `text` type, and no widget on the template channel. ## Acceptance notes - **Flows are the environment's, not an organization's** (ADR-0131 D6: the list serves the environment's rows and no organization's), so every organization of one environment is offered the same flow topics; the organization boundary applies to the stored topics, which is what the isolation pin holds. - **`PLATFORM_NOTIFICATION_TOPICS` is a measured constant**, since nothing registers topics (ADR-0030's `defineTopic()` was never built). A feature that starts sending a new fixed topic must add it there; no gate catches a miss. `auth.phone_otp` / `auth.phone_invite` are template topics (the SMS goes out without `emit()`), listed because the template form reads the same list; on a preference they match nothing. - The stored-topic read is unbounded in the number of distinct topics (one grouped `aggregate`, no limit in `EngineAggregateOptions`); the event table's 90-day lifecycle window bounds it in practice. - The anonymous floor test first stayed green under a narrower mutation (`shouldDenyAnonymous` removed, `!context` kept), because the fail-closed composition already answers no context for an unauthenticated request; the second mutation removed the whole branch and went red (below). Both runs are recorded. - **A derived-gate blind spot**: `node scripts/pm/dispatch-gates.mjs --commands` did not derive `pnpm check:route-envelope` for this diff's paths, so the 86 local gates were green while CI's `Lint · docs & code guards` went red on `Response-envelope guard` (run 42254020926, `NOT DECLARED`) at `d4930694`. Fixed in `581fce5c`; a new `*-routes.ts` module outside the derivation's reach needs that command run by hand. - No `skills/**`, `content/docs/**` or ADR edit: no published sentence states these fields have no list. The ui half (registering `field:notification-topic` / `field:notification-channel`) is the next card. ## Verification All readings on head `d4930694` unless a line says otherwise (`d4930694` = `00bd47c0` + merge of `origin/main`, 8 commits, only `turbo.json` overlapping; head `581fce5c` adds only the envelope-guard declaration). <details><summary>Package suite, typecheck, lint (on 00bd47c, before the main merge)</summary> - `pnpm --filter @objectstack/service-messaging test && pnpm --filter @objectstack/service-messaging typecheck` under the verify lock: Test Files 69 passed (69), Tests 874 passed (874); VERDICT command-exit 0. - `npx eslint --no-inline-config packages/services/service-messaging/src packages/qa/dogfood/test/route-ledger-live-mount-parity.dogfood.test.ts scripts/cross-package-test-inputs.mjs`: exit 0. - `pnpm --filter @objectstack/dogfood exec vitest run test/route-ledger-live-mount-parity.dogfood.test.ts`: 8/8 passed on the showcase boot, which logged `[messaging] preference options list mounted at GET /api/v1/messaging/preference-options`; VERDICT command-exit 0. </details> <details><summary>Negative-pin ablations (each through scripts/ablation-replace.mjs, restored blob == HEAD, git diff HEAD empty)</summary> - Organization term deleted (`where: { organization_id: organizationId },`, anchor 1 -> 0): `a topic stored in one organization never appears for another` failed, `AssertionError: expected [ '*', 'approval.comment', …(18) ] to not include 'org_b.secret_topic'`. - Anonymous branch replaced by `if (false as boolean) {`: `refuses an anonymous caller 401 UNAUTHENTICATED` failed, `expected [ 'INTERNAL_ERROR', 500 ] to deeply equal [ 'UNAUTHENTICATED', 401 ]`. (First mutation, `if (!context) {`, stayed green: see Acceptance notes.) - Held sign-in gate disabled: `refuses a held sign-in 403 ...` failed. - Query refusal disabled: `refuses a query parameter 400 VALIDATION_ERROR naming it, never ignoring it` failed. - Notify-type filter disabled (every node read as a notify step): the list case failed on `not.a.notify.topic`. </details> <details><summary>Derived gates</summary> - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on `00bd47c0` (25 paths): 86 commands, every one run with stdin from /dev/null, all `:: exit 0`. - `--ran`: `86 derived, 86 run, 0 NOT-MEASURED, 0 UNRUN`. - After the main merge, on `d4930694`: `pnpm check:turbo-task-graph`, `pnpm check:cross-package-test-inputs`, `pnpm check:ci-filter-parity`, `pnpm check:i18n`: exit 0 each. - On `581fce5c`: `pnpm check:route-envelope` exit 0 (`--self-test` then the audit; was `NOT DECLARED` for `preference-options-routes.ts` before), `npx eslint --no-inline-config scripts/check-route-envelope.mjs` exit 0. - Changeset: `.changeset/30208-messaging-preference-options.md`, `@objectstack/service-messaging: patch`, carrying both declaration lines at line start. - Dogfood battery: n/a (no `!` in the title, no `(narrowing)` arm). </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibwBQRERS1JhPWT48RW --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibwBQRERS1JhPWT48RW)_ <!-- signed: domain:server#2 · os-tesla · session_01L9qibwBQRERS1JhPWT48RW --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent adab62a commit 4fae0be

26 files changed

Lines changed: 927 additions & 35 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/service-messaging': patch
3+
---
4+
5+
feat(service-messaging): serve the notification topics and channels a preference or template can name
6+
7+
Clause-②: yes (widening) — a new read-only route, `GET /api/v1/messaging/preference-options`, mounted by `MessagingServicePlugin` on the kernel's HTTP server; nothing existing is narrowed or refused.
8+
Metadata-protocol: none
9+
10+
The topic and channel of a notification preference stay free text, `*` is still stored as written, and nothing new is refused. What is new is a list the console can offer beside the text box, so an administrator picks a value instead of typing a machine name from memory.
11+
12+
- **The route.** `GET /api/v1/messaging/preference-options` answers `{ topics, channels }`. `topics` starts with `*` and lists the platform's fixed topics (`approval.requested`, `collab.mention`, …), the topics this environment's flow `notify` steps send under (`notify` for a step that names none), and the topics already stored on this organization's notifications, each once with every source that names it. `channels` starts with `*` and lists every channel the service knows, with `configured: false` on one whose service is not set up yet (email with no email service, …). Any signed-in member may read it, as on `/api/v1/notifications`; an anonymous caller is refused `401`, a held sign-in `403`, and a query parameter `400`. A topic stored in one organization is never listed for another.
13+
- **The fields.** `sys_notification_preference.topic` and `sys_notification_template.topic` declare `widget: 'notification-topic'`, and `sys_notification_preference.channel` declares `widget: 'notification-channel'`, for the console's pick-or-type inputs; until the console registers them, the fields render as the same text boxes. The template's channel keeps its existing refusal.
14+
- **The help.** The preference channel's help now names `push`, available once a push service is configured, in every language.

‎packages/qa/dogfood/test/route-ledger-live-mount-parity.dogfood.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ import { STORAGE_ROUTE_LEDGER } from '../../../services/service-storage/src/stor
7272
import { I18N_ROUTE_LEDGER } from '../../../services/service-i18n/src/i18n-route-ledger.js';
7373
import { SETTINGS_ROUTE_LEDGER } from '../../../services/service-settings/src/settings-route-ledger.js';
7474
import { PRINT_ROUTE_LEDGER } from '../../../services/service-print/src/print-route-ledger.js';
75+
import { MESSAGING_ROUTE_LEDGER } from '../../../services/service-messaging/src/messaging-route-ledger.js';
7576
import { PERSONAL_VIEW_ROUTE_LEDGER } from '../../../plugins/plugin-auth/src/personal-view-route-ledger.js';
7677

7778
/** One ledger row, normalized to a wire pattern this gate can probe. */
@@ -109,6 +110,7 @@ function collectLedgerRows(): LedgerRow[] {
109110
for (const r of I18N_ROUTE_LEDGER) add('service-i18n/i18n-route-ledger.ts', r.route, '');
110111
for (const r of SETTINGS_ROUTE_LEDGER) add('service-settings/settings-route-ledger.ts', r.route, '');
111112
for (const r of PRINT_ROUTE_LEDGER) add('service-print/print-route-ledger.ts', r.route, '');
113+
for (const r of MESSAGING_ROUTE_LEDGER) add('service-messaging/messaging-route-ledger.ts', r.route, '');
112114
// [#29443] AuthPlugin's own-row delete door for a personal view, mounted on
113115
// the IHttpServer port (unlike its raw-app `/auth/*` catch-all above).
114116
for (const r of PERSONAL_VIEW_ROUTE_LEDGER) add('plugin-auth/personal-view-route-ledger.ts', r.route, '');
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Messaging route-ledger conformance — the package-local guard every
5+
* `*-route-ledger.ts` pairs with. `registerPreferenceOptionsRoutes` is a
6+
* standalone, synchronous function that calls `http.get` and touches neither
7+
* argument before a request arrives, so a capturing mock `IHttpServer`
8+
* enumerates its real surface (the seam the print and settings ledgers use),
9+
* and the two directions fail here by name on every `pnpm test` of this
10+
* package.
11+
*/
12+
13+
import { describe, it, expect, vi } from 'vitest';
14+
import { registerPreferenceOptionsRoutes } from './preference-options-routes.js';
15+
import { MESSAGING_ROUTE_LEDGER } from './messaging-route-ledger.js';
16+
17+
function createMockServer() {
18+
return {
19+
get: vi.fn(),
20+
post: vi.fn(),
21+
put: vi.fn(),
22+
delete: vi.fn(),
23+
patch: vi.fn(),
24+
use: vi.fn(),
25+
listen: vi.fn().mockResolvedValue(undefined),
26+
close: vi.fn().mockResolvedValue(undefined),
27+
};
28+
}
29+
30+
function enumerateMessagingRoutes(): Set<string> {
31+
const server = createMockServer();
32+
registerPreferenceOptionsRoutes(server as any, {} as any);
33+
const keys = new Set<string>();
34+
for (const verb of ['get', 'post', 'put', 'patch', 'delete'] as const) {
35+
for (const call of server[verb].mock.calls) keys.add(`${verb.toUpperCase()} ${call[0]}`);
36+
}
37+
return keys;
38+
}
39+
40+
const ledgerKeys = (): Set<string> => new Set(MESSAGING_ROUTE_LEDGER.map((e) => e.route));
41+
42+
describe('messaging route ledger ↔ registerPreferenceOptionsRoutes enumeration', () => {
43+
it('every mounted messaging route has a ledger entry', () => {
44+
const ledger = ledgerKeys();
45+
const missing = [...enumerateMessagingRoutes()].filter((k) => !ledger.has(k));
46+
expect(missing, `messaging routes with no messaging-route-ledger entry: ${missing.join(', ')}`).toEqual([]);
47+
});
48+
49+
it('every ledger entry is really mounted by the registrar', () => {
50+
const live = enumerateMessagingRoutes();
51+
const stale = [...ledgerKeys()].filter((k) => !live.has(k));
52+
expect(stale, `messaging-route-ledger entries the registrar no longer mounts: ${stale.join(', ')}`).toEqual([]);
53+
});
54+
55+
it('the ledger is compared against a real enumeration, not an empty one', () => {
56+
const live = enumerateMessagingRoutes();
57+
expect(live.size).toBeGreaterThan(0);
58+
expect(live.size).toBe(ledgerKeys().size);
59+
expect(MESSAGING_ROUTE_LEDGER.every((e) => e.disposition === 'sdk' || (e.note ?? '').length > 0)).toBe(true);
60+
});
61+
});
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Messaging route ledger — the audited disposition of every HTTP route
5+
* `registerPreferenceOptionsRoutes` (`preference-options-routes.ts`) mounts.
6+
*
7+
* WHY THIS EXISTS. `MessagingServicePlugin` reaches for the `http-server`
8+
* service and registers straight on `IHttpServer`, so neither the dispatcher
9+
* ledger nor the REST ledger sees its route, the same shape as the storage,
10+
* settings and print families. `messaging-route-ledger.conformance.test.ts`
11+
* fails when the registrar mounts a route with no row here, and when a row
12+
* names a route it no longer mounts; the dogfood live-mount parity gate reads
13+
* this ledger beside the others on a real boot. The inbox routes
14+
* (`/api/v1/notifications*`) are not here: the runtime dispatcher serves them,
15+
* and they are rows of its own ledger.
16+
*
17+
* NOT SDK SURFACE. `@objectstack/client` expresses no method for it: the
18+
* consumer is the console's notification preference and template forms, over
19+
* plain HTTP. That is a `server-only` disposition.
20+
*
21+
* This module is package-internal (not exported from the index): it is the
22+
* guard's data, not public API. It stays import-free, so a guard in another
23+
* package can read it as a relative SOURCE file.
24+
*/
25+
26+
/** Disposition of a single messaging route. Same vocabulary as the REST ledger. */
27+
export type MessagingRouteDisposition =
28+
/** Expressed by the SDK — `client` names the method (dotted path). */
29+
| 'sdk'
30+
/** Should be in the SDK and is not — an open, acknowledged gap. */
31+
| 'gap'
32+
/** Deliberately not SDK surface. */
33+
| 'server-only'
34+
/** Public, unauthenticated browser-facing route. */
35+
| 'public'
36+
/** Server and client disagree on the shape — needs reconciliation. */
37+
| 'mismatch';
38+
39+
export interface MessagingRouteLedgerEntry {
40+
/** `VERB /api/v1/messaging/...` — the full wire path. */
41+
route: string;
42+
/** Registrar family, for grouping and diff messages. */
43+
family: string;
44+
disposition: MessagingRouteDisposition;
45+
/** Dotted method path on `ObjectStackClient` — required when disposition is `sdk`. */
46+
client?: string;
47+
/** One-line rationale. Required for every non-`sdk` disposition. */
48+
note?: string;
49+
}
50+
51+
export const MESSAGING_ROUTE_LEDGER: readonly MessagingRouteLedgerEntry[] = [
52+
{ route: 'GET /api/v1/messaging/preference-options', family: 'messaging', disposition: 'server-only',
53+
note: 'the topics and channels a notification preference or template can name, for the console\'s pick-or-type inputs; any signed-in member, read-only' },
54+
];

‎packages/services/service-messaging/src/messaging-service-plugin.ts‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import { randomUUID } from 'node:crypto';
4-
import type { Plugin, PluginContext } from '@objectstack/core';
4+
import type { Plugin, PluginContext, RequestAuthService, TenancyPostureSource } from '@objectstack/core';
55
import { resolveLocalizationContext } from '@objectstack/core';
6-
import type { IDataEngine } from '@objectstack/spec/contracts';
6+
import type { IDataEngine, IHttpServer } from '@objectstack/spec/contracts';
7+
import { PREFERENCE_OPTIONS_ROUTE, registerPreferenceOptionsRoutes } from './preference-options-routes.js';
8+
import type { PreferenceOptionsEngine } from './preference-options.js';
79
import { MessagingService } from './messaging-service.js';
810
import type { MessagingChannel } from './channel.js';
911
import { createInboxChannel } from './inbox-channel.js';
@@ -548,6 +550,15 @@ export class MessagingServicePlugin implements Plugin {
548550
});
549551
}
550552

553+
// [#30208 row 6, ruling E on #30527] The preference options door
554+
// (`preference-options-routes.ts`): the topics and channels a
555+
// preference or template can name, for the console's pick-or-type
556+
// inputs. Mounted at `kernel:ready`, when the HTTP server is
557+
// registered; every source it lists is read per request.
558+
if (typeof ctx.hook === 'function') {
559+
ctx.hook('kernel:ready', async () => this.mountPreferenceOptionsDoor(ctx, service, getData));
560+
}
561+
551562
// Reliable delivery (P1): wire the outbox + dispatcher once the engine
552563
// is resolvable. Until then `emit()` runs inline best-effort.
553564
if (this.options.reliableDelivery && typeof ctx.hook === 'function') {
@@ -624,6 +635,52 @@ export class MessagingServicePlugin implements Plugin {
624635
);
625636
}
626637

638+
/**
639+
* Mount `GET /api/v1/messaging/preference-options` on the kernel's HTTP
640+
* server. A kernel with no HTTP server says so once and mounts nothing:
641+
* the fields stay plain text boxes, and the in-process service is unchanged.
642+
*/
643+
private mountPreferenceOptionsDoor(
644+
ctx: PluginContext,
645+
service: MessagingService,
646+
getData: () => IDataEngine | undefined,
647+
): void {
648+
const optional = <T>(name: string): T | undefined => {
649+
try {
650+
return ctx.getService<T>(name) ?? undefined;
651+
} catch {
652+
return undefined;
653+
}
654+
};
655+
const http = optional<IHttpServer>('http-server');
656+
if (!http) {
657+
ctx.logger.warn(
658+
`[messaging] no HTTP server is registered, so the preference options list (GET ${PREFERENCE_OPTIONS_ROUTE}) ` +
659+
'is not mounted: the console draws notification topic and channel as plain text boxes.',
660+
);
661+
return;
662+
}
663+
const kernel = ctx.getKernel?.() as
664+
| { getServiceAsync?: <T>(name: string) => Promise<T> }
665+
| undefined;
666+
registerPreferenceOptionsRoutes(http, {
667+
getEngine: () => optional<unknown>('objectql'),
668+
getAuth: () => optional<RequestAuthService>('auth'),
669+
tenancy: kernel && typeof kernel.getServiceAsync === 'function'
670+
? () => kernel.getServiceAsync!<TenancyPostureSource>('tenancy')
671+
: undefined,
672+
knownChannels: () => service.getKnownChannels(),
673+
getData: () => getData() as unknown as PreferenceOptionsEngine | undefined,
674+
readFlows: async () => {
675+
const protocol = optional<{ getMetaItems?(q: { type: string }): Promise<unknown> }>('protocol');
676+
if (!protocol || typeof protocol.getMetaItems !== 'function') return undefined;
677+
const raw = await protocol.getMetaItems({ type: 'flow' });
678+
return Array.isArray(raw) ? raw : ((raw as { items?: unknown[] } | null)?.items ?? []);
679+
},
680+
});
681+
ctx.logger.info(`[messaging] preference options list mounted at GET ${PREFERENCE_OPTIONS_ROUTE}`);
682+
}
683+
627684
/**
628685
* Provision the physical tables for this service's system objects up-front.
629686
*

‎packages/services/service-messaging/src/messaging-service.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -596,6 +596,25 @@ export class MessagingService {
596596
return [...ids];
597597
}
598598

599+
/**
600+
* Every channel id this service knows, and whether it is mounted right now:
601+
* the channels registered directly, then each lazy provider (#18050), read
602+
* per call like {@link getRegisteredChannels}. A provider whose transport is
603+
* absent (email with no email service, push with no push service) is known
604+
* and answers `configured: false`, so a list built from this can offer the
605+
* id while saying the deployment cannot send on it yet. Read by the
606+
* preference options door (`preference-options-routes.ts`).
607+
*/
608+
getKnownChannels(): Array<{ id: string; configured: boolean }> {
609+
const known: Array<{ id: string; configured: boolean }> = [];
610+
for (const id of this.channels.keys()) known.push({ id, configured: true });
611+
for (const id of this.channelProviders.keys()) {
612+
if (this.channels.has(id)) continue;
613+
known.push({ id, configured: this.getChannel(id) !== undefined });
614+
}
615+
return known;
616+
}
617+
599618
/* ------------------------------------------------------------------ */
600619
/* Inbox read API (ADR-0030) — backs /api/v1/notifications */
601620
/* */

‎packages/services/service-messaging/src/objects/notification-preference-topic-channel-help.test.ts‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
/**
44
* `sys_notification_preference.topic` and `.channel` stay free text, and their
5-
* help says what to type (#25346, ruling A 2026-10-23).
5+
* help says what to type (#25346, ruling A 2026-10-23); both, and
6+
* `sys_notification_template.topic`, declare the console's pick-or-type input
7+
* over the served list (#30208 row 6, ruling E on #30527).
68
*
79
* Setup → Notification Preferences offered two bare text boxes, so muting a
810
* topic meant knowing its machine name. Neither set can be a picker: topics
@@ -15,19 +17,26 @@
1517
* "all", so no stored row or write changes meaning;
1618
* - the channel help names exactly the ids of the channels this package
1719
* builds, read from the channel factories themselves, so a channel added
18-
* or renamed here fails this file until the help says so (the old help
19-
* named a `push` channel that never existed);
20-
* - the topic help names where topics come from and the wildcard.
20+
* or renamed here fails this file until the help says so (push joined the
21+
* four with #29041);
22+
* - the topic help names where topics come from and the wildcard;
23+
* - the widget hints name the two inputs the console registers, and only a
24+
* hint: the field type and the wildcard default do not move with them, and
25+
* the template's channel, which has its own refusal, declares none.
2126
*/
2227

2328
import { describe, expect, it } from 'vitest';
2429
import { NotificationPreference } from './notification-preference.object.js';
30+
import { NotificationTemplate } from './notification-template.object.js';
2531
import { createInboxChannel } from '../inbox-channel.js';
2632
import { createEmailChannel } from '../email-channel.js';
2733
import { createSmsChannel } from '../sms-channel.js';
34+
import { createPushChannel } from '../push-channel.js';
2835
import { NotificationTemplateStore } from '../template-renderer.js';
2936

30-
const fields = NotificationPreference.fields as Record<string, { type?: string; defaultValue?: unknown; description?: string }>;
37+
type FieldShape = { type?: string; defaultValue?: unknown; description?: string; widget?: string };
38+
const fields = NotificationPreference.fields as Record<string, FieldShape>;
39+
const templateFields = NotificationTemplate.fields as Record<string, FieldShape>;
3140

3241
/** The ids of the channels `MessagingServicePlugin` registers, read off the factories. */
3342
function builtInChannelIds(): string[] {
@@ -37,6 +46,7 @@ function builtInChannelIds(): string[] {
3746
createInboxChannel({ getData }).id,
3847
createEmailChannel({ getEmail: () => undefined, getData, store }).id,
3948
createSmsChannel({ getSms: () => undefined, getData, store }).id,
49+
createPushChannel({ getPush: () => undefined, devices: {} as any, getData }).id,
4050
];
4151
}
4252

@@ -57,10 +67,10 @@ describe('sys_notification_preference topic / channel help (#25346)', () => {
5767
it('the channel help names every channel this package builds, and no channel it does not', () => {
5868
const help = fields.channel?.description ?? '';
5969
const ids = builtInChannelIds();
60-
expect(ids).toEqual(['inbox', 'email', 'sms']);
70+
expect(ids).toEqual(['inbox', 'email', 'sms', 'push']);
6171
expect(channelIdsNamedIn(help, ids)).toEqual(ids);
6272
// Ids the spec's channel vocabulary carries that no channel here implements.
63-
expect(channelIdsNamedIn(help, ['push', 'webhook', 'slack', 'teams', 'in-app'])).toEqual([]);
73+
expect(channelIdsNamedIn(help, ['webhook', 'slack', 'teams', 'in-app'])).toEqual([]);
6474
// The seam is open: a plugin's own channel id is a valid value too.
6575
expect(help).toMatch(/a channel an installed plugin adds/);
6676
});
@@ -70,4 +80,14 @@ describe('sys_notification_preference topic / channel help (#25346)', () => {
7080
expect(help).toMatch(/notify step/);
7181
expect(help).toMatch(/approval\.requested/);
7282
});
83+
84+
it('the topic and channel inputs declare the pick-or-type widgets, and nothing else moves', () => {
85+
expect(fields.topic?.widget).toBe('notification-topic');
86+
expect(fields.channel?.widget).toBe('notification-channel');
87+
expect(templateFields.topic?.widget).toBe('notification-topic');
88+
expect(templateFields.topic?.type).toBe('text');
89+
// The template channel keeps `channel_renders_template` and no widget.
90+
expect(templateFields.channel?.widget).toBeUndefined();
91+
expect(templateFields.channel?.type).toBe('text');
92+
});
7393
});

0 commit comments

Comments
 (0)