@sssb/kit 0.0.0-stage → 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 -3
  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,716 @@
1
+ 'use client'
2
+
3
+ import { Box, Group, SegmentedControl, Stack, Text, UnstyledButton, VisuallyHidden } from '@mantine/core'
4
+ import { useFormatter, useLocale, useTranslations } from 'next-intl'
5
+ import type { CSSProperties, KeyboardEvent, PointerEvent, ReactNode } from 'react'
6
+ import { useEffect, useRef, useState } from 'react'
7
+ // LOCALES is imported relatively (not via '@') so the static-demo vite bundle resolves it the
8
+ // same way it resolves the rest of this component tree.
9
+ import { LOCALES } from '../../core/locale'
10
+ import { PeopleApp, chipStyle, type Person } from './people-app'
11
+ import { ErrorsApp, type ScrubResult } from './errors-app'
12
+ import { type AuditEntry, EventsApp, type AnalyticsEvent } from './events-app'
13
+ import { HooksApp, type HookDeliveryRow, type HookEndpointRow } from './hooks-app'
14
+ import { InboundApp, type InboundAppProps } from './inbound-app'
15
+ import { type DevTickerLike, JobsApp, type ScheduleRowLike, type WorldClockLike, type WorldJobLike } from './jobs-app'
16
+ import { MailApp, type MailItem } from './mail-app'
17
+ import { MessagesApp, type SmsMessageRow } from './messages-app'
18
+ import { ToursApp, type ToursAppProps } from './tours-app'
19
+ import { tabMount } from './tab-mount'
20
+ import { SnapshotsApp, type FeatureFlag, type Snapshot, type SnapshotAgreement } from './snapshots-app'
21
+
22
+ const COLLAPSED_KEY = 'app-simulator-collapsed'
23
+ const WIDTH_KEY = 'app-simulator-width'
24
+ const TAB_KEY = 'app-simulator-tab'
25
+ const COACH_KEY = 'app-simulator-coach-dismissed'
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
+ /** One app-registered tab, composed by the host (label already translated, content already built). */
43
+ export interface SimulatorExtraTab {
44
+ id: string
45
+ label: string
46
+ content: ReactNode
47
+ /** Mount the content from page load and never unmount it — shown when its tab is, hidden otherwise
48
+ * (other tabs, panel collapsed) — for content that RUNS something, like the Actors tab's tick
49
+ * loops. Unset: the content exists only while its tab is showing. See ./tab-mount. */
50
+ keepMounted?: boolean
51
+ }
52
+
53
+ // Panel width is a continuous drag (the seam on the panel's left edge), clamped to this range;
54
+ // the extra `viewport - 360` clamp keeps at least that much room for the main pane.
55
+ const MIN_WIDTH = 300
56
+ const MAX_WIDTH = 720
57
+ const DEFAULT_WIDTH = 360
58
+ const WIDTH_STEP = 16
59
+
60
+ function clampWidth(value: number): number {
61
+ const viewportCap = typeof window === 'undefined' ? MAX_WIDTH : Math.min(MAX_WIDTH, window.innerWidth - 360)
62
+ // Never let the viewport cap push the ceiling below the floor (very narrow screens).
63
+ const max = Math.max(MIN_WIDTH, viewportCap)
64
+ return Math.min(Math.max(value, MIN_WIDTH), max)
65
+ }
66
+
67
+ // Errors is the technical proof screen — it assumes a light page background, so wrap ONLY its tab
68
+ // content in a light box rather than reskin it. (Events now carries its own dark skin instead.)
69
+ const lightBoxStyle: CSSProperties = { background: '#f8f9fa', color: '#1a1b1e', borderRadius: 8 }
70
+
71
+ function readStoredCollapsed(): boolean {
72
+ if (typeof window === 'undefined') return true
73
+ const raw = window.localStorage.getItem(COLLAPSED_KEY)
74
+ return raw === null ? true : raw === 'true'
75
+ }
76
+
77
+ function readStoredWidth(): number {
78
+ if (typeof window === 'undefined') return DEFAULT_WIDTH
79
+ // parseInt honours legacy preset values ('360'/'520') as plain numbers; NaN → default.
80
+ const parsed = Number.parseInt(window.localStorage.getItem(WIDTH_KEY) ?? '', 10)
81
+ return Number.isNaN(parsed) ? DEFAULT_WIDTH : clampWidth(parsed)
82
+ }
83
+
84
+ // Validated against core ∪ extra ids (the host's registered tabs) so a persisted app tab survives a
85
+ // reload; anything unknown falls back to 'people'.
86
+ function readStoredTab(validIds: string[]): string {
87
+ if (typeof window === 'undefined') return 'people'
88
+ const raw = window.localStorage.getItem(TAB_KEY)
89
+ return raw !== null && validIds.includes(raw) ? raw : 'people'
90
+ }
91
+
92
+ function readCoachDismissed(): boolean {
93
+ if (typeof window === 'undefined') return true
94
+ return window.localStorage.getItem(COACH_KEY) === 'true'
95
+ }
96
+
97
+ /** A transient, simulator-owned notification (never the app's real estate — see decision log). */
98
+ export interface SimulatorNotice {
99
+ id: number
100
+ text: string
101
+ }
102
+
103
+ export interface MailAppProps {
104
+ emails: MailItem[]
105
+ scope: 'person' | 'all'
106
+ onScopeChange: (scope: 'person' | 'all') => void
107
+ personEmail: string | null
108
+ mailSeenAt?: string | null
109
+ /** Total messages across every inbox — powers the "N in All mail" hint in person scope. */
110
+ allCount?: number
111
+ onOpenLink: (href: string) => void
112
+ onSeen: () => void
113
+ onClear?: () => void
114
+ onCopyLink?: (href: string) => void
115
+ }
116
+
117
+ export interface SnapshotsAppProps {
118
+ snapshots?: Snapshot[] | undefined
119
+ onReset: () => void
120
+ onSave?: (name: string) => void
121
+ onRestore?: (name: string) => void
122
+ onDelete?: (name: string) => void
123
+ busy?: boolean
124
+ busySnapshot?: string | null
125
+ flags?: FeatureFlag[]
126
+ onToggleFlag?: (flag: string, enabled: boolean) => void
127
+ agreements?: SnapshotAgreement[]
128
+ onBumpAgreement?: (id: string) => void
129
+ busyAgreement?: string | null
130
+ onLoadPreset?: (id: string) => void
131
+ busyPreset?: string | null
132
+ }
133
+
134
+ export interface JobsAppProps {
135
+ jobs: WorldJobLike[]
136
+ held: boolean
137
+ onRunPending?: () => void | Promise<void>
138
+ /** Scheduled work — the world's schedules and clock control, both wired by the host. */
139
+ schedules?: ScheduleRowLike[]
140
+ clock?: WorldClockLike
141
+ /** The dev ticker control: wired only by a host whose server offers it (never the static demo). */
142
+ ticker?: DevTickerLike | undefined
143
+ }
144
+
145
+ export interface HooksAppProps {
146
+ endpoints: HookEndpointRow[]
147
+ deliveries: HookDeliveryRow[]
148
+ failingEndpointIds: string[]
149
+ onToggleFail: (endpointId: string, failing: boolean) => void | Promise<void>
150
+ onRunDue: () => void | Promise<void>
151
+ }
152
+
153
+ /**
154
+ * The Simulator panel (ADR-0006 twin lives in @sssb/kit/demo-static): collapsed = a small fixed pill (no
155
+ * layout shift); expanded = a right-docked column with its own dark skin so it reads as "not the
156
+ * 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:
159
+ * 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
163
+ * feedback stays inside simulator: a notice overlay anchored at the panel's bottom edge when
164
+ * expanded (absolute, so it never shifts the scroll body), a pulsing unread badge on the pill when
165
+ * collapsed — never app-level toasts that could collide with future product ones. The header shows
166
+ * a locale switcher (host-driven, optional) and a chip naming the current viewpoint.
167
+ */
168
+ export function SimulatorPanel({
169
+ people,
170
+ viewpoint,
171
+ signedIn,
172
+ onSelect,
173
+ onRefresh,
174
+ onExpandedChange,
175
+ onTabChange,
176
+ onLocaleChange,
177
+ mail,
178
+ inbound,
179
+ messages,
180
+ events,
181
+ audit,
182
+ jobs,
183
+ hooks,
184
+ extraTabs,
185
+ runServerErrorScenario,
186
+ snapshots,
187
+ tours,
188
+ notices = [],
189
+ }: {
190
+ people: Person[]
191
+ viewpoint: string | null
192
+ signedIn: boolean
193
+ onSelect: (key: string) => void
194
+ onRefresh?: () => void
195
+ onExpandedChange?: (expanded: boolean) => void
196
+ /** Emits a core id OR an extra-tab id (a plain string) — the host narrows it if it cares. */
197
+ onTabChange?: (tab: string) => void
198
+ /** When provided, the header shows a locale switcher — the host owns what switching does (a
199
+ * full reload in the real app, in-memory state in the static demo). */
200
+ onLocaleChange?: (locale: string) => void
201
+ mail: MailAppProps
202
+ /** Inbound email: the Mail tab's "compose inbound" affordance + world inbound list. */
203
+ inbound: InboundAppProps
204
+ messages: SmsMessageRow[]
205
+ events: AnalyticsEvent[]
206
+ /** Compliance-grade audit trail, rendered read-only beneath the analytics events. */
207
+ audit: AuditEntry[]
208
+ jobs: JobsAppProps
209
+ hooks: HooksAppProps
210
+ /** App-registered tabs (@sssb/app-config/simulator), composed by the host. Rendered between Hooks and
211
+ * 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
215
+ /** Scripted walkthroughs (@sssb/kit/demo-static/tour/use-tours). Undefined when the app registers no
216
+ * tours — the tab then doesn't exist at all, which is the off-switch an adopter gets for free. */
217
+ tours?: ToursAppProps | undefined
218
+ notices?: SimulatorNotice[]
219
+ }) {
220
+ const t = useTranslations('simulator')
221
+ const format = useFormatter()
222
+ const locale = useLocale()
223
+ // Collapsed by default: SSR has no localStorage, so starting expanded would flash the column
224
+ // before the persisted value can be read on mount.
225
+ const [collapsed, setCollapsed] = useState(true)
226
+ const [width, setWidth] = useState<number>(DEFAULT_WIDTH)
227
+ const [activeTab, setActiveTab] = useState<string>('people')
228
+ const [coachDismissed, setCoachDismissed] = useState(true)
229
+ // Drag/hover/focus state for the resize seam. dragRef stashes the pointer-down anchor so a
230
+ // move recomputes width relative to where the drag started (not the last frame).
231
+ const [dragging, setDragging] = useState(false)
232
+ const [seamActive, setSeamActive] = useState(false)
233
+ const dragRef = useRef<{ startX: number; startWidth: number } | null>(null)
234
+ // Stamped as data-hydrated on the pill/panel root once this mount effect has run — i.e. once
235
+ // React has attached the click handlers. The SSR'd pill LOOKS clickable before hydration but
236
+ // silently swallows clicks; Playwright waits for the stamp instead of racing that window.
237
+ const [hydrated, setHydrated] = useState(false)
238
+ // Kept-mounted content (actor frames) mounts only once the host page has loaded — see ./tab-mount.
239
+ const [pageLoaded, setPageLoaded] = useState(false)
240
+ useEffect(() => {
241
+ if (document.readyState === 'complete') {
242
+ // Syncing with an external event (the window's load), so setting state here is the point.
243
+ // eslint-disable-next-line react-hooks/set-state-in-effect
244
+ setPageLoaded(true)
245
+ return
246
+ }
247
+ const onLoad = () => setPageLoaded(true)
248
+ window.addEventListener('load', onLoad, { once: true })
249
+ return () => window.removeEventListener('load', onLoad)
250
+ }, [])
251
+ const mountState = { activeTab, collapsed, pageLoaded }
252
+ // A kept-mounted tab hidden behind the collapsed pill still needs its panel in the DOM, at the
253
+ // SAME tree position it had while expanded — an iframe that moves is an iframe that reloads.
254
+ const keepPanel = !collapsed || extraTabs.some((tab) => tabMount(tab, mountState) === 'hidden')
255
+ // A core tab's content shows only in an expanded panel (the hidden kept-alive panel holds nothing else).
256
+ const showing = (tab: string) => !collapsed && activeTab === tab
257
+
258
+ const totalUnread = people.reduce((sum, person) => sum + person.unreadMail, 0)
259
+ const badgeRef = useRef<HTMLDivElement | null>(null)
260
+ // Focus follows a toggle (WCAG 2.4.3): the control the user pressed unmounts (the pill) or is hidden with the panel
261
+ // (Hide), so focus goes to the one that replaces it. Only after toggle(): the first render and a collapsed state
262
+ // restored from localStorage never move focus on page load.
263
+ const pillRef = useRef<HTMLButtonElement | null>(null)
264
+ const collapseRef = useRef<HTMLButtonElement | null>(null)
265
+ const focusAfterToggle = useRef(false)
266
+ const prevUnread = useRef(totalUnread)
267
+
268
+ useEffect(() => {
269
+ // Reading localStorage is an external-system sync (SSR has none), so this legitimately
270
+ // sets state from an effect rather than during render.
271
+ 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)])
274
+ // eslint-disable-next-line react-hooks/set-state-in-effect
275
+ setCollapsed(storedCollapsed)
276
+ setWidth(readStoredWidth())
277
+ setActiveTab(storedTab)
278
+ setCoachDismissed(readCoachDismissed())
279
+ setHydrated(true)
280
+ onExpandedChange?.(!storedCollapsed)
281
+ onTabChange?.(storedTab)
282
+ // Intentionally mount-only: syncs the caller's poll loop with the persisted state once.
283
+ // eslint-disable-next-line react-hooks/exhaustive-deps
284
+ }, [])
285
+
286
+ useEffect(() => {
287
+ // Unmount-mid-drag safety net: pointerdown disables text selection on <body> and pointerup
288
+ // restores it, but if the panel ever unmounts between the two the restore must still run.
289
+ return () => {
290
+ document.body.style.userSelect = ''
291
+ }
292
+ }, [])
293
+
294
+ useEffect(() => {
295
+ // Collapsed feedback channel: when new mail lands, the pill's badge pulses (Web Animations
296
+ // API — no global CSS). Expanded feedback goes through the notice strip instead.
297
+ if (totalUnread > prevUnread.current && collapsed) {
298
+ badgeRef.current?.animate(
299
+ [{ transform: 'scale(1)' }, { transform: 'scale(1.35)' }, { transform: 'scale(1)' }],
300
+ { duration: 500, iterations: 3 },
301
+ )
302
+ }
303
+ prevUnread.current = totalUnread
304
+ }, [totalUnread, collapsed])
305
+
306
+ useEffect(() => {
307
+ if (!focusAfterToggle.current) return
308
+ focusAfterToggle.current = false
309
+ ;(collapsed ? pillRef : collapseRef).current?.focus()
310
+ }, [collapsed])
311
+
312
+ function dismissCoach() {
313
+ setCoachDismissed(true)
314
+ window.localStorage.setItem(COACH_KEY, 'true')
315
+ }
316
+
317
+ function toggle() {
318
+ const next = !collapsed
319
+ focusAfterToggle.current = true
320
+ setCollapsed(next)
321
+ window.localStorage.setItem(COLLAPSED_KEY, String(next))
322
+ if (!coachDismissed) dismissCoach()
323
+ onExpandedChange?.(!next)
324
+ if (!next) onRefresh?.()
325
+ }
326
+
327
+ function persistWidth(next: number) {
328
+ window.localStorage.setItem(WIDTH_KEY, String(next))
329
+ }
330
+
331
+ function onSeamPointerDown(event: PointerEvent<HTMLDivElement>) {
332
+ // preventDefault stops the browser's own text-selection/drag; pointer capture keeps events
333
+ // coming to the seam even as the cursor crosses the mail iframe (the primary drag fix).
334
+ event.preventDefault()
335
+ event.currentTarget.setPointerCapture(event.pointerId)
336
+ dragRef.current = { startX: event.clientX, startWidth: width }
337
+ document.body.style.userSelect = 'none'
338
+ setDragging(true)
339
+ }
340
+
341
+ function onSeamPointerMove(event: PointerEvent<HTMLDivElement>) {
342
+ if (!dragRef.current) return
343
+ const { startX, startWidth } = dragRef.current
344
+ // The seam is on the panel's LEFT edge, so moving left (smaller clientX) widens the panel.
345
+ setWidth(clampWidth(startWidth + (startX - event.clientX)))
346
+ }
347
+
348
+ function endSeamDrag(event: PointerEvent<HTMLDivElement>) {
349
+ if (!dragRef.current) return
350
+ dragRef.current = null
351
+ document.body.style.userSelect = ''
352
+ setDragging(false)
353
+ try {
354
+ event.currentTarget.releasePointerCapture(event.pointerId)
355
+ } catch {
356
+ // capture may already be gone (pointercancel) — nothing to release.
357
+ }
358
+ // Persist the latest committed width without a stale closure over `width`.
359
+ setWidth((current) => {
360
+ persistWidth(current)
361
+ return current
362
+ })
363
+ }
364
+
365
+ function onSeamKeyDown(event: KeyboardEvent<HTMLDivElement>) {
366
+ let next: number | null = null
367
+ if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') next = width + WIDTH_STEP
368
+ else if (event.key === 'ArrowRight' || event.key === 'ArrowDown') next = width - WIDTH_STEP
369
+ else if (event.key === 'Home') next = MIN_WIDTH
370
+ else if (event.key === 'End') next = MAX_WIDTH
371
+ if (next === null) return
372
+ event.preventDefault()
373
+ const clamped = clampWidth(next)
374
+ setWidth(clamped)
375
+ persistWidth(clamped)
376
+ }
377
+
378
+ function resetWidth() {
379
+ setWidth(DEFAULT_WIDTH)
380
+ persistWidth(DEFAULT_WIDTH)
381
+ }
382
+
383
+ function selectTab(tab: string) {
384
+ setActiveTab(tab)
385
+ window.localStorage.setItem(TAB_KEY, tab)
386
+ onTabChange?.(tab)
387
+ }
388
+
389
+ const pill = collapsed ? (
390
+ <>
391
+ {hydrated && !coachDismissed ? (
392
+ <Box
393
+ component="aside"
394
+ aria-label={t('pillLabel')}
395
+ data-testid="simulator-coachmark"
396
+ style={{
397
+ position: 'fixed',
398
+ bottom: 132,
399
+ right: 16,
400
+ zIndex: 1000,
401
+ maxWidth: 250,
402
+ background: '#1a1b1e',
403
+ color: '#f8f9fa',
404
+ border: '1px solid #373a40',
405
+ borderRadius: 10,
406
+ padding: '10px 12px',
407
+ boxShadow: '0 2px 10px rgba(0,0,0,0.35)',
408
+ // Visual-only: the bubble floats over app content, so it must never
409
+ // swallow the app's clicks — only the dismiss button is interactive
410
+ // (and opening the pill dismisses it too).
411
+ pointerEvents: 'none',
412
+ }}
413
+ >
414
+ <Group justify="space-between" wrap="nowrap" align="start" gap="xs">
415
+ <Text size="xs" c="gray.2">
416
+ {t('coachmark')}
417
+ </Text>
418
+ <UnstyledButton
419
+ aria-label={t('coachmarkDismissAriaLabel')}
420
+ data-testid="simulator-coachmark-dismiss"
421
+ onClick={dismissCoach}
422
+ style={{
423
+ color: '#f8f9fa',
424
+ fontSize: 12,
425
+ fontWeight: 700,
426
+ lineHeight: 1,
427
+ pointerEvents: 'auto',
428
+ }}
429
+ >
430
+ {t('coachmarkDismiss')}
431
+ </UnstyledButton>
432
+ </Group>
433
+ </Box>
434
+ ) : null}
435
+ <UnstyledButton
436
+ ref={pillRef}
437
+ data-testid="simulator-pill"
438
+ data-hydrated={hydrated ? 'true' : undefined}
439
+ onClick={toggle}
440
+ style={{
441
+ position: 'fixed',
442
+ bottom: 76,
443
+ right: 16,
444
+ zIndex: 1000,
445
+ display: 'flex',
446
+ alignItems: 'center',
447
+ gap: 8,
448
+ background: '#1a1b1e',
449
+ color: '#f8f9fa',
450
+ borderRadius: 999,
451
+ padding: '10px 18px',
452
+ border: '1px solid #373a40',
453
+ boxShadow: '0 2px 10px rgba(0,0,0,0.35)',
454
+ }}
455
+ >
456
+ {/* Named by its content, never an aria-label (WCAG 2.5.3 Label in Name): the visible
457
+ "Simulator", then a visually hidden ", 3 unread emails, open the panel" (Chromium
458
+ computes "Simulator , 3 unread…": the hidden text is absolutely positioned, which it
459
+ pads with a space). The badge is
460
+ aria-hidden because the hidden text says its count with a unit; both use the same
461
+ locale number format, so the digits a voice user sees are the ones in the name. axe
462
+ 4.14 reads label and badge as one word ("Simulator3"), which no aria-label contains. */}
463
+ <Text size="sm" fw={600} c="gray.0">
464
+ {t('pillLabel')}
465
+ <VisuallyHidden>
466
+ {totalUnread > 0 ? t('pillUnreadSuffix', { count: totalUnread }) : t('pillSuffix')}
467
+ </VisuallyHidden>
468
+ </Text>
469
+ {totalUnread > 0 ? (
470
+ <Text
471
+ ref={badgeRef}
472
+ aria-hidden
473
+ size="xs"
474
+ fw={700}
475
+ style={{ background: '#c92a2a', color: '#fff', borderRadius: 999, padding: '1px 8px' }}
476
+ >
477
+ {format.number(totalUnread)}
478
+ </Text>
479
+ ) : null}
480
+ </UnstyledButton>
481
+ </>
482
+ ) : null
483
+
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
+ // The person the panel is currently "watching" — powers the header chip so it's always clear
501
+ // whose world this is, even before switching tabs.
502
+ const person = people.find((person) => person.key === viewpoint) ?? null
503
+
504
+ const panel = keepPanel ? (
505
+ <Box
506
+ component="aside"
507
+ aria-label={t('panelTitle')}
508
+ data-testid="simulator-panel"
509
+ data-hydrated={hydrated ? 'true' : undefined}
510
+ style={{
511
+ width,
512
+ flexShrink: 0,
513
+ // Sticky so the panel stays docked while a long main pane scrolls (the inner
514
+ // content box below is the scroll container for the panel's own overflow). Sticky
515
+ // is a positioned value, so the absolute resize seam anchors to this box.
516
+ position: 'sticky',
517
+ top: 0,
518
+ height: '100vh',
519
+ alignSelf: 'flex-start',
520
+ display: collapsed ? 'none' : 'flex',
521
+ flexDirection: 'column',
522
+ background: '#1a1b1e',
523
+ color: '#f8f9fa',
524
+ borderLeft: '1px solid #373a40',
525
+ }}
526
+ >
527
+ {/* Draggable resize seam on the panel's left edge — a focusable separator so keyboard
528
+ users can size the panel too (arrows step, Home/End jump, double-click resets). */}
529
+ <Box
530
+ role="separator"
531
+ tabIndex={0}
532
+ aria-orientation="vertical"
533
+ aria-label={t('widthLabel')}
534
+ aria-valuenow={width}
535
+ aria-valuemin={MIN_WIDTH}
536
+ aria-valuemax={MAX_WIDTH}
537
+ data-testid="simulator-resize"
538
+ onPointerDown={onSeamPointerDown}
539
+ onPointerMove={onSeamPointerMove}
540
+ onPointerUp={endSeamDrag}
541
+ onPointerCancel={endSeamDrag}
542
+ onKeyDown={onSeamKeyDown}
543
+ onDoubleClick={resetWidth}
544
+ onMouseEnter={() => setSeamActive(true)}
545
+ onMouseLeave={() => setSeamActive(false)}
546
+ onFocus={() => setSeamActive(true)}
547
+ onBlur={() => setSeamActive(false)}
548
+ style={{
549
+ position: 'absolute',
550
+ top: 0,
551
+ bottom: 0,
552
+ left: -3,
553
+ width: 7,
554
+ zIndex: 3,
555
+ cursor: 'col-resize',
556
+ touchAction: 'none',
557
+ background: seamActive || dragging ? 'rgba(77,171,247,0.6)' : 'transparent',
558
+ }}
559
+ />
560
+ <Stack gap="xs" p="sm" style={{ borderBottom: '1px solid #373a40' }}>
561
+ <Group justify="space-between" wrap="nowrap" gap="xs">
562
+ <Text fw={700} c="gray.0">
563
+ {t('panelTitle')}
564
+ </Text>
565
+ <Group gap="xs" wrap="nowrap">
566
+ {onLocaleChange ? (
567
+ <SegmentedControl
568
+ aria-label={t('localeLabel')}
569
+ data-testid="simulator-locale"
570
+ size="xs"
571
+ value={locale}
572
+ data={[...LOCALES]}
573
+ onChange={(value) => onLocaleChange(value)}
574
+ />
575
+ ) : null}
576
+ <UnstyledButton
577
+ ref={collapseRef}
578
+ data-testid="simulator-collapse"
579
+ aria-label={t('collapseAriaLabel')}
580
+ onClick={toggle}
581
+ style={{
582
+ fontSize: 12,
583
+ fontWeight: 600,
584
+ color: '#f8f9fa',
585
+ border: '1px solid #373a40',
586
+ borderRadius: 6,
587
+ padding: '4px 10px',
588
+ }}
589
+ >
590
+ {t('collapseButton')}
591
+ </UnstyledButton>
592
+ </Group>
593
+ </Group>
594
+ {/* role="group" so the aria-label is permitted (ARIA prohibits naming a generic
595
+ div — the a11y sweep's axe pass enforces that). */}
596
+ <Group
597
+ gap="xs"
598
+ wrap="nowrap"
599
+ role="group"
600
+ data-testid="simulator-person"
601
+ aria-label={t('personChipLabel')}
602
+ style={{ minWidth: 0 }}
603
+ >
604
+ <Text size="xs" c="gray.4" truncate>
605
+ {person ? (person.name ?? person.email) : t('personChipSignedOut')}
606
+ </Text>
607
+ {person?.status === 'invited' ? (
608
+ <Text size="xs" c="gray.3" style={{ ...chipStyle, flexShrink: 0 }}>
609
+ {t('peopleInvitedBadge')}
610
+ </Text>
611
+ ) : null}
612
+ </Group>
613
+ </Stack>
614
+ <Group gap={4} p="xs" wrap="wrap" style={{ borderBottom: '1px solid #373a40' }}>
615
+ {tabs.map((tab) => (
616
+ <UnstyledButton
617
+ key={tab.id}
618
+ data-testid={`simulator-tab-${tab.id}`}
619
+ onClick={() => selectTab(tab.id)}
620
+ style={{
621
+ fontSize: 12,
622
+ fontWeight: 700,
623
+ color: '#f8f9fa',
624
+ background: activeTab === tab.id ? 'rgba(255,255,255,0.12)' : 'transparent',
625
+ borderRadius: 6,
626
+ padding: '6px 8px',
627
+ }}
628
+ >
629
+ {tab.label}
630
+ </UnstyledButton>
631
+ ))}
632
+ </Group>
633
+ {/* The sticky aside is viewport-height, so this box really scrolls — it needs to be
634
+ keyboard-focusable (scrollable-region-focusable) for arrow-key scrolling. While
635
+ dragging the seam, pointerEvents:none lets the capture ride over the mail iframe. */}
636
+ <Box
637
+ p="sm"
638
+ role="region"
639
+ aria-label={t('panelTitle')}
640
+ tabIndex={0}
641
+ style={{ flex: 1, overflowY: 'auto', pointerEvents: dragging ? 'none' : undefined }}
642
+ >
643
+ {showing('people') ? (
644
+ <>
645
+ {/* Either/or, never both: signed out, the hint has to explain that picking
646
+ anyone signs you in; signed in, it explains what clicking a row does. Both
647
+ carry the same invited-row caveat, because selecting an invited person is a
648
+ viewpoint change and not a sign-in (see world.ts's `invited:` branch). */}
649
+ <Text size="xs" c="gray.5" mb="sm">
650
+ {signedIn ? t('peopleHint') : t('signedOutHint')}
651
+ </Text>
652
+ <PeopleApp people={people} viewpoint={viewpoint} onSelect={onSelect} />
653
+ </>
654
+ ) : null}
655
+ {showing('mail') ? (
656
+ <Stack gap="lg">
657
+ <InboundApp {...inbound} />
658
+ <MailApp {...mail} />
659
+ </Stack>
660
+ ) : 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}
665
+ {/* App tabs render their host-built content here (between Hooks and Errors). An ordinary
666
+ tab's live content (iframe / mounted node) unmounts with it; a keepMounted one is there
667
+ from page load, stays put, and is only hidden (./tab-mount). */}
668
+ {extraTabs.map((tab) => {
669
+ const mount = tabMount(tab, mountState)
670
+ return mount === 'none' ? null : (
671
+ <Box key={tab.id} style={mount === 'hidden' ? { display: 'none' } : undefined}>
672
+ {tab.content}
673
+ </Box>
674
+ )
675
+ })}
676
+ {showing('errors') ? (
677
+ <Box style={lightBoxStyle}>
678
+ <ErrorsApp runServerScenario={runServerErrorScenario} />
679
+ </Box>
680
+ ) : null}
681
+ {showing('snapshots') ? <SnapshotsApp {...snapshots} /> : null}
682
+ {showing('tours') && tours ? <ToursApp {...tours} /> : null}
683
+ </Box>
684
+ {/* Notices overlay the panel's bottom edge (absolute, not in flow) so a transient
685
+ confirmation never shoves the scroll body — no layout shift when one appears. */}
686
+ {notices.length > 0 ? (
687
+ <Box
688
+ role="status"
689
+ p="xs"
690
+ style={{
691
+ position: 'absolute',
692
+ bottom: 0,
693
+ left: 0,
694
+ right: 0,
695
+ zIndex: 2,
696
+ background: '#1a1b1e',
697
+ borderTop: '1px solid #373a40',
698
+ }}
699
+ >
700
+ {notices.map((notice) => (
701
+ <Text key={notice.id} size="xs" c="yellow.3" data-testid="simulator-notice">
702
+ {notice.text}
703
+ </Text>
704
+ ))}
705
+ </Box>
706
+ ) : null}
707
+ </Box>
708
+ ) : null
709
+
710
+ return (
711
+ <>
712
+ {pill}
713
+ {panel}
714
+ </>
715
+ )
716
+ }