create-ailk 0.35.1 → 0.37.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 (169) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +51 -1
  3. package/component-catalog.md +8 -5
  4. package/dist/lib/env-catalog.js +8 -0
  5. package/dist/surfaces.js +66 -22
  6. package/dist/topology.d.ts +4 -4
  7. package/dist/topology.js +104 -60
  8. package/dist/update.d.ts +19 -1
  9. package/dist/update.js +293 -35
  10. package/package.json +3 -3
  11. package/templates/.env.example +38 -0
  12. package/templates/apps/api/.env.example +45 -0
  13. package/templates/apps/api/CLAUDE.md +12 -4
  14. package/templates/apps/api/src/lib/__mocks__/prisma.ts +7 -0
  15. package/templates/apps/mcp/CLAUDE.md +4 -2
  16. package/templates/apps/web/.env.example +16 -0
  17. package/templates/apps/web/CLAUDE.md +73 -5
  18. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  19. package/templates/apps/web/app/[locale]/(auth)/reset-password/__tests__/return.test.tsx +179 -0
  20. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +22 -2
  21. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +9 -2
  22. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  23. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  24. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  25. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  26. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  27. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  28. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  29. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  30. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +241 -66
  31. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +242 -28
  32. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +377 -151
  33. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +26 -1
  34. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  35. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +17 -6
  36. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-menu.test.tsx +51 -12
  37. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/new-popups.test.tsx +17 -2
  38. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +153 -2
  39. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +206 -23
  40. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/popups.test.tsx +150 -188
  41. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +235 -177
  42. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/rich-translator.ts +63 -0
  43. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +0 -3
  44. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/thread.test.tsx +340 -0
  45. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +7 -5
  46. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +20 -4
  47. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +8 -4
  48. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +161 -0
  49. package/templates/apps/web/app/[locale]/(authed)/account/appointments/__tests__/page.test.tsx +426 -0
  50. package/templates/apps/web/app/[locale]/(authed)/account/appointments/appointments-data.ts +76 -0
  51. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +139 -0
  52. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +92 -24
  53. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +32 -1
  54. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/file-route.test.ts +76 -3
  55. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +290 -41
  56. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +109 -11
  57. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +43 -44
  58. package/templates/apps/web/app/[locale]/(authed)/account/billing/__tests__/offerings.test.ts +99 -0
  59. package/templates/apps/web/app/[locale]/(authed)/account/billing/offerings.ts +123 -0
  60. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +323 -73
  61. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +199 -43
  62. package/templates/apps/web/app/[locale]/(authed)/account/components/request-quote.tsx +52 -7
  63. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  64. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  65. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  66. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  67. package/templates/apps/web/app/[locale]/(authed)/account/general/account-name.ts +36 -0
  68. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +70 -2
  69. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-details.tsx +42 -0
  70. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +97 -53
  71. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  72. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +215 -0
  73. package/templates/apps/web/app/[locale]/(authed)/account/general/photo-actions.ts +73 -0
  74. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-form.tsx +12 -9
  75. package/templates/apps/web/app/[locale]/(authed)/account/general/profile-source.ts +18 -4
  76. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +20 -2
  77. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/member-thread-composer.tsx +43 -0
  78. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +125 -0
  79. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-data.ts +88 -0
  80. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/thread-write.ts +31 -0
  81. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  82. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  83. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  84. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  85. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  86. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +9 -6
  87. package/templates/apps/web/app/[locale]/(authed)/account/new-menu.tsx +33 -8
  88. package/templates/apps/web/app/[locale]/(authed)/account/new-popups.tsx +31 -52
  89. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +44 -4
  90. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +69 -49
  91. package/templates/apps/web/app/[locale]/(authed)/account/privacy/__tests__/export-route.test.ts +173 -0
  92. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +42 -4
  93. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +102 -0
  94. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +147 -137
  95. package/templates/apps/web/app/[locale]/(authed)/account/security/__tests__/hub-variant.test.tsx +258 -0
  96. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +21 -22
  97. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +34 -6
  98. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +37 -7
  99. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +0 -2
  100. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +8 -5
  101. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  102. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  103. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +3 -2
  104. package/templates/apps/web/app/[locale]/layout.tsx +24 -75
  105. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  106. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  107. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  108. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +166 -7
  109. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +96 -30
  110. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  111. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  112. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  113. package/templates/apps/web/app/api/auth/hub/password/__tests__/return.test.ts +86 -0
  114. package/templates/apps/web/app/api/auth/hub/password/__tests__/route.test.ts +368 -0
  115. package/templates/apps/web/app/api/auth/hub/password/return.ts +86 -0
  116. package/templates/apps/web/app/api/auth/hub/password/route.ts +171 -0
  117. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  118. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  119. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  120. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  121. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +738 -7
  122. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  123. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  124. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  125. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  126. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  127. package/templates/apps/web/app/api/hub-session/password/return/route.ts +69 -0
  128. package/templates/apps/web/app/api/hub-session/password/route.ts +106 -0
  129. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  130. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  131. package/templates/apps/web/auth.ts +133 -6
  132. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  133. package/templates/apps/web/lib/__tests__/account-config.test.ts +129 -1
  134. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  135. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  136. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  137. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  138. package/templates/apps/web/lib/__tests__/offerings-pricing.test.ts +33 -0
  139. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  140. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  141. package/templates/apps/web/lib/account-config.ts +132 -8
  142. package/templates/apps/web/lib/auth-email.ts +62 -6
  143. package/templates/apps/web/lib/auth-env.ts +13 -0
  144. package/templates/apps/web/lib/auth-routes.ts +11 -6
  145. package/templates/apps/web/lib/auth-sms.ts +180 -0
  146. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  147. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  148. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  149. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  150. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  151. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  152. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  153. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  154. package/templates/apps/web/lib/offerings-pricing.ts +4 -1
  155. package/templates/apps/web/lib/site-header.ts +14 -1
  156. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  157. package/templates/apps/web/lib/topology.generated.ts +39 -0
  158. package/templates/apps/web/messages/en.json +264 -96
  159. package/templates/apps/web/middleware.ts +34 -2
  160. package/templates/apps/web/security-headers.config.ts +21 -0
  161. package/versions.json +48 -48
  162. package/templates/apps/web/app/[locale]/(authed)/account/components/schedule-service.tsx +0 -276
  163. package/templates/apps/web/app/[locale]/(authed)/account/components/send-message.tsx +0 -128
  164. package/templates/apps/web/app/[locale]/(authed)/account/settings/__tests__/theme-modes.test.ts +0 -42
  165. package/templates/apps/web/app/[locale]/(authed)/account/settings/theme-modes.ts +0 -40
  166. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  167. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  168. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  169. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -0,0 +1,125 @@
