@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,100 @@
1
+ 'use client'
2
+
3
+ import { Button, Card, Container, Select, Stack, Text, TextInput, Title } from '@mantine/core'
4
+ import { useForm } from '@mantine/form'
5
+ import { useTranslations } from 'next-intl'
6
+ import { type ReactNode, useState } from 'react'
7
+
8
+ export interface ProfileValues {
9
+ name: string
10
+ locale: string
11
+ }
12
+
13
+ /**
14
+ * Lean take on Clerk's UserProfile (ADR-0003): a sectioned account page. The Profile section is live;
15
+ * the Security section is a named seam so MFA / password / connected accounts have a home when those
16
+ * slices land (each becomes a port method + adapter pair, per the auth-UI playbook). `extraSection` is
17
+ * a generic slot for further account cards (the notification-preferences grid lands here)
18
+ * without coupling this screen to any one feature.
19
+ */
20
+ export function ProfileScreen({
21
+ initial,
22
+ email,
23
+ locales,
24
+ onSave,
25
+ extraSection,
26
+ }: {
27
+ initial: ProfileValues
28
+ email: string
29
+ locales: string[]
30
+ onSave: (values: ProfileValues) => Promise<void>
31
+ extraSection?: ReactNode
32
+ }) {
33
+ const t = useTranslations('profile')
34
+ const [saved, setSaved] = useState(false)
35
+ const [busy, setBusy] = useState(false)
36
+ const form = useForm({ initialValues: initial })
37
+
38
+ return (
39
+ <Container component="main" size="sm" py="xl">
40
+ <Stack gap="lg">
41
+ <Title order={1}>{t('title')}</Title>
42
+
43
+ <Card withBorder padding="lg" radius="md">
44
+ <Title order={2} size="h3" mb="md">
45
+ {t('profileSection')}
46
+ </Title>
47
+ <form
48
+ onSubmit={form.onSubmit((values) => {
49
+ setBusy(true)
50
+ setSaved(false)
51
+ onSave(values)
52
+ .then(() => setSaved(true))
53
+ .finally(() => setBusy(false))
54
+ })}
55
+ >
56
+ <Stack>
57
+ <TextInput label={t('emailLabel')} value={email} disabled />
58
+ <TextInput
59
+ label={t('nameLabel')}
60
+ data-testid="profile-name"
61
+ {...form.getInputProps('name')}
62
+ />
63
+ <Select
64
+ label={t('localeLabel')}
65
+ data={locales}
66
+ allowDeselect={false}
67
+ data-testid="profile-locale"
68
+ {...form.getInputProps('locale')}
69
+ />
70
+ <Button
71
+ type="submit"
72
+ loading={busy}
73
+ data-testid="profile-save"
74
+ style={{ alignSelf: 'start' }}
75
+ >
76
+ {t('saveButton')}
77
+ </Button>
78
+ {saved ? (
79
+ <Text c="green.8" size="sm" data-testid="profile-saved">
80
+ {t('saved')}
81
+ </Text>
82
+ ) : null}
83
+ </Stack>
84
+ </form>
85
+ </Card>
86
+
87
+ {extraSection}
88
+
89
+ <Card withBorder padding="lg" radius="md">
90
+ <Title order={2} size="h3" mb="xs">
91
+ {t('securitySection')}
92
+ </Title>
93
+ <Text c="gray.7" size="sm" data-testid="security-soon">
94
+ {t('securitySoon')}
95
+ </Text>
96
+ </Card>
97
+ </Stack>
98
+ </Container>
99
+ )
100
+ }
@@ -0,0 +1,180 @@
1
+ import type { JobStatus } from '../../core/jobs'
2
+
3
+ /**
4
+ * The Simulator actors' tick logic, isolated from JSX (ADR-0006: src/components screens are
5
+ * router-agnostic; this half is transport-agnostic too). A "driver" is whatever actually talks to
6
+ * the surfaces — real fetch drivers live in the app dir, the static twin closes over in-memory
7
+ * state — so this file can be unit-tested with scripted drivers and reused verbatim by both hosts.
8
+ *
9
+ * Two log fields per entry (see ActorLogEntry): `line` is verbatim technical text (an HTTP call and
10
+ * its status) and is NEVER translated; `note` is localized prose the caller translates at creation
11
+ * time via the `t` it passes in. Each tick performs AT MOST ONE product-visible mutation.
12
+ */
13
+
14
+ export interface ActorLogEntry {
15
+ at: string
16
+ line: string
17
+ note?: string
18
+ }
19
+
20
+ /** Appends one entry; the shell stamps `at`. `line` = verbatim HTTP text, `note` = localized prose. */
21
+ export type ActorLog = (entry: { line: string; note?: string }) => void
22
+
23
+ /**
24
+ * A note translator bound to the 'simulator' next-intl namespace — the caller passes the function
25
+ * `useTranslations('simulator')` returns. Keys are the `actorNote*` set; `values` fill ICU
26
+ * placeholders. Kept structural (not next-intl's own type) so packages/kit/src/core stays reachable and the
27
+ * static twin can supply its own translator.
28
+ */
29
+ export type ActorNoteT = (key: string, values?: Record<string, string | number>) => string
30
+
31
+ /** A job as the service runner sees it over its poll (no timeline — light polling). */
32
+ export interface ServiceJobLike {
33
+ id: string
34
+ kind: string
35
+ status: JobStatus
36
+ createdAt: string
37
+ }
38
+
39
+ /** A pending build the builder-console may deliver a completion webhook for. */
40
+ export interface PendingBuildLike {
41
+ jobId: string
42
+ tenantId: string
43
+ tenantSlug: string
44
+ orgSlug: string | null
45
+ kind: string
46
+ status: 'queued' | 'running'
47
+ createdAt: string
48
+ }
49
+
50
+ /**
51
+ * Outcome of a single lifecycle hop against the genuine surface. `failed` = the surface accepted a
52
+ * *failed* terminal report (a job whose handler couldn't produce its artifact) — distinct from
53
+ * `applied` so the runtime narrates it as "reported failed", never as "completed".
54
+ */
55
+ export type HopOutcome = 'applied' | 'failed' | 'conflict' | 'gone' | 'unauthorized'
56
+ /** A build delivery can additionally be a no-op redelivery of an already-terminal job. */
57
+ export type DeliverOutcome = HopOutcome | 'idempotent'
58
+
59
+ export interface ServiceDriver {
60
+ listJobs(): Promise<ServiceJobLike[]>
61
+ claim(jobId: string): Promise<HopOutcome>
62
+ /** Produces the artifact, then reports the terminal status carrying its key. */
63
+ complete(jobId: string): Promise<HopOutcome>
64
+ }
65
+
66
+ export interface BuilderDriver {
67
+ listBuilds(): Promise<PendingBuildLike[]>
68
+ deliver(build: PendingBuildLike): Promise<DeliverOutcome>
69
+ }
70
+
71
+ /** The service runner's only cross-tick memory: the ids it believes it has claimed. */
72
+ export interface ServiceMemory {
73
+ claimed: Set<string>
74
+ }
75
+
76
+ /** Picks the oldest item by ISO createdAt (min) — ISO strings sort chronologically. */
77
+ function oldest<T extends { createdAt: string }>(items: T[]): T {
78
+ return items.reduce((a, b) => (a.createdAt <= b.createdAt ? a : b))
79
+ }
80
+
81
+ /**
82
+ * One service-runner tick: poll the team's jobs, then make at most one hop. Completing a running job
83
+ * takes priority over claiming a queued one, so a job never stalls half-done — and because it acts
84
+ * on whatever is `running` (not only ids it remembers claiming), it self-heals after an iframe
85
+ * reload wiped its memory. Claimed-id memory is pruned to ids still present each poll, so a
86
+ * reset-orphaned claim simply vanishes.
87
+ */
88
+ export async function serviceTick(
89
+ driver: ServiceDriver,
90
+ memory: ServiceMemory,
91
+ log: ActorLog,
92
+ t: ActorNoteT,
93
+ ): Promise<void> {
94
+ const jobs = await driver.listJobs()
95
+ log({ line: `GET /api/service/jobs → 200 (${jobs.length} jobs)` })
96
+
97
+ const present = new Set(jobs.map((j) => j.id))
98
+ for (const id of [...memory.claimed]) if (!present.has(id)) memory.claimed.delete(id)
99
+
100
+ const running = jobs.filter((j) => j.status === 'running')
101
+ if (running.length > 0) {
102
+ const job = oldest(running)
103
+ const outcome = await driver.complete(job.id)
104
+ // Whatever happened, we no longer own this id — a completed, lost, or vanished job is done.
105
+ memory.claimed.delete(job.id)
106
+ logServiceHop(log, t, job.id, outcome, 'complete')
107
+ return
108
+ }
109
+
110
+ const queued = jobs.filter((j) => j.status === 'queued')
111
+ if (queued.length > 0) {
112
+ const job = oldest(queued)
113
+ const outcome = await driver.claim(job.id)
114
+ if (outcome === 'applied') memory.claimed.add(job.id)
115
+ logServiceHop(log, t, job.id, outcome, 'claim')
116
+ return
117
+ }
118
+
119
+ log({ line: `GET /api/service/jobs → 200 (0 actionable)`, note: t('actorNoteIdle') })
120
+ }
121
+
122
+ function logServiceHop(log: ActorLog, t: ActorNoteT, id: string, outcome: HopOutcome, hop: 'claim' | 'complete'): void {
123
+ const path = `POST /api/service/jobs/${id}/status`
124
+ switch (outcome) {
125
+ case 'applied':
126
+ if (hop === 'claim') log({ line: `${path} → 200 running`, note: t('actorNoteClaimed', { id }) })
127
+ else log({ line: `${path} → 200 completed`, note: t('actorNoteCompleted', { id }) })
128
+ return
129
+ case 'failed':
130
+ log({ line: `${path} → 200 failed`, note: t('actorNoteFailedReported', { id }) })
131
+ return
132
+ case 'conflict':
133
+ log({ line: `${path} → 409`, note: t('actorNoteLostRace') })
134
+ return
135
+ case 'gone':
136
+ log({ line: `${path} → 404`, note: t('actorNoteVanished') })
137
+ return
138
+ case 'unauthorized':
139
+ log({ line: `${path} → 401`, note: t('actorNoteError', { message: 'unauthorized' }) })
140
+ return
141
+ }
142
+ }
143
+
144
+ /**
145
+ * One builder-console tick: poll the pending-build pool, then deliver a completion webhook for the
146
+ * oldest build. The webhook is idempotent by construction (a redelivery of an already-terminal job
147
+ * is a no-op), so the outcome maps cleanly: delivered / redelivered / moved-on / vanished.
148
+ */
149
+ export async function builderTick(driver: BuilderDriver, log: ActorLog, t: ActorNoteT): Promise<void> {
150
+ const builds = await driver.listBuilds()
151
+ log({ line: `GET /api/simulator/actors/builds → 200 (${builds.length} builds)` })
152
+ if (builds.length === 0) {
153
+ log({ line: `GET /api/simulator/actors/builds → 200 (0 pending)`, note: t('actorNoteIdle') })
154
+ return
155
+ }
156
+
157
+ const build = oldest(builds)
158
+ const outcome = await driver.deliver(build)
159
+ const path = `POST /api/webhooks/jobs`
160
+ switch (outcome) {
161
+ case 'applied':
162
+ log({ line: `${path} → 200`, note: t('actorNoteDelivered', { id: build.jobId }) })
163
+ return
164
+ case 'failed':
165
+ log({ line: `${path} → 200 failed`, note: t('actorNoteFailedReported', { id: build.jobId }) })
166
+ return
167
+ case 'idempotent':
168
+ log({ line: `${path} → 200 (idempotent)`, note: t('actorNoteRedelivered') })
169
+ return
170
+ case 'conflict':
171
+ log({ line: `${path} → 409`, note: t('actorNoteMovedOn') })
172
+ return
173
+ case 'gone':
174
+ log({ line: `${path} → 404`, note: t('actorNoteVanished') })
175
+ return
176
+ case 'unauthorized':
177
+ log({ line: `${path} → 401`, note: t('actorNoteError', { message: 'unauthorized' }) })
178
+ return
179
+ }
180
+ }
@@ -0,0 +1,275 @@
1
+ 'use client'
2
+
3
+ import { Box, Group, Stack, Text, UnstyledButton } from '@mantine/core'
4
+ import { useLocale, useTranslations } from 'next-intl'
5
+ import { useCallback, useEffect, useRef, useState } from 'react'
6
+ import type { ActorId } from '@sssb/app-config/actors'
7
+ import type { ActorLog, ActorLogEntry } from './actor-runtime'
8
+ import { formatTimeShort } from './format-when'
9
+
10
+ const MAX_LOG_ENTRIES = 50
11
+ const DEFAULT_INTERVAL_MS = 3_000
12
+ const MAX_BACKOFF_MS = 15_000
13
+
14
+ const buttonStyle = {
15
+ fontSize: 12,
16
+ fontWeight: 600,
17
+ color: '#f8f9fa',
18
+ border: '1px solid #373a40',
19
+ borderRadius: 6,
20
+ padding: '4px 12px',
21
+ } as const
22
+
23
+ type ActorState = 'running' | 'paused' | 'ticking' | 'held'
24
+
25
+ /** data-state → status-dot colour cue. Presentational only; the label stays translated. */
26
+ function stateColor(state: ActorState): string {
27
+ switch (state) {
28
+ case 'ticking':
29
+ return 'blue.4'
30
+ case 'held':
31
+ return 'yellow.4'
32
+ case 'running':
33
+ return 'teal.4'
34
+ default:
35
+ return 'gray.5'
36
+ }
37
+ }
38
+
39
+ export interface ActorShellProps {
40
+ actor: ActorId
41
+ /** One iteration of the actor's work. The shell supplies the log sink; the caller closes over
42
+ * its driver + memory. A throw triggers the error note + exponential backoff. */
43
+ tick: (log: ActorLog) => Promise<void>
44
+ startPaused: boolean
45
+ /** The WORLD's hold on its counterparties (e.g. a Simulator flag), asked before every AUTONOMOUS
46
+ * tick: while it answers true the loop keeps its schedule but does nothing. A manual Step is an
47
+ * explicit operator act and ignores it. Omit for an actor the world never holds. */
48
+ held?: () => boolean | Promise<boolean>
49
+ intervalMs?: number
50
+ /** Compact skin for the Actors-tab card (vs. the full-page host frame). */
51
+ inline?: boolean
52
+ }
53
+
54
+ /**
55
+ * The shared process UI + scheduler behind both actor frames (ADR-0006 twin lives in
56
+ * @sssb/kit/demo-static). A setTimeout CHAIN — the next tick is scheduled only after the previous one
57
+ * resolves, so ticks never overlap. Pause/resume halts and restarts the chain; Step runs exactly one
58
+ * awaited tick while paused (disabled mid-tick, which is the await handle a test waits on). The log
59
+ * is a 50-entry ring buffer; a thrown tick logs the error note and doubles the interval (capped
60
+ * 15s), reset on the next success. Dark-skinned to match the Simulator panel — it reads as "not the
61
+ * product". Router- and transport-agnostic: the `tick` closure owns all I/O.
62
+ */
63
+ export function ActorShell({ actor, tick, startPaused, held, intervalMs, inline = false }: ActorShellProps) {
64
+ const t = useTranslations('simulator')
65
+ const locale = useLocale()
66
+ const baseInterval = intervalMs ?? DEFAULT_INTERVAL_MS
67
+
68
+ const [paused, setPaused] = useState(startPaused)
69
+ const [ticking, setTicking] = useState(false)
70
+ const [entries, setEntries] = useState<ActorLogEntry[]>([])
71
+ const [worldHeld, setWorldHeld] = useState(false)
72
+
73
+ const pausedRef = useRef(startPaused)
74
+ const tickingRef = useRef(false)
75
+ const intervalRef = useRef(baseInterval)
76
+ const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
77
+ const mountedRef = useRef(false)
78
+
79
+ const log = useCallback<ActorLog>((entry) => {
80
+ setEntries((prev) => {
81
+ const next: ActorLogEntry[] = [
82
+ ...prev,
83
+ {
84
+ at: new Date().toISOString(),
85
+ line: entry.line,
86
+ ...(entry.note === undefined ? {} : { note: entry.note }),
87
+ },
88
+ ]
89
+ return next.length > MAX_LOG_ENTRIES ? next.slice(next.length - MAX_LOG_ENTRIES) : next
90
+ })
91
+ }, [])
92
+
93
+ const runTick = useCallback(async () => {
94
+ if (tickingRef.current) return
95
+ tickingRef.current = true
96
+ setTicking(true)
97
+ try {
98
+ await tick(log)
99
+ intervalRef.current = baseInterval // success resets the backoff
100
+ } catch (error) {
101
+ const message = error instanceof Error ? error.message : String(error)
102
+ log({ line: `tick error → ${message}`, note: t('actorNoteError', { message }) })
103
+ intervalRef.current = Math.min(intervalRef.current * 2, MAX_BACKOFF_MS)
104
+ } finally {
105
+ tickingRef.current = false
106
+ setTicking(false)
107
+ }
108
+ }, [tick, log, t, baseInterval])
109
+
110
+ // Keep the scheduler pointed at the latest runTick without re-creating the (stable) scheduler.
111
+ const runTickRef = useRef(runTick)
112
+ useEffect(() => {
113
+ runTickRef.current = runTick
114
+ }, [runTick])
115
+
116
+ // An autonomous tick asks the world first. A failed answer counts as "not held": the tick itself
117
+ // then surfaces whatever is wrong through the usual error note + backoff.
118
+ const heldRef = useRef(held)
119
+ useEffect(() => {
120
+ heldRef.current = held
121
+ }, [held])
122
+ const autonomousTick = useCallback(async () => {
123
+ // An async wrapper turns a synchronous throw into a rejection, so both count as "not held".
124
+ const isHeld = await (async () => (await heldRef.current?.()) ?? false)().catch(() => false)
125
+ if (!mountedRef.current) return
126
+ setWorldHeld(isHeld)
127
+ if (!isHeld) await runTickRef.current()
128
+ }, [])
129
+
130
+ // The chain: clear any pending timer, then (unless paused/unmounted) arm the next tick, which
131
+ // re-arms itself (via armRef — no self-reference) once it resolves. Stable (refs only) so
132
+ // mount/toggle can call it freely.
133
+ const armRef = useRef<() => void>(() => {})
134
+ const arm = useCallback(() => {
135
+ if (timeoutRef.current) {
136
+ clearTimeout(timeoutRef.current)
137
+ timeoutRef.current = null
138
+ }
139
+ if (pausedRef.current || !mountedRef.current) return
140
+ timeoutRef.current = setTimeout(() => {
141
+ timeoutRef.current = null
142
+ void autonomousTick().finally(() => armRef.current())
143
+ }, intervalRef.current)
144
+ }, [autonomousTick])
145
+ useEffect(() => {
146
+ armRef.current = arm
147
+ }, [arm])
148
+
149
+ useEffect(() => {
150
+ mountedRef.current = true
151
+ if (!pausedRef.current) arm()
152
+ return () => {
153
+ mountedRef.current = false
154
+ if (timeoutRef.current) clearTimeout(timeoutRef.current)
155
+ }
156
+ }, [arm])
157
+
158
+ function toggle() {
159
+ const next = !pausedRef.current
160
+ pausedRef.current = next
161
+ setPaused(next)
162
+ if (next) {
163
+ if (timeoutRef.current) {
164
+ clearTimeout(timeoutRef.current)
165
+ timeoutRef.current = null
166
+ }
167
+ } else {
168
+ arm()
169
+ }
170
+ }
171
+
172
+ function step() {
173
+ if (!pausedRef.current || tickingRef.current) return
174
+ void runTickRef.current()
175
+ }
176
+
177
+ const state: ActorState = ticking ? 'ticking' : paused ? 'paused' : worldHeld ? 'held' : 'running'
178
+
179
+ return (
180
+ <Box
181
+ data-testid="actor-shell"
182
+ data-actor={actor}
183
+ style={{
184
+ background: '#1a1b1e',
185
+ color: '#f8f9fa',
186
+ borderRadius: inline ? 8 : 0,
187
+ border: inline ? '1px solid rgba(255,255,255,0.12)' : 'none',
188
+ padding: inline ? 12 : 24,
189
+ minHeight: inline ? undefined : '100vh',
190
+ }}
191
+ >
192
+ <Stack gap="sm">
193
+ <Group justify="space-between" wrap="nowrap" gap="xs">
194
+ {/* The full-page host is a standalone document (and each iframe is too), so its
195
+ title is the page's level-one heading — axe requires one. The inline card
196
+ lives inside the dashboard's own <h1>, so it stays a plain <p>. */}
197
+ <Text component={inline ? 'p' : 'h1'} size={inline ? 'sm' : 'md'} fw={700} c="gray.0" truncate>
198
+ {t('actorFrameTitle', { actor })}
199
+ </Text>
200
+ <Group gap={8} wrap="nowrap" data-testid="actor-status" data-state={state}>
201
+ <Box
202
+ aria-hidden
203
+ style={{
204
+ width: 8,
205
+ height: 8,
206
+ borderRadius: 999,
207
+ background: `var(--mantine-color-${stateColor(state).replace('.', '-')})`,
208
+ }}
209
+ />
210
+ <Text size="xs" fw={700} c={stateColor(state)}>
211
+ {paused ? t('actorPaused') : worldHeld ? t('actorHeld') : t('actorRunning')}
212
+ </Text>
213
+ </Group>
214
+ </Group>
215
+
216
+ <Group gap={8} wrap="nowrap">
217
+ <UnstyledButton data-testid="actor-toggle" onClick={toggle} style={buttonStyle}>
218
+ {paused ? t('actorResumeButton') : t('actorPauseButton')}
219
+ </UnstyledButton>
220
+ <UnstyledButton
221
+ data-testid="actor-step"
222
+ onClick={step}
223
+ disabled={!paused || ticking}
224
+ style={{ ...buttonStyle, opacity: !paused || ticking ? 0.4 : 1 }}
225
+ >
226
+ {t('actorStepButton')}
227
+ </UnstyledButton>
228
+ </Group>
229
+
230
+ <Text size="xs" fw={700} c="gray.4" tt="uppercase" style={{ letterSpacing: 0.4 }}>
231
+ {t('actorLogHeading')}
232
+ </Text>
233
+ {entries.length === 0 ? (
234
+ <Text size="sm" c="gray.5" data-testid="actor-log-empty">
235
+ {t('actorLogEmpty')}
236
+ </Text>
237
+ ) : (
238
+ <Stack
239
+ gap={2}
240
+ data-testid="actor-log"
241
+ style={{ maxHeight: inline ? 220 : '60vh', overflowY: 'auto' }}
242
+ >
243
+ {entries.map((entry, index) => (
244
+ <Box
245
+ // Log entries are append-only and never reordered, so the index is a
246
+ // stable key here.
247
+ key={`${entry.at}-${index}`}
248
+ data-testid="actor-log-entry"
249
+ style={{ borderBottom: '1px solid rgba(255,255,255,0.08)', padding: '4px 0' }}
250
+ >
251
+ <Group gap={8} wrap="nowrap" align="baseline">
252
+ <Text size="xs" c="gray.6" style={{ flexShrink: 0, whiteSpace: 'nowrap' }}>
253
+ {formatTimeShort(entry.at, locale)}
254
+ </Text>
255
+ <Text
256
+ size="xs"
257
+ c="gray.2"
258
+ style={{ fontFamily: 'monospace', wordBreak: 'break-all', minWidth: 0 }}
259
+ >
260
+ {entry.line}
261
+ </Text>
262
+ </Group>
263
+ {entry.note ? (
264
+ <Text size="xs" c="gray.5" pl={4}>
265
+ {entry.note}
266
+ </Text>
267
+ ) : null}
268
+ </Box>
269
+ ))}
270
+ </Stack>
271
+ )}
272
+ </Stack>
273
+ </Box>
274
+ )
275
+ }
@@ -0,0 +1,119 @@
1
+ 'use client'
2
+
3
+ import { Box, Group, Stack, Text } from '@mantine/core'
4
+ import { useTranslations } from 'next-intl'
5
+ import type { ReactNode } from 'react'
6
+ import type { ActorId } from '@sssb/app-config/actors'
7
+ import { chipStyle } from './people-app'
8
+
9
+ /**
10
+ * One card's body plus its ALREADY-TRANSLATED label, host-supplied (ADR-0006: this component stays
11
+ * router- and transport-blind — and catalog-blind: WHICH counterparties exist is app vocabulary, so
12
+ * their copy belongs in the app's catalog and arrives here as finished strings, exactly like
13
+ * SimulatorExtraTab.label). The
14
+ * real glue hands over a same-origin iframe src pointing at the actor's own page; the static twin
15
+ * hands over an already-mounted ActorShell node running inline. A discriminated union keeps the two
16
+ * shapes mutually exclusive rather than an always-both-optional prop bag.
17
+ */
18
+ export type ActorSlot = { id: ActorId; title: string; description: string } & (
19
+ { iframeSrc: string } | { node: ReactNode }
20
+ )
21
+
22
+ export interface ActorsWorldCounts {
23
+ queued: number
24
+ running: number
25
+ completed: number
26
+ }
27
+
28
+ /**
29
+ * Router-agnostic Simulator Actors tab (ADR-0006 twin lives in @sssb/kit/demo-static): two labeled cards,
30
+ * one per actor (see src/app-config/actors.ts for the org split), each hosting its own process UI. A
31
+ * compact world strip above the cards reads the SAME cross-tenant job data the Jobs tab shows (held
32
+ * badge + queued/running/completed counts), so an operator can watch the pool drain without
33
+ * switching tabs. The Jobs tab itself stays — this is a live-process view, not a replacement for the
34
+ * full world list.
35
+ */
36
+ export function ActorsApp({
37
+ slots,
38
+ world,
39
+ }: {
40
+ slots: ActorSlot[]
41
+ world: { held: boolean; counts: ActorsWorldCounts }
42
+ }) {
43
+ const t = useTranslations('simulator')
44
+
45
+ return (
46
+ <Stack gap="sm" data-testid="simulator-actors">
47
+ <Text size="xs" c="gray.5">
48
+ {t('actorsHint')}
49
+ </Text>
50
+ <Group
51
+ justify="space-between"
52
+ wrap="nowrap"
53
+ gap="xs"
54
+ data-testid="simulator-actors-world"
55
+ style={{ border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8, padding: '6px 10px' }}
56
+ >
57
+ {world.held ? (
58
+ <Text
59
+ size="xs"
60
+ fw={700}
61
+ data-testid="actors-world-held"
62
+ style={{ background: '#5c3d00', color: '#ffd43b', borderRadius: 999, padding: '2px 10px' }}
63
+ >
64
+ {t('actorsWorldHeld')}
65
+ </Text>
66
+ ) : (
67
+ <span />
68
+ )}
69
+ <Text size="xs" c="gray.3" style={chipStyle}>
70
+ {t('actorsWorldCounts', {
71
+ queued: world.counts.queued,
72
+ running: world.counts.running,
73
+ completed: world.counts.completed,
74
+ })}
75
+ </Text>
76
+ </Group>
77
+ {slots.map((slot) => (
78
+ <Box
79
+ key={slot.id}
80
+ data-testid={`actor-card-${slot.id}`}
81
+ style={{ border: '1px solid rgba(255,255,255,0.18)', borderRadius: 8, padding: 10 }}
82
+ >
83
+ <Stack gap={6}>
84
+ <Stack gap={2}>
85
+ <Text size="sm" fw={700} c="gray.0">
86
+ {slot.title}
87
+ </Text>
88
+ <Text size="xs" c="gray.5">
89
+ {slot.description}
90
+ </Text>
91
+ </Stack>
92
+ {'node' in slot ? (
93
+ slot.node
94
+ ) : (
95
+ // These frames are OUR OWN same-origin pages (src/app/[locale]/simulator/actors/
96
+ // [actor]) that must run their own scripts AND make same-origin fetch calls
97
+ // (minting a service token, producing an artifact, posting status/webhook
98
+ // updates) — the opposite trust class from MailApp's reading-pane iframe, which
99
+ // renders UNTRUSTED caught-email HTML and is deliberately sandboxed to an OPAQUE
100
+ // origin with only allow-scripts (no allow-same-origin) so that content can never
101
+ // touch the app's origin, cookies, or fetch. An actor frame is trusted, first-
102
+ // party code that NEEDS the real origin for fetch()/cookies to work at all, so
103
+ // `sandbox="allow-scripts"` alone would break it (opaque origin ≠ same origin).
104
+ // Omitting `sandbox` entirely keeps the frame's privileges identical to a normal
105
+ // same-origin navigation — nothing gained, nothing given up beyond what a page
106
+ // already has.
107
+ <iframe
108
+ title={t('actorFrameTitle', { actor: slot.id })}
109
+ src={slot.iframeSrc}
110
+ data-testid={`actor-frame-${slot.id}`}
111
+ style={{ width: '100%', height: 320, border: 0, borderRadius: 6, background: '#111' }}
112
+ />
113
+ )}
114
+ </Stack>
115
+ </Box>
116
+ ))}
117
+ </Stack>
118
+ )
119
+ }