@sssb/kit 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/release.json +1 -1
  2. package/package.json +4 -1
  3. package/src/adapters/fake/auth.ts +18 -6
  4. package/src/adapters/fake/db.ts +4 -2
  5. package/src/adapters/fake/jobs.ts +17 -39
  6. package/src/adapters/fake/simulator.ts +2 -3
  7. package/src/adapters/index.ts +33 -6
  8. package/src/adapters/lazy-jobs.ts +25 -0
  9. package/src/adapters/proxy.ts +34 -0
  10. package/src/adapters/real/absent.ts +54 -0
  11. package/src/adapters/real/accept-invite-form.tsx +62 -15
  12. package/src/adapters/real/analytics.ts +1 -1
  13. package/src/adapters/real/auth.ts +28 -2
  14. package/src/adapters/real/clerk-proxy.ts +111 -0
  15. package/src/adapters/real/db-data-api.ts +1 -1
  16. package/src/adapters/real/db-port.ts +27 -0
  17. package/src/adapters/real/db.ts +2 -21
  18. package/src/adapters/real/index.ts +117 -30
  19. package/src/adapters/real/jobs-in-process.ts +118 -0
  20. package/src/adapters/real/jobs.ts +2 -1
  21. package/src/adapters/real/no-analytics.ts +17 -0
  22. package/src/adapters/real/optional-ports.ts +112 -0
  23. package/src/adapters/real/s3-storage.ts +7 -1
  24. package/src/adapters/real/storage-settings.ts +37 -0
  25. package/src/adapters/real/storage.ts +65 -0
  26. package/src/adapters/run-mode.ts +11 -0
  27. package/src/components/app-header.tsx +1 -1
  28. package/src/components/simulator/simulator-host.tsx +335 -0
  29. package/src/components/simulator/simulator-panel.tsx +45 -57
  30. package/src/core/abilities.ts +6 -1
  31. package/src/core/same-origin-path.ts +20 -0
  32. package/src/cutover/rows.json +13 -1
  33. package/src/db/audit.ts +2 -2
  34. package/src/db/family-suite.ts +42 -0
  35. package/src/db/family.ts +91 -0
  36. package/src/db/jobs.ts +4 -3
  37. package/src/db/keyset.ts +12 -25
  38. package/src/db/migrations/0015_app_user_grant.ts +1 -1
  39. package/src/db/notifications.ts +2 -2
  40. package/src/db/org-lookup.ts +1 -1
  41. package/src/db/rls-proof-runner.ts +3 -2
  42. package/src/db/schedules.ts +2 -1
  43. package/src/db/webhooks.ts +4 -4
  44. package/src/demo-static/world.ts +5 -4
  45. package/src/guide.md +23 -4
  46. package/src/jobs/digest-email.ts +32 -17
  47. package/src/jobs/run-in-process.ts +82 -0
  48. package/src/observability/scrub.ts +3 -1
  49. package/src/ports/auth.ts +21 -2
  50. package/src/ports/db.ts +19 -0
  51. package/src/ports/jobs.ts +25 -4
  52. package/src/server-lib/defer.ts +4 -0
  53. package/src/server-lib/invite.ts +34 -26
  54. package/src/server-lib/scheduled-tick.ts +13 -3
  55. package/src/server-lib/simulator-api.ts +311 -0
  56. package/src/service-auth/credential.ts +20 -0
  57. package/src/service-auth/mailgun.ts +2 -2
  58. package/src/service-auth/verify.ts +10 -3
  59. package/src/service-auth/webhook.ts +14 -5
  60. package/src/testing/checks.json +9 -0
  61. package/src/testing/conformance/auth-provider.ts +296 -0
  62. package/src/testing/conformance/db.ts +6 -5
  63. package/src/testing/conformance/suite.ts +2 -0
  64. package/src/testing/contract.ts +6 -4
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The values of `STORAGE_PROVIDER=s3-compatible` that choose behaviour, checked in one place that loads no SDK: the
3
+ * adapter (./storage.ts) checks them as it is built, and `assertRealEnv` (./index.ts) checks them too, so
4
+ * `sssb check-real-env` refuses what the server would refuse at boot. Each failure names its variable and, so that a
5
+ * secret pasted into the wrong one never reaches a log, never repeats a value that could hold one (the endpoint).
6
+ */
7
+
8
+ /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `none` if it does not. */
9
+ export function parseUploadTarget(value: string): 'post' | 'none' {
10
+ if (value === 'post' || value === 'none') return value
11
+ throw new Error(`STORAGE_UPLOAD_TARGET must be post or none (got "${value}")`)
12
+ }
13
+
14
+ /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (an empty value counts as unset) for the SDK's own addressing. */
15
+ export function parseForcePathStyle(value: string | undefined): boolean | undefined {
16
+ if (value === undefined || value === '') return undefined
17
+ if (value === 'true') return true
18
+ if (value === 'false') return false
19
+ throw new Error(`STORAGE_FORCE_PATH_STYLE must be true or false when set (got "${value}")`)
20
+ }
21
+
22
+ /** `STORAGE_ENDPOINT`: an http(s) URL carrying no credentials (the key pair has settings of its own). */
23
+ export function assertEndpoint(endpoint: string): void {
24
+ let url: URL
25
+ try {
26
+ url = new URL(endpoint)
27
+ } catch {
28
+ throw new Error('STORAGE_ENDPOINT must be an http(s) URL')
29
+ }
30
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
31
+ throw new Error('STORAGE_ENDPOINT must be an http(s) URL')
32
+ if (url.username !== '' || url.password !== '') {
33
+ throw new Error(
34
+ 'STORAGE_ENDPOINT must not carry a user or password: the key pair is STORAGE_ACCESS_KEY_ID and STORAGE_SECRET_ACCESS_KEY',
35
+ )
36
+ }
37
+ }
@@ -1,5 +1,6 @@
1
1
  import type { StoragePort } from '../../ports/storage'
