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