1
+ /**
2
+ * /[locale]/account/inbox/thread — the member's conversation with the
3
+ * workspace (#11152; operator ruling 2026-11-08).
4
+ *
5
+ * RSC, inside the account layout's SignedInShell (the rail keeps Inbox
6
+ * selected under /account/inbox/…). The Admin reads a client's exchange as
7
+ * one per-person thread page; the member gets the same page shape, through
8
+ * the same shared pieces (`@working-theory/templates/account`): the Record
9
+ * frame — `InboxItemFrame layout="chat"`, its `RecordHeader` titled
10
+ * Messages with the back link to the Inbox's Messages tab — over every
11
+ * message between this person and the workspace, OLDEST FIRST, each the
12
+ * bubble its own Inbox kind renders (`renderDetail`: the provider's messages
13
+ * on the start side, the member's own sent requests and messages on the
14
+ * end), a message's own actions (a file's Download, Open onboarding) under
15
+ * its bubble, and the shared `ThreadComposer` pinned at the foot
16
+ * (`member-thread-composer.tsx`): one field, Send, the existing member
17
+ * message write. The New menu's Send message navigates here (#11152 AC-1);
18
+ * the lightbox it opened is retired. One stream per (person, workspace):
19
+ * `thread-data.ts` records the decision.
20
+ *
21
+ * An empty thread reads the empty line above the composer; a kind's failed
22
+ * read renders the error row with Retry above what did load (D12's
23
+ * posture); signed out is a not-found (the layout's gate renders in the
24
+ * page's place).
25
+ */
26
+
27
+ import { InboxItemFrame, type InboxItemAction } from "@working-theory/templates/account";
28
+ import { localeHref } from "@working-theory/ui";
29
+ import { Button, Link, Text } from "@working-theory/ui/primitives";
30
+ import type { Metadata } from "next";
31
+ import { notFound } from "next/navigation";
32
+ import { getTranslations } from "next-intl/server";
33
+ import type { ReactElement } from "react";
34
+
35
+ import { accountSession } from "../../account-data";
36
+ import { ErrorRow } from "../../error-row";
37
+ import { newActionErrorLabels } from "../../new-popups";
38
+
39
+ import { MemberThreadComposer } from "./member-thread-composer";
40
+ import { loadThread } from "./thread-data";
41
+
42
+ interface Props {
43
+ params: Promise<{ locale: string }>;
44
+ }
45
+
46
+ export async function generateMetadata({ params }: Props): Promise<Metadata> {
47
+ const { locale } = await params;
48
+ const t = await getTranslations({ locale, namespace: "account" });
49
+ return { title: t("thread.title") };
50
+ }
51
+
52
+ /** A bubble's own action, as a small link under it; an RSC detail carries `href` actions only. */
53
+ function EntryAction({ action }: { action: InboxItemAction }): ReactElement | null {
54
+ if (action.href === undefined) return null;
55
+ return (
56
+ <Button asChild variant={action.variant} size="thin">
57
+ <Link href={action.href} variant="bare" data-testid={`account-thread-action-${action.key}`}>
58
+ {action.label}
59
+ </Link>
60
+ </Button>
61
+ );
62
+ }
63
+
64
+ export default async function AccountThreadPage({ params }: Props): Promise<ReactElement> {
65
+ const { locale } = await params;
66
+ const t = await getTranslations({ locale, namespace: "account" });
67
+ const session = await accountSession(locale);
68
+ if (!session) notFound();
69
+
70
+ const { entries, failed } = await loadThread(session.ctx);
71
+ // The refusal lines the composer shows, keyed on `sendMessage`'s codes — the popups' own map.
72
+ const errors = newActionErrorLabels(session.ctx.t);
73
+
74
+ return (
75
+ <InboxItemFrame
76
+ layout="chat"
77
+ back={{ href: localeHref(locale, "/account?tab=messages"), label: t("inbox.back") }}
78
+ caption={t("thread.title")}
79
+ title={t("thread.title")}
80
+ testIdPrefix="account-thread"
81
+ composer={
82
+ <MemberThreadComposer
83
+ labels={{
84
+ label: t("thread.composer.label"),
85
+ body: t("thread.composer.body"),
86
+ placeholder: t("thread.composer.placeholder"),
87
+ send: t("thread.composer.send"),
88
+ sending: t("thread.composer.sending"),
89
+ sent: t("thread.composer.sent"),
90
+ needsContent: t("thread.composer.needsContent"),
91
+ failed: t("new.errors.failed"),
92
+ }}
93
+ errors={errors}
94
+ />
95
+ }
96
+ >
97
+ {failed ? <ErrorRow message={t("thread.error")} retryLabel={t("inbox.retry")} /> : null}
98
+ {!failed && entries.length === 0 ? (
99
+ <Text as="p" variant="body-sm" tone="muted" data-testid="account-thread-empty">
100
+ {t("thread.empty")}
101
+ </Text>
102
+ ) : null}
103
+ {entries.map(({ kind, item }) => {
104
+ const detail = kind.renderDetail(item, session.ctx);
105
+ return (
106
+ <div
107
+ key={`${kind.kind}:${item.id}`}
108
+ className="flex flex-col gap-2"
109
+ data-testid="account-thread-entry"
110
+ data-kind={kind.kind}
111
+ >
112
+ {detail.body}
113
+ {detail.actions && detail.actions.length > 0 ? (
114
+ <div className="flex flex-wrap gap-2">
115
+ {detail.actions.map((action) => (
116
+ <EntryAction key={action.key} action={action} />
117
+ ))}
118
+ </div>
119
+ ) : null}
120
+ </div>
121
+ );
122
+ })}
123
+ </InboxItemFrame>
124
+ );
125
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * thread-data.ts — the member thread page's reads (#11152).
3
+ *
4
+ * The thread is every message between the signed-in person and this
5
+ * workspace: the conversation kinds of `lib/account-config.ts`
6
+ * (`accountChatKinds`) — the provider's messages (`message`,
7
+ * `GET /v1/member/messages`) and the person's own sent requests and messages
8
+ * (`request`, `GET /v1/member/requests`) — merged and sorted OLDEST FIRST,
9
+ * the Admin thread's order, each entry keeping the kind that loaded it so
10
+ * the page renders the same bubble the item page shows. A kind's rejected
11
+ * read sets `failed` (D12: the page shows the error row above what did
12
+ * load, never a silently partial thread); a 404 is already `[]` inside the
13
+ * kind's own `load`.
14
+ *
15
+ * One stream per (person, workspace) — the design decision this page rests
16
+ * on (issue #11152, operator question of 2026-11-08, recorded here because
17
+ * the issue carries no spec): the data model keys every message on exactly
18
+ * that pair (`Interaction` rows on the person's `Person` in this workspace;
19
+ * the member reads above resolve the pair from the credential), and the
20
+ * Admin's thread page is one stream per person. A second stream would need
21
+ * a new subject entity on both sides — a thread id stamped on each
22
+ * `Interaction`, a member read and write that take it, an Admin thread list
23
+ * and page keyed on it — and is not this page's.
24
+ *
25
+ * `threadSubject` — the member composer has one field, no Subject (#11007's
26
+ * composer shape), yet `POST /v1/member/messages` requires one: the subject
27
+ * is cut from the body's first non-blank line, whitespace collapsed and
28
+ * clipped to the server's cap. A blank body yields `""`, which the server
29
+ * refuses — the composer never posts a blank body.
30
+ */
31
+
32
+ import type {
33
+ AccountContext,
34
+ AccountInboxItem,
35
+ AccountInboxKind,
36
+ } from "@working-theory/templates/account";
37
+ import { MESSAGE_SUBJECT_MAX } from "@working-theory/validation";
38
+
39
+ import { accountChatKinds, accountInboxKinds } from "../../../../../../lib/account-config";
40
+ import { logReadFailure } from "../../account-data";
41
+
42
+ /** One loaded message with the kind it came from — what a bubble is built from. */
43
+ export interface ThreadEntry {
44
+ kind: AccountInboxKind;
45
+ item: AccountInboxItem;
46
+ }
47
+
48
+ export interface LoadedThread {
49
+ /** Oldest first. */
50
+ entries: ThreadEntry[];
51
+ /** True when a kind's read rejected (D12). */
52
+ failed: boolean;
53
+ }
54
+
55
+ /** The conversation kinds, in the config's order. */
56
+ const threadKinds = accountInboxKinds.filter((kind) => accountChatKinds.has(kind.kind));
57
+
58
+ // Both conversation kinds set `at` from the row's `createdAt`; the `""`
59
+ // fallback (an entry with no time sorts first) is `account-data.ts`'s idiom,
60
+ // kept so a kind that omitted it would still render rather than throw.
61
+ const oldestFirst = (a: ThreadEntry, b: ThreadEntry): number =>
62
+ (a.item.at ?? "").localeCompare(b.item.at ?? "");
63
+
64
+ /** Every conversation kind's items, oldest first. A rejected kind sets `failed`. */
65
+ export async function loadThread(ctx: AccountContext): Promise<LoadedThread> {
66
+ const settled = await Promise.allSettled(
67
+ threadKinds.map(async (kind) => (await kind.load(ctx)).map((item) => ({ kind, item }))),
68
+ );
69
+ settled.forEach((r, i) => {
70
+ if (r.status === "rejected") logReadFailure(`thread:${threadKinds[i]!.kind}`, r.reason);
71
+ });
72
+ return {
73
+ entries: settled
74
+ .flatMap((r) => (r.status === "fulfilled" ? r.value : []))
75
+ .sort(oldestFirst),
76
+ failed: settled.some((r) => r.status === "rejected"),
77
+ };
78
+ }
79
+
80
+ /** The subject the member write needs, cut from the body's first non-blank line. */
81
+ export function threadSubject(body: string): string {
82
+ const line =
83
+ body
84
+ .split(/\r?\n/)
85
+ .map((part) => part.replace(/\s+/g, " ").trim())
86
+ .find((part) => part !== "") ?? "";
87
+ return line.slice(0, MESSAGE_SUBJECT_MAX);
88
+ }
@@ -0,0 +1,31 @@
1
+ "use server";
2
+
3
+ /**
4
+ * thread-write.ts — the member thread composer's post (#11152).
5
+ *
6
+ * The thread's composer has one field; the member write it runs is the
7
+ * EXISTING one — `sendMessage` (`../../new-actions.ts`, #8170's
8
+ * `member.sendMessage`, `POST /v1/member/messages`) — handed the body as
9
+ * typed and a subject cut from its first line (`threadSubject`). No new
10
+ * write, no new route: the message lands as the same inbound `Interaction`
11
+ * on the person's Person the retired lightbox wrote, so the Admin's thread
12
+ * for that person shows it (#11157). The refusal codes are `sendMessage`'s
13
+ * own; the composer's host maps each to its line.
14
+ *
15
+ * Not a `*.actions.ts` file and no `*Action`-suffixed export, for the same
16
+ * reason `new-actions.ts` is not (apps/mcp's parity test reads that suffix;
17
+ * the member writes have no MCP twin by decision). Action input is
18
+ * untrusted: anything but a string is `invalid_input`.
19
+ */
20
+
21
+ import { sendMessage, type NewActionState } from "../../new-actions";
22
+
23
+ import { threadSubject } from "./thread-data";
24
+
25
+ export async function postThreadMessage(body: unknown): Promise<NewActionState> {
26
+ if (typeof body !== "string") return { kind: "error", code: "invalid_input" };
27
+ const formData = new FormData();
28
+ formData.set("subject", threadSubject(body));
29
+ formData.set("body", body);
30
+ return sendMessage({ kind: "idle" }, formData);
31
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @jest-environment node
3
+ */
4
+ // `isInvitationId` (#11141): the `invite_` + uuid check the invitation page
5
+ // and its actions run before any call. It lives in a plain module — a
6
+ // synchronous export of the "use server" actions file fails `next build`.
7
+
8
+ import { readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+
11
+ import { isInvitationId } from "../invitation-id";
12
+
13
+ describe("isInvitationId", () => {
14
+ it("accepts `invite_` + a lowercase uuid", () => {
15
+ expect(isInvitationId("invite_01920000-0000-7000-8000-000000000001")).toBe(true);
16
+ });
17
+
18
+ it.each([
19
+ "",
20
+ "01920000-0000-7000-8000-000000000001",
21
+ "invite_01920000-0000-7000-8000-00000000000",
22
+ "invite_01920000-0000-7000-8000-0000000000011",
23
+ "invite_01920000-0000-7000-8000-00000000000G",
24
+ "INVITE_01920000-0000-7000-8000-000000000001",
25
+ "invite_01920000-0000-7000-8000-000000000001/accept",
26
+ "../invite_01920000-0000-7000-8000-000000000001",
27
+ ])("rejects %j", (value) => {
28
+ expect(isInvitationId(value)).toBe(false);
29
+ });
30
+
31
+ it('is not a "use server" module', () => {
32
+ const source = readFileSync(join(__dirname, "..", "invitation-id.ts"), "utf8");
33
+ expect(source).not.toMatch(/^\s*["']use server["']/m);
34
+ });
35
+ });
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The account invitation page (#11106, spec
3
+ * docs/specs/11106-the-workforce-foundation-roles-by-spec.md D5; AC-3's page
4
+ * bullet).
5
+ *
6
+ * - Signed out, the `(authed)` gate redirects the page to
7
+ * `/sign-in?next=…` (asserted on the thrown `NEXT_REDIRECT`), and the
8
+ * mailed URL renders `/sign-in` with the email input's value set.
9
+ * - Signed in: a pending invitation renders the organization, the inviter,
10
+ * the role and Accept — a form POST. A GET of the page reads once and
11
+ * writes nothing.
12
+ * - Accept POSTs `/v1/invitations/:id/accept` with no email in its body and
13
+ * returns to the page with `?joined=1`, or `?error=<code>` on a refusal.
14
+ * - Another address's invitation renders the refusal; a missing one is
15
+ * `notFound()`.
16
+ *
17
+ * The API is the boundary: `fetch` answers here. `next-intl/server` reads the
18
+ * real en.json with placeholders filled.
19
+ */
20
+ import { render, screen, within } from "@testing-library/react";
21
+
22
+ const mockGetActiveProviderIds = jest.fn();
23
+ // eslint-disable-next-line no-restricted-syntax -- #507: auth-env.ts is a pure env-introspection module with no external boundary to mock instead; a PARTIAL mock, so every predicate the gate and /sign-in call is declared.
24
+ jest.mock("../../../../../../../lib/auth-env", () => ({
25
+ __esModule: true,
26
+ getActiveProviderIds: () => mockGetActiveProviderIds(),
27
+ isResetAvailable: () => false,
28
+ resetSendConfigured: () => false,
29
+ }));
30
+
31
+ const mockGetSession = jest.fn();
32
+ // eslint-disable-next-line no-restricted-syntax -- #507: auth.ts is Better Auth's server singleton (a DB/HTTP boundary); the gate reads its session and /sign-in its secret.
33
+ jest.mock("../../../../../../../auth", () => ({
34
+ __esModule: true,
35
+ auth: { api: { getSession: (...args: unknown[]) => mockGetSession(...args) } },
36
+ resolveSecret: () => "test-secret-for-the-invitation-page-suite",
37
+ }));
38
+
39
+ let mockRequestPathname: string | undefined;
40
+ jest.mock("next/headers", () => ({
41
+ __esModule: true,
42
+ headers: jest.fn(async () => {
43
+ const h = new Headers({ origin: "https://hub.example" });
44
+ if (mockRequestPathname) h.set("x-pathname", mockRequestPathname);
45
+ return h;
46
+ }),
47
+ cookies: jest.fn(async () => ({
48
+ toString: () => "better-auth.session_token=abc",
49
+ get: () => undefined,
50
+ })),
51
+ }));
52
+
53
+ jest.mock("next/navigation", () => ({
54
+ __esModule: true,
55
+ redirect: (url: string): never => {
56
+ throw new Error(`NEXT_REDIRECT ${url}`);
57
+ },
58
+ notFound: (): never => {
59
+ throw new Error("NEXT_NOT_FOUND");
60
+ },
61
+ }));
62
+
63
+ jest.mock("@working-theory/web-i18n", () => ({
64
+ __esModule: true,
65
+ readLocales: jest.fn().mockReturnValue(["en", "fr"]),
66
+ }));
67
+
68
+ jest.mock("better-auth/react", () => ({
69
+ __esModule: true,
70
+ createAuthClient: () => ({ signIn: { social: jest.fn(), email: jest.fn() } }),
71
+ }));
72
+
73
+ jest.mock("@working-theory/api-client", () => ({
74
+ __esModule: true,
75
+ getApiBase: () => "https://api.hub.example",
76
+ hubSignIn: { clientInfo: jest.fn() },
77
+ }));
78
+
79
+ jest.mock("next-intl/server", () => {
80
+ const messages = jest.requireActual("../../../../../../../messages/en.json") as Record<string, unknown>;
81
+ const lookup = (namespace: string, key: string): unknown =>
82
+ `${namespace}.${key}`
83
+ .split(".")
84
+ .reduce<unknown>(
85
+ (node, part) => (node && typeof node === "object" ? (node as Record<string, unknown>)[part] : undefined),
86
+ messages,
87
+ );
88
+ return {
89
+ __esModule: true,
90
+ getTranslations: async ({ namespace }: { namespace: string }) => {
91
+ const t = (key: string, values?: Record<string, string>): string => {
92
+ const found = lookup(namespace, key);
93
+ return (typeof found === "string" ? found : `${namespace}.${key}`).replace(
94
+ /\{(\w+)\}/g,
95
+ (match, name: string) => values?.[name] ?? match,
96
+ );
97
+ };
98
+ t.has = (key: string): boolean => typeof lookup(namespace, key) === "string";
99
+ return t;
100
+ },
101
+ };
102
+ });
103
+
104
+ import en from "../../../../../../../messages/en.json";
105
+ import SignInPage from "../../../../../(auth)/sign-in/page";
106
+ import AuthedLayout from "../../../../layout";
107
+ import { acceptInvitation } from "../actions";
108
+ import InvitationPage from "../page";
109
+
110
+ const ID = "invite_01920000-0000-7000-8000-000000000001";
111
+ const ADDRESS = "invitee@example.test";
112
+
113
+ type Call = { url: string; method: string; body: unknown; headers: Record<string, string> };
114
+ const calls: Call[] = [];
115
+ let answer: { status: number; body: unknown } = { status: 200, body: null };
116
+
117
+ const realFetch = globalThis.fetch;
118
+ beforeEach(() => {
119
+ calls.length = 0;
120
+ mockRequestPathname = undefined;
121
+ mockGetActiveProviderIds.mockReset().mockReturnValue(["google", "email", "magic-link"]);
122
+ mockGetSession.mockReset().mockResolvedValue({ user: { email: ADDRESS, emailVerified: true } });
123
+ globalThis.fetch = jest.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
124
+ calls.push({
125
+ url: String(input),
126
+ method: init?.method ?? "GET",
127
+ body: init?.body ?? null,
128
+ headers: (init?.headers ?? {}) as Record<string, string>,
129
+ });
130
+ // A minimal answer: jsdom's global scope has no `Response`.
131
+ const { status, body } = answer;
132
+ // eslint-disable-next-line no-restricted-syntax -- the fetch boundary's double: the actions read only `status` and `json()`, and jsdom has no Response to build a real one.
133
+ return { status, json: async () => body } as unknown as Response;
134
+ }) as typeof fetch;
135
+ });
136
+ afterAll(() => {
137
+ globalThis.fetch = realFetch;
138
+ });
139
+
140
+ const pending = {
141
+ ok: true,
142
+ data: {
143
+ organizationName: "Acme Studio",
144
+ inviterName: "Sam Rivera",
145
+ role: "editor",
146
+ status: "pending",
147
+ expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
148
+ },
149
+ };
150
+
151
+ async function renderInvitation(search: Record<string, string> = {}): Promise<void> {
152
+ const el = await InvitationPage({
153
+ params: Promise.resolve({ locale: "en", invitationId: ID }),
154
+ searchParams: Promise.resolve(search),
155
+ });
156
+ render(el);
157
+ }
158
+
159
+ describe("signed out", () => {
160
+ it("the (authed) gate redirects the page to /sign-in?next=…", async () => {
161
+ mockGetSession.mockResolvedValue(null);
162
+ mockRequestPathname = `/account/invitations/${ID}`;
163
+ await expect(
164
+ AuthedLayout({ children: null, params: Promise.resolve({ locale: "en" }) }),
165
+ ).rejects.toThrow(`NEXT_REDIRECT /sign-in?next=${encodeURIComponent(`/account/invitations/${ID}`)}`);
166
+ });
167
+
168
+ it("the mailed URL renders /sign-in with the invited address in the email input", async () => {
169
+ const mailed = new URL(
170
+ `https://hub.example/sign-in?next=%2Faccount%2Finvitations%2F${ID}&email=${encodeURIComponent(ADDRESS)}`,
171
+ );
172
+ const el = await SignInPage({
173
+ params: Promise.resolve({ locale: "en" }),
174
+ searchParams: Promise.resolve(Object.fromEntries(mailed.searchParams)),
175
+ });
176
+ render(el);
177
+ expect(mailed.pathname).toBe("/sign-in");
178
+ expect(screen.getByTestId("auth-email")).toHaveValue(ADDRESS);
179
+ });
180
+ });
181
+
182
+ describe("signed in", () => {
183
+ it("a pending invitation renders the organization, inviter and role, and Accept is a form POST", async () => {
184
+ answer = { status: 200, body: pending };
185
+ await renderInvitation();
186
+ expect(screen.getByTestId("account-invitation-lead")).toHaveTextContent(
187
+ "Sam Rivera invited you to join Acme Studio as an editor.",
188
+ );
189
+ const form = screen.getByTestId("account-invitation-form");
190
+ expect(form.tagName).toBe("FORM");
191
+ expect(within(form).getByTestId("account-invitation-accept")).toHaveAttribute("type", "submit");
192
+ expect(within(form).getByTestId("account-invitation-accept")).toHaveTextContent(en.account.invitation.accept);
193
+ });
194
+
195
+ it("a GET of the page reads once and writes nothing", async () => {
196
+ answer = { status: 200, body: pending };
197
+ await renderInvitation();
198
+ expect(calls).toHaveLength(1);
199
+ expect(calls[0]).toMatchObject({ url: `https://api.hub.example/v1/invitations/${ID}`, method: "GET" });
200
+ expect(calls[0]!.headers.cookie).toBe("better-auth.session_token=abc");
201
+ });
202
+
203
+ it("another address's invitation renders the refusal", async () => {
204
+ answer = {
205
+ status: 403,
206
+ body: { ok: false, error: { code: "invitation_for_another_address", message: "Forbidden" } },
207
+ };
208
+ await renderInvitation();
209
+ expect(screen.getByTestId("account-invitation-other-address")).toHaveTextContent(
210
+ "This invitation is for a different email address. Sign out and sign in with the invited address.",
211
+ );
212
+ expect(screen.queryByTestId("account-invitation-form")).toBeNull();
213
+ });
214
+
215
+ it("a missing invitation, or a malformed id, is notFound()", async () => {
216
+ answer = { status: 404, body: { ok: false, error: { code: "not_found", message: "Not found" } } };
217
+ await expect(renderInvitation()).rejects.toThrow("NEXT_NOT_FOUND");
218
+ calls.length = 0;
219
+ await expect(
220
+ InvitationPage({
221
+ params: Promise.resolve({ locale: "en", invitationId: "../../admin" }),
222
+ searchParams: Promise.resolve({}),
223
+ }),
224
+ ).rejects.toThrow("NEXT_NOT_FOUND");
225
+ expect(calls).toHaveLength(0);
226
+ });
227
+
228
+ it("after joining it reads You've joined <organization>.", async () => {
229
+ answer = { status: 200, body: { ok: true, data: { ...pending.data, status: "accepted" } } };
230
+ await renderInvitation({ joined: "1" });
231
+ expect(screen.getByTestId("account-invitation-joined")).toHaveTextContent("You've joined Acme Studio.");
232
+ });
233
+
234
+ it("a refusal returned by accept shows its line beside the form", async () => {
235
+ answer = { status: 200, body: pending };
236
+ await renderInvitation({ error: "invitation_expired" });
237
+ expect(screen.getByTestId("account-invitation-error")).toHaveTextContent(en.account.invitation.expired);
238
+ });
239
+ });
240
+
241
+ describe("acceptInvitation", () => {
242
+ it("POSTs accept with the session and no email, then returns with ?joined=1", async () => {
243
+ answer = { status: 200, body: { ok: true, data: { status: "accepted", organizationName: "Acme Studio", role: "editor" } } };
244
+ await expect(acceptInvitation(ID, "en")).rejects.toThrow(`NEXT_REDIRECT /account/invitations/${ID}?joined=1`);
245
+ expect(calls).toHaveLength(1);
246
+ expect(calls[0]).toMatchObject({ url: `https://api.hub.example/v1/invitations/${ID}/accept`, method: "POST", body: "{}" });
247
+ expect(calls[0]!.headers.origin).toBe("https://hub.example");
248
+ });
249
+
250
+ it.each([
251
+ ["invitation_expired", 409],
252
+ ["invitation_for_another_address", 403],
253
+ ["invitation_void", 409],
254
+ ])("a %s refusal returns with ?error=%s", async (code, status) => {
255
+ answer = { status, body: { ok: false, error: { code, message: "x" } } };
256
+ await expect(acceptInvitation(ID, "en")).rejects.toThrow(`NEXT_REDIRECT /account/invitations/${ID}?error=${code}`);
257
+ });
258
+
259
+ it("anything else, or a malformed id, returns ?error=failed", async () => {
260
+ answer = { status: 500, body: null };
261
+ await expect(acceptInvitation(ID, "en")).rejects.toThrow(`?error=failed`);
262
+ calls.length = 0;
263
+ await expect(acceptInvitation("nope", "en")).rejects.toThrow(`?error=failed`);
264
+ expect(calls).toHaveLength(0);
265
+ });
266
+ });
@@ -0,0 +1,116 @@
1
+ "use server";
2
+
3
+ /**
4
+ * account/invitations/[invitationId]/actions.ts — the invitee's two calls
5
+ * (#11106, spec docs/specs/11106-the-workforce-foundation-roles-by-spec.md
6
+ * D5): read the invitation, and accept it.
7
+ *
8
+ * GET /v1/invitations/:invitationId → `readInvitation`
9
+ * POST /v1/invitations/:invitationId/accept → `acceptInvitation`
10
+ *
11
+ * Both are server-side fetches carrying the person's own session
12
+ * (`forwardedCookieInit()`: the cookie and, on the POST, the request's
13
+ * `Origin` the API's CSRF check needs). The API answers only the invited,
14
+ * verified address — the invitation id is the only input, never an email.
15
+ * `@working-theory/api-client` carries no invitation namespace, so the call is
16
+ * a bare `fetch` to its `getApiBase()` (the `app/openapi.json/route.ts`
17
+ * precedent).
18
+ *
19
+ * Accepting is a form POST to `acceptInvitation`, bound to the id and locale
20
+ * by the page; it redirects back to the page with `?joined=1` or `?error=<code>`
21
+ * — a GET of the page never writes. Logs carry a status or a code only.
22
+ *
23
+ * Not a `*.actions.ts` file and no `*Action`-suffixed export: accepting is a
24
+ * person's own act with no MCP twin (apps/mcp's parity test reads that
25
+ * suffix).
26
+ */
27
+
28
+ import { getApiBase } from "@working-theory/api-client";
29
+ import { localeHref } from "@working-theory/ui";
30
+ import { invitationDetailSchema, type InvitationDetail } from "@working-theory/validation";
31
+ import { redirect } from "next/navigation";
32
+
33
+ import { forwardedCookieInit } from "../../../../../../lib/server-api";
34
+
35
+ import { isInvitationId } from "./invitation-id";
36
+
37
+ /** Bounds the call so a hung apps/api cannot pin a render. */
38
+ const CALL_TIMEOUT_MS = 10_000;
39
+
40
+ export type InvitationRead =
41
+ | { kind: "ok"; invitation: InvitationDetail }
42
+ | { kind: "not_found" }
43
+ | { kind: "other_address" }
44
+ | { kind: "failed" };
45
+
46
+ function errorCode(body: unknown): string | null {
47
+ const code = (body as { error?: { code?: unknown } } | null)?.error?.code;
48
+ return typeof code === "string" ? code : null;
49
+ }
50
+
51
+ async function call(
52
+ method: "GET" | "POST",
53
+ path: string,
54
+ ): Promise<{ status: number; body: unknown }> {
55
+ const { headers } = await forwardedCookieInit();
56
+ const res = await fetch(`${getApiBase()}${path}`, {
57
+ method,
58
+ headers: { ...headers, ...(method === "POST" ? { "content-type": "application/json" } : {}) },
59
+ ...(method === "POST" ? { body: "{}" } : {}),
60
+ cache: "no-store",
61
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
62
+ });
63
+ const body: unknown = await res.json().catch(() => null);
64
+ return { status: res.status, body };
65
+ }
66
+
67
+ /** The invitation, for the signed-in person the API matches to it. */
68
+ export async function readInvitation(invitationId: string): Promise<InvitationRead> {
69
+ if (!isInvitationId(invitationId)) return { kind: "not_found" };
70
+ try {
71
+ const { status, body } = await call("GET", `/v1/invitations/${invitationId}`);
72
+ if (status === 404) return { kind: "not_found" };
73
+ if (status === 403 && errorCode(body) === "invitation_for_another_address") {
74
+ return { kind: "other_address" };
75
+ }
76
+ const data = (body as { ok?: unknown; data?: unknown } | null)?.data;
77
+ const parsed = invitationDetailSchema.safeParse(data);
78
+ if (status === 200 && parsed.success) return { kind: "ok", invitation: parsed.data };
79
+ console.error(`[account-invitation] read status=${status}`);
80
+ return { kind: "failed" };
81
+ } catch (err) {
82
+ console.error(
83
+ `[account-invitation] read errName=${err instanceof Error ? err.name : "unknown"}`,
84
+ );
85
+ return { kind: "failed" };
86
+ }
87
+ }
88
+
89
+ /** The refusal codes the page has a line for; anything else is `failed`. */
90
+ const KNOWN_REFUSALS = new Set([
91
+ "invitation_for_another_address",
92
+ "invitation_not_pending",
93
+ "invitation_expired",
94
+ "invitation_void",
95
+ "already_member",
96
+ ]);
97
+
98
+ /** Accept — a form POST, bound to the invitation id and locale by the page. */
99
+ export async function acceptInvitation(invitationId: string, locale: string): Promise<void> {
100
+ const page = localeHref(locale, `/account/invitations/${invitationId}`);
101
+ if (!isInvitationId(invitationId)) redirect(`${page}?error=failed`);
102
+ let outcome: string;
103
+ try {
104
+ const { status, body } = await call("POST", `/v1/invitations/${invitationId}/accept`);
105
+ const code = errorCode(body);
106
+ outcome =
107
+ status === 200 ? "joined" : code !== null && KNOWN_REFUSALS.has(code) ? code : "failed";
108
+ if (outcome === "failed") console.error(`[account-invitation] accept status=${status}`);
109
+ } catch (err) {
110
+ console.error(
111
+ `[account-invitation] accept errName=${err instanceof Error ? err.name : "unknown"}`,
112
+ );
113
+ outcome = "failed";
114
+ }
115
+ redirect(outcome === "joined" ? `${page}?joined=1` : `${page}?error=${outcome}`);
116
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The invitation id check the page and `actions.ts` run before any call
3
+ * (#11141). Not in `actions.ts`: Next.js makes every runtime export of a
4
+ * "use server" file a Server Action and fails the build on a synchronous one.
5
+ */
6
+
7
+ /** `invite_` + a uuid — the table's id format, checked before any call. */
8
+ const INVITATION_ID = /^invite_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
9
+
10
+ export function isInvitationId(value: string): boolean {
11
+ return INVITATION_ID.test(value);
12
+ }