@sssb/kit 0.0.0 → 0.2.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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,210 @@
1
+ 'use client'
2
+
3
+ import { Box, Button, Group, NativeSelect, Stack, Text, TextInput, Textarea } from '@mantine/core'
4
+ import { useLocale, useTranslations } from 'next-intl'
5
+ import { useState } from 'react'
6
+ import { chipStyle } from './people-app'
7
+ import { formatWhen } from './format-when'
8
+
9
+ /** One inbound message as the Simulator world view sees it (packages/kit/src/db/inbound-email.ts WorldInboundEmail). */
10
+ export interface InboundEmailRow {
11
+ id: string
12
+ toEmail: string
13
+ fromEmail: string
14
+ subject: string
15
+ status: string
16
+ handler: string | null
17
+ error: string | null
18
+ createdAt: string
19
+ tenantSlug: string
20
+ orgSlug: string | null
21
+ }
22
+
23
+ export interface InboundComposeInput {
24
+ from: string
25
+ orgSlug: string
26
+ handler: string
27
+ subject: string
28
+ body: string
29
+ }
30
+
31
+ export interface InboundAppProps {
32
+ inbound: InboundEmailRow[]
33
+ orgs: { slug: string; name: string; tenantSlug: string }[]
34
+ people: { email: string; name: string }[]
35
+ handlers: string[]
36
+ domain: string
37
+ onCompose: (input: InboundComposeInput) => void
38
+ }
39
+
40
+ /** Mantine text colour cue per intake status (the jobs-app/hooks-app chip pattern — a `.4` shade on
41
+ * the dark panel meets AA, unlike a white-on-fill Badge; presentational only). */
42
+ function statusColor(status: string): string {
43
+ switch (status) {
44
+ case 'handled':
45
+ return 'teal.4'
46
+ case 'unmatched':
47
+ return 'yellow.4'
48
+ case 'failed':
49
+ return 'red.4'
50
+ default:
51
+ return 'gray.4'
52
+ }
53
+ }
54
+
55
+ /**
56
+ * The Mail tab's "compose inbound" affordance + inbound list: the world emails the app. Data
57
+ * and callbacks only — the glue (simulator-glue.tsx) owns fetching and the POST, and the static-demo
58
+ * twin drives the same props over its in-memory intake. Native <select>s (not Mantine comboboxes) keep
59
+ * the compose form trivially Playwright-selectable. The handler is a free-text field so an unknown slug
60
+ * can be sent on purpose to demonstrate the 'unmatched' path.
61
+ */
62
+ export function InboundApp({ inbound, orgs, people, handlers, domain, onCompose }: InboundAppProps) {
63
+ const t = useTranslations('simulator')
64
+ const locale = useLocale()
65
+ const [from, setFrom] = useState('')
66
+ const [orgSlug, setOrgSlug] = useState('')
67
+ const [handler, setHandler] = useState('note')
68
+ const [subject, setSubject] = useState('')
69
+ const [body, setBody] = useState('')
70
+
71
+ const effectiveFrom = from || people[0]?.email || ''
72
+ const effectiveOrg = orgSlug || orgs[0]?.slug || ''
73
+ const address = effectiveOrg && handler ? `${effectiveOrg}+${handler}@${domain}` : ''
74
+ const canSend = Boolean(effectiveFrom && effectiveOrg && handler.trim())
75
+
76
+ function send() {
77
+ if (!canSend) return
78
+ onCompose({ from: effectiveFrom, orgSlug: effectiveOrg, handler: handler.trim(), subject, body })
79
+ setSubject('')
80
+ setBody('')
81
+ }
82
+
83
+ return (
84
+ <Stack gap="md" data-testid="simulator-inbound">
85
+ <Box
86
+ data-testid="inbound-compose"
87
+ style={{ border: '1px solid rgba(255,255,255,0.2)', borderRadius: 8, padding: 10 }}
88
+ >
89
+ <Stack gap="xs">
90
+ <Text size="sm" fw={700} c="gray.1">
91
+ {t('inboundComposeHeading')}
92
+ </Text>
93
+ <Text size="xs" c="gray.5">
94
+ {t('inboundComposeHint')}
95
+ </Text>
96
+ <NativeSelect
97
+ size="xs"
98
+ data-testid="inbound-compose-from"
99
+ label={t('inboundFromLabel')}
100
+ value={effectiveFrom}
101
+ onChange={(event) => setFrom(event.currentTarget.value)}
102
+ data={people.map((person) => ({
103
+ value: person.email,
104
+ label: `${person.name} (${person.email})`,
105
+ }))}
106
+ />
107
+ <Group grow gap="xs">
108
+ <NativeSelect
109
+ size="xs"
110
+ data-testid="inbound-compose-org"
111
+ label={t('inboundOrgLabel')}
112
+ value={effectiveOrg}
113
+ onChange={(event) => setOrgSlug(event.currentTarget.value)}
114
+ data={orgs.map((org) => ({
115
+ value: org.slug,
116
+ label: `${org.name} (${org.tenantSlug})`,
117
+ }))}
118
+ />
119
+ <TextInput
120
+ size="xs"
121
+ data-testid="inbound-compose-handler"
122
+ label={t('inboundHandlerLabel')}
123
+ value={handler}
124
+ onChange={(event) => setHandler(event.currentTarget.value)}
125
+ />
126
+ </Group>
127
+ <Text size="xs" c="gray.6" data-testid="inbound-compose-address">
128
+ {t('inboundAddressPreview', { address })}
129
+ </Text>
130
+ <Text size="xs" c="gray.6">
131
+ {t('inboundHandlersHint', { handlers: handlers.join(', ') })}
132
+ </Text>
133
+ <TextInput
134
+ size="xs"
135
+ data-testid="inbound-compose-subject"
136
+ label={t('inboundSubjectLabel')}
137
+ value={subject}
138
+ onChange={(event) => setSubject(event.currentTarget.value)}
139
+ />
140
+ <Textarea
141
+ size="xs"
142
+ data-testid="inbound-compose-body"
143
+ label={t('inboundBodyLabel')}
144
+ autosize
145
+ minRows={2}
146
+ value={body}
147
+ onChange={(event) => setBody(event.currentTarget.value)}
148
+ />
149
+ <Group justify="flex-end">
150
+ <Button size="compact-sm" data-testid="inbound-compose-send" disabled={!canSend} onClick={send}>
151
+ {t('inboundSendButton')}
152
+ </Button>
153
+ </Group>
154
+ </Stack>
155
+ </Box>
156
+
157
+ <Stack gap={4}>
158
+ <Text size="sm" fw={700} c="gray.1">
159
+ {t('inboundListHeading')}
160
+ </Text>
161
+ {inbound.length === 0 ? (
162
+ <Text size="xs" c="gray.5" data-testid="inbound-empty">
163
+ {t('inboundEmpty')}
164
+ </Text>
165
+ ) : (
166
+ <Stack gap={0} data-testid="inbound-list">
167
+ {inbound.map((item) => (
168
+ <Box
169
+ key={item.id}
170
+ data-testid={`inbound-item-${item.id}`}
171
+ style={{ borderBottom: '1px solid rgba(255,255,255,0.12)', padding: '6px 4px' }}
172
+ >
173
+ <Group justify="space-between" wrap="nowrap" gap="xs">
174
+ <Text size="sm" c="gray.0" truncate style={{ minWidth: 0 }}>
175
+ {item.subject || t('inboundNoSubject')}
176
+ </Text>
177
+ <Group gap={6} wrap="nowrap">
178
+ <Text
179
+ size="xs"
180
+ fw={700}
181
+ c={statusColor(item.status)}
182
+ style={chipStyle}
183
+ data-testid={`inbound-status-${item.id}`}
184
+ >
185
+ {t(`inboundStatus_${item.status}` as 'inboundStatus_handled')}
186
+ </Text>
187
+ <Text size="xs" c="gray.6" style={{ whiteSpace: 'nowrap' }}>
188
+ {formatWhen(item.createdAt, locale)}
189
+ </Text>
190
+ </Group>
191
+ </Group>
192
+ <Text size="xs" c="gray.5" truncate>
193
+ {t('inboundMetaLine', {
194
+ to: item.toEmail,
195
+ from: item.fromEmail,
196
+ })}
197
+ </Text>
198
+ {item.error ? (
199
+ <Text size="xs" c="yellow.6" truncate>
200
+ {t('inboundErrorLine', { error: item.error })}
201
+ </Text>
202
+ ) : null}
203
+ </Box>
204
+ ))}
205
+ </Stack>
206
+ )}
207
+ </Stack>
208
+ </Stack>
209
+ )
210
+ }
@@ -0,0 +1,471 @@
1
+ 'use client'
2
+
3
+ import { Box, Group, Stack, Text, TextInput, UnstyledButton } from '@mantine/core'
4
+ import { useLocale, useTranslations } from 'next-intl'
5
+ import { useState } from 'react'
6
+ import type { ScheduleSpec } from '../../core/schedules'
7
+ import { JobTimeline, type JobTimelineItem } from '../job-timeline'
8
+ import { chipStyle } from './people-app'
9
+ import { formatWhen } from './format-when'
10
+
11
+ /** Local prop shape (never import the adapter's WorldJob into components) — the world view of a job,
12
+ * joined to its tenant/org slugs, as the Jobs tab needs to render it. */
13
+ export interface WorldJobLike {
14
+ id: string
15
+ kind: string
16
+ status: string
17
+ tenantSlug: string
18
+ orgSlug: string | null
19
+ createdAt: string
20
+ error?: string | null
21
+ timeline: JobTimelineItem[]
22
+ }
23
+
24
+ /** A schedule as the Jobs tab renders it (local shape, decoupled from packages/kit/src/db's WorldSchedule). */
25
+ export interface ScheduleRowLike {
26
+ id: string
27
+ kind: string
28
+ spec: ScheduleSpec
29
+ nextRunAt: string
30
+ enabled: boolean
31
+ tenantSlug: string
32
+ orgSlug: string
33
+ }
34
+
35
+ /** The simulated world-clock control surface, wired by the host (real glue / static twin). */
36
+ export interface WorldClockLike {
37
+ /** Current offset ahead of real time, in ms (0 = real time). */
38
+ offsetMs: number
39
+ /** The world's current instant (real time + offset), ISO. */
40
+ worldNow: string
41
+ /** Advance the clock forward by the given ms, then drain due schedules. */
42
+ onAdvance: (deltaMs: number) => void | Promise<void>
43
+ /** Back to real time. */
44
+ onReset: () => void | Promise<void>
45
+ /** Drain due schedules at the current world clock without moving it. */
46
+ onRunDue: () => void | Promise<void>
47
+ }
48
+
49
+ /**
50
+ * The dev ticker, wired by the real glue only, and only when the dev server answers for it (a simulated `next dev`;
51
+ * never a production build, the demo, e2e or the static twin, which has no server). `running`..`lastError` are the
52
+ * ticker's own status (@sssb/tools/ticker); `elsewhere` is a ticker this panel did not start, live on the same world.
53
+ */
54
+ export interface DevTickerLike {
55
+ running: boolean
56
+ /** The interval while running (and the last one used, after a stop). */
57
+ seconds: number | null
58
+ ticks: number
59
+ lastTickAt: string | null
60
+ lastError: string | null
61
+ elsewhere: { pid: number; seconds: number } | null
62
+ minSeconds: number
63
+ maxSeconds: number
64
+ defaultSeconds: number
65
+ onStart: (seconds: number) => void | Promise<void>
66
+ onStop: () => void | Promise<void>
67
+ }
68
+
69
+ const MS_PER_HOUR = 3_600_000
70
+ const MS_PER_DAY = 86_400_000
71
+ const MS_PER_WEEK = 7 * MS_PER_DAY
72
+
73
+ const runButtonStyle = {
74
+ fontSize: 12,
75
+ fontWeight: 600,
76
+ color: '#f8f9fa',
77
+ border: '1px solid #373a40',
78
+ borderRadius: 6,
79
+ padding: '4px 10px',
80
+ } as const
81
+
82
+ const sectionStyle = {
83
+ border: '1px solid rgba(255,255,255,0.18)',
84
+ borderRadius: 8,
85
+ padding: 10,
86
+ } as const
87
+
88
+ /** Mantine text colour cue per status — presentational only, the chip label stays the raw enum. */
89
+ function statusColor(status: string): string {
90
+ switch (status) {
91
+ case 'completed':
92
+ return 'teal.4'
93
+ case 'running':
94
+ return 'blue.4'
95
+ case 'failed':
96
+ return 'red.4'
97
+ default:
98
+ return 'gray.4'
99
+ }
100
+ }
101
+
102
+ /** Localized one-line summary of a schedule's timing rule. UTC throughout (see packages/kit/src/core/schedules). */
103
+ function ScheduleSpecSummary({ spec }: { spec: ScheduleSpec }) {
104
+ const t = useTranslations('simulator')
105
+ if (spec.type === 'interval') return <>{t('scheduleInterval', { minutes: spec.everyMinutes })}</>
106
+ const time = `${String(spec.atUtcHour).padStart(2, '0')}:${String(spec.atUtcMinute).padStart(2, '0')}`
107
+ if (spec.type === 'daily') return <>{t('scheduleDaily', { time })}</>
108
+ // Weekday names are seven literal keys so the lookup typechecks without a dynamic key.
109
+ const weekday =
110
+ [t('weekday0'), t('weekday1'), t('weekday2'), t('weekday3'), t('weekday4'), t('weekday5'), t('weekday6')][
111
+ spec.utcDay
112
+ ] ?? ''
113
+ return <>{t('scheduleWeekly', { weekday, time })}</>
114
+ }
115
+
116
+ /**
117
+ * The world-clock control block: shows how far ahead of real time the demo has advanced, and offers
118
+ * "advance +1h / +1d / +1w" (each also drains due schedules), "run due now" (drain without moving),
119
+ * and "reset clock". All buttons share one busy latch so a click can't race the refetch.
120
+ */
121
+ function WorldClock({ clock }: { clock: WorldClockLike }) {
122
+ const t = useTranslations('simulator')
123
+ const locale = useLocale()
124
+ const [busy, setBusy] = useState(false)
125
+
126
+ const run = (action: () => void | Promise<void>) => {
127
+ setBusy(true)
128
+ void Promise.resolve(action()).finally(() => setBusy(false))
129
+ }
130
+
131
+ const hoursAhead = Math.round(clock.offsetMs / MS_PER_HOUR)
132
+
133
+ return (
134
+ <Box style={sectionStyle} data-testid="simulator-clock">
135
+ <Text size="xs" fw={700} c="gray.0" mb={6}>
136
+ {t('clockTitle')}
137
+ </Text>
138
+ <Text size="xs" c="gray.4" data-testid="simulator-clock-now">
139
+ {formatWhen(clock.worldNow, locale)}
140
+ </Text>
141
+ <Text size="xs" c={clock.offsetMs > 0 ? 'yellow.4' : 'gray.5'} mb={8} data-testid="simulator-clock-offset">
142
+ {clock.offsetMs > 0 ? t('clockAhead', { hours: hoursAhead }) : t('clockRealTime')}
143
+ </Text>
144
+ <Group gap={6} wrap="wrap">
145
+ <UnstyledButton
146
+ data-testid="simulator-clock-advance-hour"
147
+ disabled={busy}
148
+ onClick={() => run(() => clock.onAdvance(MS_PER_HOUR))}
149
+ style={{ ...runButtonStyle, opacity: busy ? 0.6 : 1 }}
150
+ >
151
+ {t('clockAdvanceHour')}
152
+ </UnstyledButton>
153
+ <UnstyledButton
154
+ data-testid="simulator-clock-advance-day"
155
+ disabled={busy}
156
+ onClick={() => run(() => clock.onAdvance(MS_PER_DAY))}
157
+ style={{ ...runButtonStyle, opacity: busy ? 0.6 : 1 }}
158
+ >
159
+ {t('clockAdvanceDay')}
160
+ </UnstyledButton>
161
+ <UnstyledButton
162
+ data-testid="simulator-clock-advance-week"
163
+ disabled={busy}
164
+ onClick={() => run(() => clock.onAdvance(MS_PER_WEEK))}
165
+ style={{ ...runButtonStyle, opacity: busy ? 0.6 : 1 }}
166
+ >
167
+ {t('clockAdvanceWeek')}
168
+ </UnstyledButton>
169
+ <UnstyledButton
170
+ data-testid="simulator-clock-run-due"
171
+ disabled={busy}
172
+ onClick={() => run(clock.onRunDue)}
173
+ style={{ ...runButtonStyle, opacity: busy ? 0.6 : 1 }}
174
+ >
175
+ {t('clockRunDue')}
176
+ </UnstyledButton>
177
+ {clock.offsetMs > 0 ? (
178
+ <UnstyledButton
179
+ data-testid="simulator-clock-reset"
180
+ disabled={busy}
181
+ onClick={() => run(clock.onReset)}
182
+ style={{ ...runButtonStyle, opacity: busy ? 0.6 : 1 }}
183
+ >
184
+ {t('clockReset')}
185
+ </UnstyledButton>
186
+ ) : null}
187
+ </Group>
188
+ </Box>
189
+ )
190
+ }
191
+
192
+ /**
193
+ * The dev ticker block: ticks the scheduler on real time, as `pnpm tick` does, until stopped. Off until someone
194
+ * starts it. One Start/Stop button whose label changes, never two buttons swapped, so keyboard focus stays on it; and
195
+ * `aria-disabled` rather than `disabled` while busy: disabling a focused button moves `document.activeElement` to
196
+ * `<body>` (measured in Chromium).
197
+ */
198
+ function DevTicker({ ticker }: { ticker: DevTickerLike }) {
199
+ const t = useTranslations('simulator')
200
+ const locale = useLocale()
201
+ const [busy, setBusy] = useState(false)
202
+ const [seconds, setSeconds] = useState(String(ticker.seconds ?? ticker.defaultSeconds))
203
+ // Another process's ticker is live on this world: starting a second is refused, so the button says so up front.
204
+ const blocked = !ticker.running && ticker.elsewhere !== null
205
+ const inert = busy || blocked
206
+
207
+ function toggle() {
208
+ if (inert) return
209
+ setBusy(true)
210
+ const action = ticker.running ? ticker.onStop() : ticker.onStart(Number(seconds))
211
+ void Promise.resolve(action).finally(() => setBusy(false))
212
+ }
213
+
214
+ let status: string
215
+ if (ticker.running && ticker.seconds !== null) status = t('tickerRunning', { seconds: ticker.seconds })
216
+ // The pid as a string: ICU would group a number's digits ("pid 12,345"), which is not the pid you would kill.
217
+ else if (ticker.elsewhere)
218
+ status = t('tickerElsewhere', { seconds: ticker.elsewhere.seconds, pid: String(ticker.elsewhere.pid) })
219
+ else status = t('tickerStopped')
220
+
221
+ return (
222
+ <Box style={sectionStyle} data-testid="simulator-ticker">
223
+ <Text size="xs" fw={700} c="gray.0" mb={4}>
224
+ {t('tickerTitle')}
225
+ </Text>
226
+ <Text size="xs" c="gray.5" mb={6}>
227
+ {t('tickerHint')}
228
+ </Text>
229
+ <Text
230
+ size="xs"
231
+ c={ticker.running ? 'teal.4' : ticker.elsewhere ? 'yellow.4' : 'gray.4'}
232
+ data-testid="simulator-ticker-status"
233
+ >
234
+ {status}
235
+ </Text>
236
+ {ticker.running ? (
237
+ <Text size="xs" c="gray.4" data-testid="simulator-ticker-ticks">
238
+ {ticker.lastTickAt
239
+ ? t('tickerTicks', { count: ticker.ticks, when: formatWhen(ticker.lastTickAt, locale) })
240
+ : t('tickerNoTickYet')}
241
+ </Text>
242
+ ) : null}
243
+ {ticker.lastError ? (
244
+ <Text size="xs" c="red.4" data-testid="simulator-ticker-error">
245
+ {t('tickerLastError', { error: ticker.lastError })}
246
+ </Text>
247
+ ) : null}
248
+ <Group gap={6} wrap="nowrap" align="end" mt={8}>
249
+ {/* While it runs, the status line names the interval; a disabled field would only be harder to read. */}
250
+ {ticker.running ? null : (
251
+ // A native number field, not Mantine's NumberInput: that one brings react-number-format into the
252
+ // static demo's bundle for a control the demo never shows. The server checks the value anyway.
253
+ <TextInput
254
+ size="xs"
255
+ w={150}
256
+ type="number"
257
+ inputMode="numeric"
258
+ data-testid="simulator-ticker-seconds"
259
+ label={t('tickerIntervalLabel')}
260
+ min={ticker.minSeconds}
261
+ max={ticker.maxSeconds}
262
+ step={1}
263
+ value={seconds}
264
+ onChange={(event) => setSeconds(event.currentTarget.value)}
265
+ />
266
+ )}
267
+ <UnstyledButton
268
+ data-testid="simulator-ticker-toggle"
269
+ aria-disabled={inert || undefined}
270
+ onClick={toggle}
271
+ style={{ ...runButtonStyle, opacity: inert ? 0.6 : 1, cursor: inert ? 'not-allowed' : undefined }}
272
+ >
273
+ {ticker.running ? t('tickerStop') : t('tickerStart')}
274
+ </UnstyledButton>
275
+ </Group>
276
+ </Box>
277
+ )
278
+ }
279
+
280
+ /** The schedule list: kind, its timing summary, next run, and enabled state, per tenant/org. */
281
+ function Schedules({ schedules }: { schedules: ScheduleRowLike[] }) {
282
+ const t = useTranslations('simulator')
283
+ const locale = useLocale()
284
+
285
+ return (
286
+ <Box style={sectionStyle} data-testid="simulator-schedules">
287
+ <Text size="xs" fw={700} c="gray.0" mb={6}>
288
+ {t('schedulesTitle')}
289
+ </Text>
290
+ {schedules.length === 0 ? (
291
+ <Text size="xs" c="gray.5" data-testid="simulator-schedules-empty">
292
+ {t('schedulesEmpty')}
293
+ </Text>
294
+ ) : (
295
+ <Stack gap={6}>
296
+ {schedules.map((schedule) => (
297
+ <Box
298
+ key={schedule.id}
299
+ data-testid={`simulator-schedule-${schedule.id}`}
300
+ style={{ border: '1px solid rgba(255,255,255,0.12)', borderRadius: 6, padding: '6px 8px' }}
301
+ >
302
+ <Group justify="space-between" wrap="nowrap" gap="xs" align="start">
303
+ <Stack gap={2} style={{ minWidth: 0 }}>
304
+ <Text size="sm" fw={600} c="gray.0" truncate>
305
+ {schedule.kind}
306
+ </Text>
307
+ <Text size="xs" c="gray.4">
308
+ <ScheduleSpecSummary spec={schedule.spec} />
309
+ </Text>
310
+ <Group gap={4} wrap="nowrap">
311
+ <Text size="xs" c="gray.3" style={chipStyle}>
312
+ {schedule.tenantSlug}
313
+ </Text>
314
+ <Text size="xs" c="gray.3" style={chipStyle}>
315
+ {schedule.orgSlug}
316
+ </Text>
317
+ </Group>
318
+ </Stack>
319
+ <Stack gap={2} align="end" style={{ flexShrink: 0 }}>
320
+ <Text
321
+ size="xs"
322
+ fw={700}
323
+ c={schedule.enabled ? 'teal.4' : 'gray.5'}
324
+ style={chipStyle}
325
+ >
326
+ {schedule.enabled ? t('scheduleEnabled') : t('scheduleDisabled')}
327
+ </Text>
328
+ <Text size="xs" c="gray.5" style={{ whiteSpace: 'nowrap' }}>
329
+ {t('scheduleNextRun', { when: formatWhen(schedule.nextRunAt, locale) })}
330
+ </Text>
331
+ </Stack>
332
+ </Group>
333
+ </Box>
334
+ ))}
335
+ </Stack>
336
+ )}
337
+ </Box>
338
+ )
339
+ }
340
+
341
+ /**
342
+ * Router-agnostic Simulator Jobs tab (ADR-0006 twin lives in @sssb/kit/demo-static): the simulated world's
343
+ * cross-tenant job view, dark-skinned to match the other world tabs (People/Events). Above the job
344
+ * list, it also carries the world-clock control and the schedule list, so the operator can
345
+ * advance simulated time past a schedule's next_run_at and watch it fire. Each job row shows the kind,
346
+ * its tenant/org slug chips, a coloured status chip and the time, and expands to the full status
347
+ * timeline. A held badge flags the paused world; "Run pending jobs" (only when the host wires
348
+ * onRunPending) steps every queued job forward.
349
+ */
350
+ export function JobsApp({
351
+ jobs,
352
+ held,
353
+ onRunPending,
354
+ schedules,
355
+ clock,
356
+ ticker,
357
+ }: {
358
+ jobs: WorldJobLike[]
359
+ held: boolean
360
+ onRunPending?: () => void | Promise<void>
361
+ /** Scheduled work — the world's schedules and clock. Optional so a host that doesn't wire them still works. */
362
+ schedules?: ScheduleRowLike[]
363
+ clock?: WorldClockLike
364
+ /** The dev ticker control; absent unless the host's server offers one (see DevTickerLike). */
365
+ ticker?: DevTickerLike | undefined
366
+ }) {
367
+ const t = useTranslations('simulator')
368
+ const locale = useLocale()
369
+ const [openId, setOpenId] = useState<string | null>(null)
370
+ const [busy, setBusy] = useState(false)
371
+
372
+ return (
373
+ <Stack gap="sm" data-testid="simulator-jobs">
374
+ {clock ? <WorldClock clock={clock} /> : null}
375
+ {ticker ? <DevTicker ticker={ticker} /> : null}
376
+ {schedules ? <Schedules schedules={schedules} /> : null}
377
+
378
+ {held || onRunPending ? (
379
+ <Group justify="space-between" wrap="nowrap" gap="xs">
380
+ {held ? (
381
+ <Text
382
+ size="xs"
383
+ fw={700}
384
+ data-testid="simulator-jobs-held"
385
+ style={{ background: '#5c3d00', color: '#ffd43b', borderRadius: 999, padding: '2px 10px' }}
386
+ >
387
+ {t('jobsHeldBadge')}
388
+ </Text>
389
+ ) : (
390
+ <span />
391
+ )}
392
+ {onRunPending ? (
393
+ <UnstyledButton
394
+ data-testid="simulator-jobs-run"
395
+ disabled={busy}
396
+ onClick={() => {
397
+ setBusy(true)
398
+ void Promise.resolve(onRunPending()).finally(() => setBusy(false))
399
+ }}
400
+ style={{ ...runButtonStyle, opacity: busy ? 0.6 : 1 }}
401
+ >
402
+ {t('jobsRunPending')}
403
+ </UnstyledButton>
404
+ ) : null}
405
+ </Group>
406
+ ) : null}
407
+
408
+ {jobs.length === 0 ? (
409
+ <Text size="sm" c="gray.5" data-testid="simulator-jobs-empty">
410
+ {t('jobsEmpty')}
411
+ </Text>
412
+ ) : (
413
+ <Stack gap={6} data-testid="simulator-jobs-list">
414
+ {jobs.map((job) => {
415
+ const open = job.id === openId
416
+ return (
417
+ <Box
418
+ key={job.id}
419
+ data-testid={`simulator-job-${job.id}`}
420
+ style={{ border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8 }}
421
+ >
422
+ <UnstyledButton
423
+ data-testid={`simulator-job-toggle-${job.id}`}
424
+ aria-expanded={open}
425
+ onClick={() => setOpenId(open ? null : job.id)}
426
+ style={{ display: 'block', width: '100%', padding: '8px 10px' }}
427
+ >
428
+ <Group justify="space-between" wrap="nowrap" gap="xs" align="start">
429
+ <Stack gap={4} style={{ minWidth: 0 }}>
430
+ <Text size="sm" fw={600} c="gray.0" truncate>
431
+ {job.kind}
432
+ </Text>
433
+ <Group gap={4} wrap="nowrap">
434
+ <Text size="xs" c="gray.3" style={chipStyle}>
435
+ {job.tenantSlug}
436
+ </Text>
437
+ {job.orgSlug ? (
438
+ <Text size="xs" c="gray.3" style={chipStyle}>
439
+ {job.orgSlug}
440
+ </Text>
441
+ ) : null}
442
+ </Group>
443
+ </Stack>
444
+ <Stack gap={4} align="end" style={{ flexShrink: 0 }}>
445
+ <Text size="xs" fw={700} c={statusColor(job.status)} style={chipStyle}>
446
+ {job.status}
447
+ </Text>
448
+ <Text size="xs" c="gray.5" style={{ whiteSpace: 'nowrap' }}>
449
+ {formatWhen(job.createdAt, locale)}
450
+ </Text>
451
+ </Stack>
452
+ </Group>
453
+ </UnstyledButton>
454
+ {open ? (
455
+ <Box px={10} pb="xs" style={{ color: '#f8f9fa' }}>
456
+ <JobTimeline timeline={job.timeline} />
457
+ {job.error ? (
458
+ <Text size="xs" c="red.4" mt={4}>
459
+ {job.error}
460
+ </Text>
461
+ ) : null}
462
+ </Box>
463
+ ) : null}
464
+ </Box>
465
+ )
466
+ })}
467
+ </Stack>
468
+ )}
469
+ </Stack>
470
+ )
471
+ }