2
2
  import { createS3Storage } from './s3-storage'
3
+ import { assertEndpoint, parseForcePathStyle, parseUploadTarget } from './storage-settings'
3
4
 
4
5
  /**
5
6
  * The storage the real-mode registry builds (`./index.ts`): the published S3 adapter (`./s3-storage.ts`,
@@ -8,3 +9,67 @@ import { createS3Storage } from './s3-storage'
8
9
  export function createRealStorage(bucket: string, region: string): StoragePort {
9
10
  return createS3Storage({ bucket, region })
10
11
  }
12
+
13
+ /**
14
+ * Where an S3-compatible store (Cloudflare R2, MinIO, Backblaze B2) is, as `STORAGE_PROVIDER=s3-compatible` reads it
15
+ * (./optional-ports.ts). The two strings that choose behaviour arrive as the environment gave them and are checked
16
+ * here, so a wrong value fails at boot naming its variable.
17
+ */
18
+ export interface CompatibleStorageSettings {
19
+ /** `STORAGE_BUCKET`. */
20
+ bucket: string
21
+ /** `STORAGE_ENDPOINT`: the store's S3 API endpoint, as an http(s) URL. */
22
+ endpoint: string
23
+ /** `STORAGE_REGION`: what the store signs requests for (R2 takes `auto`). Not `AWS_REGION`, which Lambda reserves. */
24
+ region: string
25
+ /** `STORAGE_ACCESS_KEY_ID`. Not `AWS_ACCESS_KEY_ID`, which Lambda reserves for the function's own role. */
26
+ accessKeyId: string
27
+ /** `STORAGE_SECRET_ACCESS_KEY`. */
28
+ secretAccessKey: string
29
+ /** `STORAGE_UPLOAD_TARGET`: `post` if the store accepts a presigned POST, `none` if it does not. */
30
+ uploadTarget: string
31
+ /** `STORAGE_FORCE_PATH_STYLE`: `true`, `false`, or unset (empty counts as unset) for the SDK's own addressing. */
32
+ forcePathStyle?: string | undefined
33
+ }
34
+
35
+ /**
36
+ * The storage port on an S3-compatible store: the same adapter as `createRealStorage`, pointed at `endpoint` with the
37
+ * store's own key pair. Everything but the upload target is S3's API, which these stores implement (ADR-0015, section
38
+ * 6 lists what R2 does). `createUploadTarget` is an S3 presigned POST, which R2 does not accept, so it follows
39
+ * `uploadTarget`: with `none` it fails naming the setting rather than minting a URL the store would refuse.
40
+ *
41
+ * AUTHORED — CUTOVER (`storage-compatible-store`, `storage-compatible-credentials`, and the live round trip
42
+ * `storage-compatible-live`): typechecked and run with the SDK's transport replaced, never against a real store.
43
+ */
44
+ export function createCompatibleStorage(settings: CompatibleStorageSettings): StoragePort {
45
+ const { bucket, endpoint, region, accessKeyId, secretAccessKey, uploadTarget } = settings
46
+ const target = parseUploadTarget(uploadTarget)
47
+ const forcePathStyle = parseForcePathStyle(settings.forcePathStyle)
48
+ assertEndpoint(endpoint)
49
+
50
+ const s3 = createS3Storage({
51
+ bucket,
52
+ region,
53
+ endpoint,
54
+ credentials: { accessKeyId, secretAccessKey },
55
+ forcePathStyle,
56
+ // The SDK's default (since v3.729, `WHEN_SUPPORTED`) puts a CRC32 checksum on every PutObject, which stores
57
+ // older than that default can reject; Cloudflare tells R2 users to ask for checksums only where an operation
58
+ // requires one. `WHEN_REQUIRED` does that, and no more: DeleteObjects requires one, so it still carries CRC32
59
+ // and no Content-MD5, which a store that wants MD5 would refuse (the live row, `storage-compatible-live`, runs
60
+ // `delete` against the real store for that). AWS accepts both, so the `s3` choice keeps the default.
61
+ requestChecksumCalculation: 'WHEN_REQUIRED',
62
+ responseChecksumValidation: 'WHEN_REQUIRED',
63
+ })
64
+ if (target === 'post') return s3
65
+ return {
66
+ ...s3,
67
+ createUploadTarget: async () => {
68
+ throw new Error(
69
+ 'storage createUploadTarget: STORAGE_UPLOAD_TARGET=none, so this store is declared not to accept a ' +
70
+ 'presigned POST (Cloudflare R2 does not). Set STORAGE_UPLOAD_TARGET=post for a store that does, ' +
71
+ 'such as MinIO, or upload another way.',
72
+ )
73
+ },
74
+ }
75
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The run mode, read once. Everything imports it from the registry (./index.ts), which re-exports it; this module
3
+ * exists so code that must not load the registry (the request proxy, ./proxy.ts; the digest job handler,
4
+ * ../jobs/digest-email.ts, which the registry itself loads) can ask the mode without its ports and their fakes.
5
+ *
6
+ * `APP_MODE` only ever tests for `'real'`, so an older `APP_MODE=fake` still resolves to `simulated`
7
+ * and no deployed config breaks.
8
+ */
9
+ export type AppMode = 'simulated' | 'real'
10
+ export const appMode: AppMode = process.env['APP_MODE'] === 'real' ? 'real' : 'simulated'
11
+ export const isSimulated = appMode === 'simulated'
@@ -23,7 +23,7 @@ export function AppHeader({
23
23
  * products, so any fallback key here would hold whichever app was written first and render it
24
24
  * for every other app — silently, because a default that resolves is indistinguishable from a
25
25
  * default that is right. Requiring the prop moves that from a sentence in a docstring to
26
- * something the compiler checks (ADR-0012, docs/adopting.md).
26
+ * something the compiler checks (ADR-0012, docs/adopting-reference.md).
27
27
  */
28
28
  appName: ReactNode
29
29
  }) {
@@ -0,0 +1,335 @@
1
+ 'use client'
2
+
3
+ import { useTranslations } from 'next-intl'
4
+ import type { ReactNode } from 'react'
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
6
+ import type { SimulatorJobs, SimulatorMail, SimulatorSchedules, SimulatorSummary } from '../../server-lib/simulator-api'
7
+ import { sameOriginPath } from '../../core/same-origin-path'
8
+ import { SimulatorPanel, type SimulatorNotice } from './simulator-panel'
9
+
10
+ const EMPTY_SUMMARY: SimulatorSummary = { viewpoint: null, signedIn: false, people: [] }
11
+ const EMPTY_MAIL: SimulatorMail = { emails: [], mailSeenAt: null, allCount: 0 }
12
+ const EMPTY_JOBS: SimulatorJobs = { jobs: [], held: false }
13
+ const EMPTY_SCHEDULES: SimulatorSchedules = { schedules: [], clockOffsetMs: 0, worldNow: new Date(0).toISOString() }
14
+ const EXPANDED_POLL_MS = 4_000
15
+ const COLLAPSED_POLL_MS = 15_000
16
+ const NOTICE_MS = 6_000
17
+ const MAIL_SCOPE_KEY = 'app-simulator-mail-scope'
18
+ const API = '/api/simulator'
19
+
20
+ /** A POST to the server host. Always JSON, even with no body: the server refuses any other content type. */
21
+ function post(path: string, body: unknown = {}): Promise<Response> {
22
+ return fetch(`${API}/${path}`, {
23
+ method: 'POST',
24
+ headers: { 'content-type': 'application/json' },
25
+ body: JSON.stringify(body),
26
+ })
27
+ }
28
+
29
+ async function getJson<T>(path: string): Promise<T | null> {
30
+ const response = await fetch(`${API}/${path}`)
31
+ return response.ok ? ((await response.json()) as T) : null
32
+ }
33
+
34
+ /**
35
+ * Polls overlap, and their answers can arrive out of order: each fetch takes a ticket, and its answer is applied only
36
+ * when no later ticket's answer has been. A slow answer is never shown over a newer one, and, unlike "only the latest
37
+ * request's answer", answers slower than the poll still land.
38
+ */
39
+ function useTickets() {
40
+ const counts = useRef({ issued: 0, applied: 0 })
41
+ return useMemo(
42
+ () => ({
43
+ take: () => (counts.current.issued += 1),
44
+ fresh: (ticket: number) => {
45
+ if (ticket <= counts.current.applied) return false
46
+ counts.current.applied = ticket
47
+ return true
48
+ },
49
+ }),
50
+ [],
51
+ )
52
+ }
53
+
54
+ function readStoredScope(): 'person' | 'all' | null {
55
+ try {
56
+ const stored = window.localStorage.getItem(MAIL_SCOPE_KEY)
57
+ return stored === 'person' || stored === 'all' ? stored : null
58
+ } catch {
59
+ return null
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The Simulator on an app's own `pnpm dev`: the panel, fed by the kit's server host
65
+ * (`@sssb/kit/server-lib/simulator-api`, which the app mounts at `src/app/api/simulator/[...path]/route.ts`). The app's
66
+ * locale layout renders it around the page, in simulated mode only and through a dynamic import, so no page of a real
67
+ * build loads it.
68
+ *
69
+ * It wires the tabs that host serves: People (switch to anyone, signed in or not), Mail (each person's inbox, or all
70
+ * of it) and Jobs with the world clock (run what is queued, move the clock, run what is due). The panel leaves out
71
+ * every tab it is not given; the rest, the app's own tabs, presets and tours included, are later stages of the same
72
+ * host. An app that needs one of them today keeps a glue of its own instead of this component.
73
+ *
74
+ * Polling, never a stream: the summary (the pill's unread badge) on a slow beat while the panel is collapsed, and
75
+ * the open tab's data on a faster one while it is expanded. Every acknowledgement is a notice inside the panel,
76
+ * never the app's own toast.
77
+ */
78
+ export function SimulatorHost({ locale, children }: { locale: string; children: ReactNode }) {
79
+ const t = useTranslations('simulator')
80
+ const [summary, setSummary] = useState<SimulatorSummary>(EMPTY_SUMMARY)
81
+ const [expanded, setExpanded] = useState(false)
82
+ const [activeTab, setActiveTab] = useState('people')
83
+ const [mailScope, setMailScope] = useState<'person' | 'all'>('person')
84
+ const [mail, setMail] = useState<SimulatorMail>(EMPTY_MAIL)
85
+ const [jobsData, setJobsData] = useState<SimulatorJobs>(EMPTY_JOBS)
86
+ const [schedulesData, setSchedulesData] = useState<SimulatorSchedules>(EMPTY_SCHEDULES)
87
+ const [notices, setNotices] = useState<SimulatorNotice[]>([])
88
+ const noticeSeq = useRef(0)
89
+ const prevUnread = useRef<Map<string, number> | null>(null)
90
+ const summaryTickets = useTickets()
91
+ const mailTickets = useTickets()
92
+ const jobsTickets = useTickets()
93
+
94
+ const personEmail = summary.people.find((person) => person.key === summary.viewpoint)?.email ?? null
95
+ // Signed out, or no viewpoint yet: there is no one's own inbox to show, so the scope is every inbox.
96
+ const effectiveMailScope: 'person' | 'all' = personEmail ? mailScope : 'all'
97
+ const mailQuery = effectiveMailScope === 'all' ? 'all=1' : `person=${encodeURIComponent(summary.viewpoint ?? '')}`
98
+ // The scope this render shows. An answer for another scope is dropped even when it is the newest to arrive: the
99
+ // summary's first answer turns "all" into one person's inbox, and an action's callback can hold an older render's
100
+ // fetch.
101
+ const shownMailQuery = useRef(mailQuery)
102
+ useEffect(() => {
103
+ shownMailQuery.current = mailQuery
104
+ }, [mailQuery])
105
+
106
+ const pushNotice = useCallback((text: string) => {
107
+ const id = (noticeSeq.current += 1)
108
+ setNotices((prev) => [...prev, { id, text }])
109
+ setTimeout(() => setNotices((prev) => prev.filter((notice) => notice.id !== id)), NOTICE_MS)
110
+ }, [])
111
+
112
+ const refresh = useCallback(async () => {
113
+ const ticket = summaryTickets.take()
114
+ const next = await getJson<SimulatorSummary>('summary')
115
+ if (!next || !summaryTickets.fresh(ticket)) return
116
+ setSummary(next)
117
+ // New mail since the last poll gets a notice; the first load has nothing "new".
118
+ if (prevUnread.current) {
119
+ for (const person of next.people) {
120
+ const before = prevUnread.current.get(person.key) ?? 0
121
+ if (person.unreadMail > before) pushNotice(t('noticeNewMail', { email: person.email }))
122
+ }
123
+ }
124
+ prevUnread.current = new Map(next.people.map((person) => [person.key, person.unreadMail]))
125
+ }, [pushNotice, t, summaryTickets])
126
+
127
+ const refreshMail = useCallback(async () => {
128
+ const ticket = mailTickets.take()
129
+ const next = await getJson<SimulatorMail>(`mail?${mailQuery}`)
130
+ if (next && mailQuery === shownMailQuery.current && mailTickets.fresh(ticket)) setMail(next)
131
+ }, [mailQuery, mailTickets])
132
+
133
+ const refreshJobs = useCallback(async () => {
134
+ const ticket = jobsTickets.take()
135
+ const [nextJobs, nextSchedules] = await Promise.all([
136
+ getJson<SimulatorJobs>('jobs'),
137
+ getJson<SimulatorSchedules>('schedules'),
138
+ ])
139
+ if (!nextJobs || !nextSchedules || !jobsTickets.fresh(ticket)) return
140
+ setJobsData(nextJobs)
141
+ setSchedulesData(nextSchedules)
142
+ }, [jobsTickets])
143
+
144
+ /** The open tab's own data, when the panel is expanded. */
145
+ const refreshOpenTab = useCallback(() => {
146
+ if (!expanded) return
147
+ if (activeTab === 'mail') void refreshMail()
148
+ if (activeTab === 'jobs') void refreshJobs()
149
+ }, [expanded, activeTab, refreshMail, refreshJobs])
150
+
151
+ useEffect(() => {
152
+ // Fetch on mount, and restore the remembered mail scope: syncing with external systems (the server, the
153
+ // browser's storage), which is what setting state from an effect is for.
154
+ // eslint-disable-next-line react-hooks/set-state-in-effect
155
+ void refresh()
156
+ const storedScope = readStoredScope()
157
+ if (storedScope) setMailScope(storedScope)
158
+ // Mount-only.
159
+ // eslint-disable-next-line react-hooks/exhaustive-deps
160
+ }, [])
161
+
162
+ useEffect(() => {
163
+ const id = setInterval(
164
+ () => {
165
+ void refresh()
166
+ refreshOpenTab()
167
+ },
168
+ expanded ? EXPANDED_POLL_MS : COLLAPSED_POLL_MS,
169
+ )
170
+ return () => clearInterval(id)
171
+ }, [expanded, refresh, refreshOpenTab])
172
+
173
+ useEffect(() => {
174
+ // A tab that opens (or a mail scope that changes) fetches at once rather than on the next poll: the state is
175
+ // set when the server answers, the same external-system sync as the mount effect.
176
+ // eslint-disable-next-line react-hooks/set-state-in-effect
177
+ refreshOpenTab()
178
+ }, [refreshOpenTab])
179
+
180
+ function handleSelect(person: string) {
181
+ void post('viewpoint', { person, locale }).then(async (response) => {
182
+ if (!response.ok) return
183
+ const { redirectTo } = (await response.json()) as { redirectTo: unknown }
184
+ // A full reload: the theme and the header are per-user server output. Only ever to a path on this origin:
185
+ // the server answers no other, and this is the client's own check.
186
+ const path = sameOriginPath(redirectTo)
187
+ if (path) window.location.assign(path)
188
+ })
189
+ }
190
+
191
+ function handleMailSeen() {
192
+ if (!summary.viewpoint) return
193
+ void post('mail/seen', { person: summary.viewpoint }).then((response) => {
194
+ if (response.ok) void refresh()
195
+ })
196
+ }
197
+
198
+ function handleScopeChange(scope: 'person' | 'all') {
199
+ setMailScope(scope)
200
+ try {
201
+ window.localStorage.setItem(MAIL_SCOPE_KEY, scope)
202
+ } catch {
203
+ // No storage (a private window, say): the scope lasts for this page only.
204
+ }
205
+ }
206
+
207
+ function handleOpenLink(href: string) {
208
+ // Same origin only, and never silently. A path is followed; so is an absolute URL on this origin, since a real
209
+ // email carries one. Both go through `sameOriginPath`, which refuses what a browser would read as another
210
+ // origin (`/\host`, a tab inside). A protocol-relative `//host` link is resolved against this page, so it is
211
+ // judged by its host like any absolute URL; one with no origin at all (`mailto:`) is unusable here.
212
+ const path = sameOriginPath(href)
213
+ if (path) {
214
+ window.location.assign(path)
215
+ return
216
+ }
217
+ try {
218
+ const url = href.startsWith('//') ? new URL(href, window.location.href) : new URL(href)
219
+ const local =
220
+ url.origin === window.location.origin ? sameOriginPath(url.pathname + url.search + url.hash) : null
221
+ if (local) {
222
+ window.location.assign(local)
223
+ return
224
+ }
225
+ if (url.origin === window.location.origin || url.origin === 'null') {
226
+ pushNotice(t('noticeLinkUnusable', { href }))
227
+ } else {
228
+ pushNotice(t('noticeLinkOrigin', { origin: url.origin }))
229
+ }
230
+ } catch {
231
+ pushNotice(t('noticeLinkUnusable', { href }))
232
+ }
233
+ }
234
+
235
+ function handleCopyLink(href: string) {
236
+ void navigator.clipboard
237
+ .writeText(href)
238
+ .then(() => pushNotice(t('noticeLinkCopied')))
239
+ .catch(() => pushNotice(t('noticeLinkCopyFailed')))
240
+ }
241
+
242
+ function handleClearMail() {
243
+ void post('mail/clear').then((response) => {
244
+ if (!response.ok) return
245
+ void refreshMail()
246
+ void refresh()
247
+ pushNotice(t('noticeMailCleared'))
248
+ })
249
+ }
250
+
251
+ async function handleRunPending() {
252
+ const response = await post('jobs/run-pending')
253
+ if (!response.ok) return
254
+ const { ran } = (await response.json()) as { ran: number }
255
+ await refreshJobs()
256
+ pushNotice(t('noticeJobsRan', { count: ran }))
257
+ }
258
+
259
+ /** After the clock moved or due work ran: the schedules, the jobs a schedule spawned, and any mail they sent. */
260
+ async function afterSchedulesChanged(response: Response, moved: 'advanced' | 'reset' | null) {
261
+ if (!response.ok) return
262
+ const { spawned } = (await response.json()) as { spawned: number }
263
+ await Promise.all([refreshJobs(), refresh()])
264
+ if (spawned > 0) pushNotice(t('noticeScheduleFired', { count: spawned }))
265
+ else if (moved === 'advanced') pushNotice(t('noticeClockAdvanced'))
266
+ else if (moved === 'reset') pushNotice(t('noticeClockReset'))
267
+ else pushNotice(t('noticeNoDue'))
268
+ }
269
+
270
+ async function handleAdvanceClock(deltaMs: number) {
271
+ await afterSchedulesChanged(await post('clock', { action: 'advance', deltaMs }), 'advanced')
272
+ }
273
+
274
+ async function handleResetClock() {
275
+ await afterSchedulesChanged(await post('clock', { action: 'reset' }), 'reset')
276
+ }
277
+
278
+ async function handleRunDue() {
279
+ await afterSchedulesChanged(await post('schedules/run-due'), null)
280
+ }
281
+
282
+ function handleLocaleChange(next: string) {
283
+ if (next === locale) return
284
+ // Swap the leading /<locale> segment and reload the same page: the theme and the header are per-request
285
+ // server output, so a client navigation would not re-render them.
286
+ const { pathname, search, hash } = window.location
287
+ const swapped = pathname.replace(new RegExp(`^/${locale}(?=/|$)`), `/${next}`) + search + hash
288
+ window.location.assign(sameOriginPath(swapped) ?? `/${next}`)
289
+ }
290
+
291
+ return (
292
+ <div style={{ display: 'flex', minHeight: '100vh', alignItems: 'stretch' }}>
293
+ <div style={{ flex: 1, minWidth: 0 }}>{children}</div>
294
+ <SimulatorPanel
295
+ people={summary.people}
296
+ viewpoint={summary.viewpoint}
297
+ signedIn={summary.signedIn}
298
+ onSelect={handleSelect}
299
+ onRefresh={refresh}
300
+ onExpandedChange={(value) => {
301
+ setExpanded(value)
302
+ if (value) void refresh()
303
+ }}
304
+ onTabChange={setActiveTab}
305
+ onLocaleChange={handleLocaleChange}
306
+ notices={notices}
307
+ mail={{
308
+ emails: mail.emails,
309
+ scope: effectiveMailScope,
310
+ onScopeChange: handleScopeChange,
311
+ personEmail,
312
+ mailSeenAt: mail.mailSeenAt,
313
+ allCount: mail.allCount,
314
+ onOpenLink: handleOpenLink,
315
+ onSeen: handleMailSeen,
316
+ onClear: handleClearMail,
317
+ onCopyLink: handleCopyLink,
318
+ }}
319
+ jobs={{
320
+ jobs: jobsData.jobs,
321
+ held: jobsData.held,
322
+ onRunPending: handleRunPending,
323
+ schedules: schedulesData.schedules,
324
+ clock: {
325
+ offsetMs: schedulesData.clockOffsetMs,
326
+ worldNow: schedulesData.worldNow,
327
+ onAdvance: handleAdvanceClock,
328
+ onReset: handleResetClock,
329
+ onRunDue: handleRunDue,
330
+ },
331
+ }}
332
+ />
333
+ </div>
334
+ )
335
+ }
@@ -24,21 +24,6 @@ const WIDTH_KEY = 'app-simulator-width'
24
24
  const TAB_KEY = 'app-simulator-tab'
25
25
  const COACH_KEY = 'app-simulator-coach-dismissed'
26
26
 
27
- // The panel's OWN (framework) tabs — one per subsystem. App tabs arrive via `extraTabs` and slot in
28
- // between Hooks and Errors; the active tab is therefore a plain string (a core id OR an extra id).
29
- type SimulatorTab = 'people' | 'mail' | 'messages' | 'events' | 'jobs' | 'hooks' | 'errors' | 'snapshots' | 'tours'
30
- const CORE_TAB_IDS: SimulatorTab[] = [
31
- 'people',
32
- 'mail',
33
- 'messages',
34
- 'events',
35
- 'jobs',
36
- 'hooks',
37
- 'errors',
38
- 'snapshots',
39
- 'tours',
40
- ]
41
-
42
27
  /** One app-registered tab, composed by the host (label already translated, content already built). */
43
28
  export interface SimulatorExtraTab {
44
29
  id: string
@@ -154,12 +139,12 @@ export interface HooksAppProps {
154
139
  * The Simulator panel (ADR-0006 twin lives in @sssb/kit/demo-static): collapsed = a small fixed pill (no
155
140
  * layout shift); expanded = a right-docked column with its own dark skin so it reads as "not the
156
141
  * product". The column is sticky so it stays docked while long pages scroll. Router-agnostic —
157
- * navigation happens via `onSelect`/mail's `onOpenLink`, data arrives as props; the glue
158
- * (src/app/[locale]/simulator-glue.tsx) owns fetching and polling. Tab strip:
142
+ * navigation happens via `onSelect`/mail's `onOpenLink`, data arrives as props; the host owns fetching and polling
143
+ * (the kit's own server host, ./simulator-host, an app's own glue, or the static demo's shell). Tab strip:
159
144
  * People / Mail / Messages / Events / Jobs / Hooks / …host `extraTabs`… / Errors / Snapshots / Tours —
160
- * `data-testid="simulator-tab-<id>"`. App tabs are registered on the seam (@sssb/app-config/simulator)
161
- * and composed by the host into `extraTabs`, slotted in between Hooks and Errors so the panel itself
162
- * knows nothing of app content. Transient
145
+ * `data-testid="simulator-tab-<id>"`, each tab but People present only when the host passes its props. App tabs are
146
+ * registered on the seam (@sssb/app-config/simulator) and composed by the host into `extraTabs`, slotted in between
147
+ * Hooks and Errors so the panel itself knows nothing of app content. Transient
163
148
  * feedback stays inside simulator: a notice overlay anchored at the panel's bottom edge when
164
149
  * expanded (absolute, so it never shifts the scroll body), a pulsing unread badge on the pill when
165
150
  * collapsed — never app-level toasts that could collide with future product ones. The header shows
@@ -181,7 +166,7 @@ export function SimulatorPanel({
181
166
  audit,
182
167
  jobs,
183
168
  hooks,
184
- extraTabs,
169
+ extraTabs = [],
185
170
  runServerErrorScenario,
186
171
  snapshots,
187
172
  tours,
@@ -198,20 +183,22 @@ export function SimulatorPanel({
198
183
  /** When provided, the header shows a locale switcher — the host owns what switching does (a
199
184
  * full reload in the real app, in-memory state in the static demo). */
200
185
  onLocaleChange?: (locale: string) => void
201
- mail: MailAppProps
186
+ // Every tab but People exists only when the host wires it: a host that serves a subset of the subsystems (the
187
+ // kit's own server host, ./simulator-host) leaves the rest out, and their tabs are not shown at all.
188
+ mail?: MailAppProps | undefined
202
189
  /** Inbound email: the Mail tab's "compose inbound" affordance + world inbound list. */
203
- inbound: InboundAppProps
204
- messages: SmsMessageRow[]
205
- events: AnalyticsEvent[]
190
+ inbound?: InboundAppProps | undefined
191
+ messages?: SmsMessageRow[] | undefined
192
+ events?: AnalyticsEvent[] | undefined
206
193
  /** Compliance-grade audit trail, rendered read-only beneath the analytics events. */
207
- audit: AuditEntry[]
208
- jobs: JobsAppProps
209
- hooks: HooksAppProps
194
+ audit?: AuditEntry[] | undefined
195
+ jobs?: JobsAppProps | undefined
196
+ hooks?: HooksAppProps | undefined
210
197
  /** App-registered tabs (@sssb/app-config/simulator), composed by the host. Rendered between Hooks and
211
198
  * Errors — visual order and the `simulator-tab-<id>` testid derive from each tab's id. */
212
- extraTabs: SimulatorExtraTab[]
213
- runServerErrorScenario: () => Promise<ScrubResult>
214
- snapshots: SnapshotsAppProps
199
+ extraTabs?: SimulatorExtraTab[] | undefined
200
+ runServerErrorScenario?: (() => Promise<ScrubResult>) | undefined
201
+ snapshots?: SnapshotsAppProps | undefined
215
202
  /** Scripted walkthroughs (@sssb/kit/demo-static/tour/use-tours). Undefined when the app registers no
216
203
  * tours — the tab then doesn't exist at all, which is the off-switch an adopter gets for free. */
217
204
  tours?: ToursAppProps | undefined
@@ -255,6 +242,22 @@ export function SimulatorPanel({
255
242
  // A core tab's content shows only in an expanded panel (the hidden kept-alive panel holds nothing else).
256
243
  const showing = (tab: string) => !collapsed && activeTab === tab
257
244
 
245
+ // Host `extraTabs` slot in between Hooks and Errors — where Actors sat when it was hard-coded — so
246
+ // visual order and the `simulator-tab-<id>` testids are preserved as app tabs register.
247
+ const tabs: { id: string; label: string }[] = [
248
+ { id: 'people', label: t('peopleTab') },
249
+ ...(mail ? [{ id: 'mail', label: t('mailTab') }] : []),
250
+ ...(messages ? [{ id: 'messages', label: t('messagesTab') }] : []),
251
+ ...(events ? [{ id: 'events', label: t('eventsTab') }] : []),
252
+ ...(jobs ? [{ id: 'jobs', label: t('jobsTab') }] : []),
253
+ ...(hooks ? [{ id: 'hooks', label: t('hooksTab') }] : []),
254
+ ...extraTabs.map((tab) => ({ id: tab.id, label: tab.label })),
255
+ ...(runServerErrorScenario ? [{ id: 'errors', label: t('errorsTab') }] : []),
256
+ ...(snapshots ? [{ id: 'snapshots', label: t('snapshotsTab') }] : []),
257
+ // Tours sits beside Snapshots (state and narrative, in that order) and only when the app has any.
258
+ ...(tours ? [{ id: 'tours', label: t('toursTab') }] : []),
259
+ ]
260
+
258
261
  const totalUnread = people.reduce((sum, person) => sum + person.unreadMail, 0)
259
262
  const badgeRef = useRef<HTMLDivElement | null>(null)
260
263
  // Focus follows a toggle (WCAG 2.4.3): the control the user pressed unmounts (the pill) or is hidden with the panel
@@ -269,8 +272,9 @@ export function SimulatorPanel({
269
272
  // Reading localStorage is an external-system sync (SSR has none), so this legitimately
270
273
  // sets state from an effect rather than during render.
271
274
  const storedCollapsed = readStoredCollapsed()
272
- // Core ids ∪ the host's extra-tab ids — a persisted app tab must survive reload.
273
- const storedTab = readStoredTab([...CORE_TAB_IDS, ...extraTabs.map((tab) => tab.id)])
275
+ // The tabs this host wires (core and extra): a persisted app tab survives a reload, and one this host
276
+ // does not show falls back to People.
277
+ const storedTab = readStoredTab(tabs.map((tab) => tab.id))
274
278
  // eslint-disable-next-line react-hooks/set-state-in-effect
275
279
  setCollapsed(storedCollapsed)
276
280
  setWidth(readStoredWidth())
@@ -481,22 +485,6 @@ export function SimulatorPanel({
481
485
  </>
482
486
  ) : null
483
487
 
484
- // Host `extraTabs` slot in between Hooks and Errors — where Actors sat when it was hard-coded — so
485
- // visual order and the `simulator-tab-<id>` testids are preserved as app tabs register.
486
- const tabs: { id: string; label: string }[] = [
487
- { id: 'people', label: t('peopleTab') },
488
- { id: 'mail', label: t('mailTab') },
489
- { id: 'messages', label: t('messagesTab') },
490
- { id: 'events', label: t('eventsTab') },
491
- { id: 'jobs', label: t('jobsTab') },
492
- { id: 'hooks', label: t('hooksTab') },
493
- ...extraTabs.map((tab) => ({ id: tab.id, label: tab.label })),
494
- { id: 'errors', label: t('errorsTab') },
495
- { id: 'snapshots', label: t('snapshotsTab') },
496
- // Tours sits beside Snapshots (state and narrative, in that order) and only when the app has any.
497
- ...(tours ? [{ id: 'tours', label: t('toursTab') }] : []),
498
- ]
499
-
500
488
  // The person the panel is currently "watching" — powers the header chip so it's always clear
501
489
  // whose world this is, even before switching tabs.
502
490
  const person = people.find((person) => person.key === viewpoint) ?? null
@@ -652,16 +640,16 @@ export function SimulatorPanel({
652
640
  <PeopleApp people={people} viewpoint={viewpoint} onSelect={onSelect} />
653
641
  </>
654
642
  ) : null}
655
- {showing('mail') ? (
643
+ {showing('mail') && mail ? (
656
644
  <Stack gap="lg">
657
- <InboundApp {...inbound} />
645
+ {inbound ? <InboundApp {...inbound} /> : null}
658
646
  <MailApp {...mail} />
659
647
  </Stack>
660
648
  ) : null}
661
- {showing('events') ? <EventsApp events={events} audit={audit} /> : null}
662
- {showing('jobs') ? <JobsApp {...jobs} /> : null}
663
- {showing('messages') ? <MessagesApp messages={messages} /> : null}
664
- {showing('hooks') ? <HooksApp {...hooks} /> : null}
649
+ {showing('events') && events ? <EventsApp events={events} audit={audit ?? []} /> : null}
650
+ {showing('jobs') && jobs ? <JobsApp {...jobs} /> : null}
651
+ {showing('messages') && messages ? <MessagesApp messages={messages} /> : null}
652
+ {showing('hooks') && hooks ? <HooksApp {...hooks} /> : null}
665
653
  {/* App tabs render their host-built content here (between Hooks and Errors). An ordinary
666
654
  tab's live content (iframe / mounted node) unmounts with it; a keepMounted one is there
667
655
  from page load, stays put, and is only hidden (./tab-mount). */}
@@ -673,12 +661,12 @@ export function SimulatorPanel({
673
661
  </Box>
674
662
  )
675
663
  })}
676
- {showing('errors') ? (
664
+ {showing('errors') && runServerErrorScenario ? (
677
665
  <Box style={lightBoxStyle}>
678
666
  <ErrorsApp runServerScenario={runServerErrorScenario} />
679
667
  </Box>
680
668
  ) : null}
681
- {showing('snapshots') ? <SnapshotsApp {...snapshots} /> : null}
669
+ {showing('snapshots') && snapshots ? <SnapshotsApp {...snapshots} /> : null}
682
670
  {showing('tours') && tours ? <ToursApp {...tours} /> : null}
683
671
  </Box>
684
672
  {/* Notices overlay the panel's bottom edge (absolute, not in flow) so a transient
@@ -62,7 +62,12 @@ type BaseSubjectType =
62
62
  /** The full subject union: framework base + the app's registered subjects (src/app-config/abilities.ts). */
63
63
  export type SubjectType = BaseSubjectType | AppSubjectType
64
64
 
65
- export interface AbilitySubject extends AppSubjectFields {
65
+ /**
66
+ * The subject an ability is checked against: the shape below, with the app's own fields (`AppSubjectFields`) intersected in.
67
+ * An INTERSECTION, not an `interface extends`, so the app may declare those fields as an interface, a type alias or a mapped type, and
68
+ * an app with none writes `Record<never, never>` rather than an empty interface it must silence the linter for.
69
+ */
70
+ export type AbilitySubject = AppSubjectFields & {
66
71
  type: SubjectType
67
72
  /** The org the subject lives in. `null`/absent means "not org-scoped" and never satisfies sameOrg. */
68
73
  orgId?: string | null