@wix/himalaya-cli 0.1768.0 → 0.1769.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 (109) hide show
  1. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-config.d.ts +4 -0
  2. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/dev-server/src/app-module.d.ts +7 -0
  3. package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/sdui.mjs +1 -0
  4. package/dist/cli.mjs +25 -6
  5. package/guides/himi-json-output.md +3 -3
  6. package/guides/qa-builds.md +73 -84
  7. package/package.json +2 -2
  8. package/templates/beauty-salon/tier5-src/_shared/business-chat-transport.ts +20 -4
  9. package/templates/beauty-salon/tier5-src/_shared/engine-intl.ts +6 -0
  10. package/templates/beauty-salon-owner/tier5-src/_shared/engine-intl.ts +6 -0
  11. package/templates/branded-lite/config.ts +2 -1
  12. package/templates/branded-lite/dev/index.ts +2 -1
  13. package/templates/branded-lite/l10n/ar.json +120 -0
  14. package/templates/branded-lite/l10n/cs.json +120 -0
  15. package/templates/branded-lite/l10n/da.json +120 -0
  16. package/templates/branded-lite/l10n/de.json +120 -0
  17. package/templates/branded-lite/l10n/el.json +120 -0
  18. package/templates/branded-lite/l10n/es.json +120 -0
  19. package/templates/branded-lite/l10n/fi.json +120 -0
  20. package/templates/branded-lite/l10n/fr.json +120 -0
  21. package/templates/branded-lite/l10n/he.json +96 -0
  22. package/templates/branded-lite/l10n/hu.json +120 -0
  23. package/templates/branded-lite/l10n/id.json +120 -0
  24. package/templates/branded-lite/l10n/it.json +120 -0
  25. package/templates/branded-lite/l10n/ja.json +120 -0
  26. package/templates/branded-lite/l10n/ko.json +120 -0
  27. package/templates/branded-lite/l10n/lt.json +120 -0
  28. package/templates/branded-lite/l10n/nl.json +120 -0
  29. package/templates/branded-lite/l10n/no.json +120 -0
  30. package/templates/branded-lite/l10n/pl.json +120 -0
  31. package/templates/branded-lite/l10n/pt.json +120 -0
  32. package/templates/branded-lite/l10n/ru.json +120 -0
  33. package/templates/branded-lite/l10n/sv.json +120 -0
  34. package/templates/branded-lite/l10n/th.json +120 -0
  35. package/templates/branded-lite/l10n/tr.json +120 -0
  36. package/templates/branded-lite/l10n/uk.json +120 -0
  37. package/templates/branded-lite/l10n/vi.json +120 -0
  38. package/templates/branded-lite/l10n/zh.json +120 -0
  39. package/templates/branded-lite/tier5-src/_shared/business-chat-transport.ts +20 -4
  40. package/templates/branded-lite/tier5-src/_shared/engine-intl.ts +6 -0
  41. package/templates/branded-lite/tier5-src/_shared/inbox-rooms.ts +101 -11
  42. package/templates/branded-lite/tier5-src/_shared/inbox-search.ts +119 -0
  43. package/templates/branded-lite/tier5-src/_shared/member-inbox-transport.ts +64 -0
  44. package/templates/branded-lite/tier5-src/_shared/member-thread-rows.ts +233 -0
  45. package/templates/branded-lite/tier5-src/business-chat/index.ts +73 -22
  46. package/templates/branded-lite/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
  47. package/templates/branded-lite/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
  48. package/templates/branded-lite/tier5-src/wix-spaces-new-message/index.ts +4 -2
  49. package/templates/brandy/tier5-src/_shared/business-chat-message-model.ts +177 -0
  50. package/templates/brandy/tier5-src/_shared/business-chat-transport.ts +164 -0
  51. package/templates/brandy/tier5-src/_shared/engine-intl.ts +6 -0
  52. package/templates/brandy/tier5-src/_shared/inbox-rooms.ts +101 -11
  53. package/templates/brandy/tier5-src/_shared/inbox-search.ts +119 -0
  54. package/templates/brandy/tier5-src/_shared/member-inbox-transport.ts +64 -0
  55. package/templates/brandy/tier5-src/_shared/member-thread-rows.ts +233 -0
  56. package/templates/brandy/tier5-src/himi-branded-lite-inbox/index.ts +777 -54
  57. package/templates/brandy/tier5-src/wix-spaces-chat-thread/index.ts +426 -143
  58. package/templates/community-club/tier5-src/_shared/engine-intl.ts +6 -0
  59. package/templates/community-club-owner/tier5-src/_shared/engine-intl.ts +6 -0
  60. package/templates/conference/tier5-src/_shared/business-chat-transport.ts +20 -4
  61. package/templates/conference/tier5-src/_shared/chat-live.ts +242 -0
  62. package/templates/conference/tier5-src/_shared/engine-intl.ts +6 -0
  63. package/templates/conference/tier5-src/_shared/inbox-rooms.ts +101 -11
  64. package/templates/conference/tier5-src/business-chat/index.ts +73 -22
  65. package/templates/events-meetups/tier5-src/_shared/engine-intl.ts +6 -0
  66. package/templates/events-meetups-owner/tier5-src/_shared/engine-intl.ts +6 -0
  67. package/templates/fitness-gym/tier5-src/_shared/business-chat-transport.ts +20 -4
  68. package/templates/fitness-gym/tier5-src/_shared/chat-live.ts +242 -0
  69. package/templates/fitness-gym/tier5-src/_shared/engine-intl.ts +6 -0
  70. package/templates/fitness-gym/tier5-src/_shared/inbox-rooms.ts +101 -11
  71. package/templates/fitness-gym/tier5-src/business-chat/index.ts +73 -22
  72. package/templates/gym-fitness/tier5-src/_shared/business-chat-transport.ts +20 -4
  73. package/templates/gym-fitness/tier5-src/_shared/engine-intl.ts +6 -0
  74. package/templates/gym-fitness-owner/tier5-src/_shared/engine-intl.ts +6 -0
  75. package/templates/medical-services/tier5-src/_shared/business-chat-transport.ts +20 -4
  76. package/templates/medical-services/tier5-src/_shared/chat-live.ts +242 -0
  77. package/templates/medical-services/tier5-src/_shared/engine-intl.ts +6 -0
  78. package/templates/medical-services/tier5-src/_shared/inbox-rooms.ts +101 -11
  79. package/templates/medical-services/tier5-src/business-chat/index.ts +73 -22
  80. package/templates/nonprofit-cause/tier5-src/_shared/engine-intl.ts +6 -0
  81. package/templates/nonprofit-cause-owner/tier5-src/_shared/engine-intl.ts +6 -0
  82. package/templates/owner-lite/tier5-src/_shared/engine-intl.ts +6 -0
  83. package/templates/personal-fitness-trainer/dev/index.ts +2 -1
  84. package/templates/personal-fitness-trainer/tier5-src/_shared/business-chat-transport.ts +20 -4
  85. package/templates/personal-fitness-trainer/tier5-src/_shared/chat-live.ts +242 -0
  86. package/templates/personal-fitness-trainer/tier5-src/_shared/engine-intl.ts +6 -0
  87. package/templates/personal-fitness-trainer/tier5-src/_shared/inbox-rooms.ts +101 -11
  88. package/templates/personal-fitness-trainer/tier5-src/business-chat/index.ts +73 -22
  89. package/templates/podcast-creator/tier5-src/_shared/engine-intl.ts +6 -0
  90. package/templates/podcast-creator-owner/tier5-src/_shared/engine-intl.ts +6 -0
  91. package/templates/portfolio-creative/tier5-src/_shared/engine-intl.ts +6 -0
  92. package/templates/portfolio-creative-owner/tier5-src/_shared/engine-intl.ts +6 -0
  93. package/templates/restaurant/tier5-src/_shared/engine-intl.ts +6 -0
  94. package/templates/restaurant-owner/tier5-src/_shared/engine-intl.ts +6 -0
  95. package/templates/retail-store/tier5-src/_shared/engine-intl.ts +6 -0
  96. package/templates/retail-store-owner/tier5-src/_shared/engine-intl.ts +6 -0
  97. package/templates/salon-spa/tier5-src/_shared/business-chat-transport.ts +20 -4
  98. package/templates/salon-spa/tier5-src/_shared/chat-live.ts +242 -0
  99. package/templates/salon-spa/tier5-src/_shared/engine-intl.ts +6 -0
  100. package/templates/salon-spa/tier5-src/_shared/inbox-rooms.ts +101 -11
  101. package/templates/salon-spa/tier5-src/business-chat/index.ts +73 -22
  102. package/templates/wholesale-store/tier5-src/_shared/business-chat-transport.ts +20 -4
  103. package/templates/wholesale-store/tier5-src/_shared/chat-live.ts +242 -0
  104. package/templates/wholesale-store/tier5-src/_shared/engine-intl.ts +6 -0
  105. package/templates/wholesale-store/tier5-src/_shared/inbox-rooms.ts +101 -11
  106. package/templates/wholesale-store/tier5-src/business-chat/index.ts +73 -22
  107. package/templates/yoga-studio/tier5-src/_shared/business-chat-transport.ts +20 -4
  108. package/templates/yoga-studio/tier5-src/_shared/engine-intl.ts +6 -0
  109. package/templates/yoga-studio-owner/tier5-src/_shared/engine-intl.ts +6 -0
@@ -9,16 +9,27 @@
9
9
  // `chatRealtime` channel, else a 4 s foreground `_poll` of `refresh`. A message from the
10
10
  // business then appears without the member leaving the screen. `load`, `setDraft` and
11
11
  // `send` keep their contract; the directives are stripped by the runtime, never state.
12
- import { defineService, type PollDirective, type PollStopDirective, type StreamDirective } from "@himalaya/state";
12
+ //
13
+ // TWO SCREENS SHARE THIS WORKER. The Spaces app binds the original fields and behaves as it always did. Branded Lite's
14
+ // thread screen adds what it needs on top, and every addition is one of:
15
+ // • an ADDITIVE field or action (header, per-row avatar and status flags, send enabled, error classes, room menu);
16
+ // • behaviour behind the opt-in `richThread` load param, which only that screen passes: rich message rows (images,
17
+ // files, a card, the unsupported fallback, private media through its authorized URL), the peer header refreshed from
18
+ // the messages, and sends that stay on screen as "Sending…" / "Couldn't send" rows with a Retry under the SAME
19
+ // message id. Without `richThread` a send keeps its original shape (the composer keeps the text on failure, `sendHint`).
20
+ // The contract is written out in the design hand-off (thread-worker-contract.md).
21
+ import { classifyLoadError, defineService, type PollDirective, type PollStopDirective, type StreamDirective } from "@himalaya/state";
13
22
  import { getMessages, sendChatMessage, getOrCreateDirectChatroom, getChatToken, type ChatMessage } from "@himalaya/wix-chat-web";
14
23
  import { getMyData } from "@himalaya/wix-users";
15
- import { formatMonthDay, formatMonthDayTime } from "../_shared/engine-intl.js";
16
24
  import { initials } from "../_shared/himi-text.js";
17
25
  import { copyParam, stashCopy } from "../_shared/himi-copy.js";
18
26
  import { presence, presenceAfterError, detailInputId, type PresenceFlags } from "../_shared/detail-presence.js";
19
27
  import { isOfflineFailure, writeMayHaveLanded } from "../_shared/owner-load-error.js";
20
28
  import { logChatSendError } from "../_shared/wix-bi.js";
21
- import { CHAT_LIVE_POLL_ID, chatRealtimeConfig, createReloadGate, createSendIntents, createVisitToken, liveDirectives, postWithVisitToken, isTokenRejected, liveFallback, type ChatLiveMode, type ChatRealtimeConfig } from "../_shared/chat-live.js";
29
+ import { CHAT_LIVE_POLL_ID, chatRealtimeConfig, createReloadGate, createSendIntents, createVisitToken, liveDirectives, postWithVisitToken, isTokenRejected, liveFallback, uuidV4, type ChatLiveMode, type ChatRealtimeConfig } from "../_shared/chat-live.js";
30
+ import { attachmentUrl, chatIdentity } from "../_shared/business-chat-transport.js";
31
+ import { deleteRoom, markRoomUnread, setRoomArchived } from "../_shared/member-inbox-transport.js";
32
+ import { localSentRow, privateMediaOf, rowsOf, type OutboxEntry, type Row } from "../_shared/member-thread-rows.js";
22
33
 
23
34
  import { memberAccess, memberAccessChanged } from "../_shared/member-access.js";
24
35
  import { readAccess, assertReadAccess, readAccessDenied, NO_READ_SIGN_IN, type ReadAccess } from "../_shared/member-read.js";
@@ -26,14 +37,9 @@ import { readAccess, assertReadAccess, readAccessDenied, NO_READ_SIGN_IN, type R
26
37
  const SERVICE = "spacesChatThread";
27
38
  const EMPTY_TEXT = "No messages yet. Say hello!";
28
39
 
29
- // `mine` / `notMine` pick the incoming or outgoing row layout (the descriptor hides the other
30
- // one). Empty strings and `*Hidden` flags let a row drop its badge, avatar or attachment.
31
- // `leadFill` (" " for my messages) stays for screens that right-align with a gated spacer.
32
- interface Row {
33
- id: string; text: string; when: string; leadFill: string; mine: boolean; notMine: boolean;
34
- senderBadge: string; avatarUrl: string; avatarInitials: string;
35
- imageUrl: string; imageDescription: string; imageHidden: boolean; dayLabel: string; dayHidden: boolean;
36
- }
40
+ type FailureKind = "offline" | "server" | "permission" | "signIn";
41
+ type ClosedReason = "" | "archived" | "deleted" | "markedUnread";
42
+
37
43
  interface S extends PresenceFlags {
38
44
  threadMember: ReadAccess | null; signInRequired: boolean; noSignIn: boolean;
39
45
  status: "loading" | "ready"; messages: Row[]; emptyText: string; emptyHidden: boolean; draft: string; sendHint: string; resolvedChatroomId: string; myUserId: string;
@@ -43,6 +49,21 @@ interface S extends PresenceFlags {
43
49
  live?: ChatLiveMode;
44
50
  _stream?: StreamDirective;
45
51
  _poll?: PollDirective | PollStopDirective;
52
+
53
+ /** Header: who the conversation is with. From the open params (`peerName`, `peerPhoto`) at once, refreshed from the
54
+ * messages of a private conversation when `richThread` is on. `peerInitial` is the avatar fallback. */
55
+ peerName: string; peerPhoto: string; peerInitial: string; hidePeerName: boolean; hidePeerPhoto: boolean;
56
+ /** The composer's Send is on only with a loaded conversation and text other than whitespace. */
57
+ sendEnabled: boolean; sendDisabled: boolean;
58
+ /** Why the conversation could not be shown ("" if it could, or if it is simply not there). One flag per class, true = hide. */
59
+ errorKind: "" | FailureKind; errorText: string;
60
+ hideOfflineError: boolean; hideServerError: boolean; hidePermissionError: boolean; hideSignInError: boolean;
61
+ /** The room menu. `isPrivate`: a 1:1 conversation between members (the only kind a member can delete). */
62
+ isPrivate: boolean; isArchived: boolean; hideArchive: boolean; hideUnarchive: boolean; hideDelete: boolean;
63
+ /** The last menu action Wix refused, as a customer sentence ("" none). */
64
+ roomActionError: string; hideRoomActionError: boolean;
65
+ /** The member left the conversation through the menu (archived, deleted or marked unread): the screen goes back. */
66
+ closed: boolean; closedReason: ClosedReason;
46
67
  }
47
68
 
48
69
  function inputId(): string {
@@ -52,6 +73,22 @@ function inputKind(): string {
52
73
  // The native nav plumbs an optional `kind` flat onto himalaya.input (screen|id|kind).
53
74
  return (globalThis as { himalaya?: { input?: { kind?: string } } }).himalaya?.input?.kind ?? "";
54
75
  }
76
+ function inputText(key: string): string {
77
+ const value = (globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input?.[key];
78
+ return typeof value === "string" ? value.trim() : "";
79
+ }
80
+ const FLAG = new Set(["1", "true"]);
81
+ const isFlag = (value: unknown): boolean => value === true || (typeof value === "string" && FLAG.has(value));
82
+ /** What the open params already say about the conversation. A thread opened with a MEMBER id is the 1:1 private room
83
+ * with that member; one opened with a chatroom id is private only when the inbox row says so (`isPrivate`). */
84
+ function openedRoom(): Pick<S, "peerName" | "peerPhoto" | "isPrivate" | "isArchived"> {
85
+ const photo = inputText("peerPhoto");
86
+ const input = (globalThis as { himalaya?: { input?: Record<string, unknown> } }).himalaya?.input;
87
+ return {
88
+ peerName: inputText("peerName"), peerPhoto: /^https:\/\//i.test(photo) ? photo : "",
89
+ isPrivate: (!!inputId() && inputKind() !== "chatroom") || isFlag(input?.isPrivate), isArchived: isFlag(input?.isArchived),
90
+ };
91
+ }
55
92
  // Resolve the raw input id (member OR chatroom) to a real CHATROOM id.
56
93
  // kind==="chatroom" → the inbox already passed a resolved chatroom id; use it as-is.
57
94
  // otherwise (member picker / member detail) → the raw id is a MEMBER id; get-or-create
@@ -69,68 +106,149 @@ async function resolveChatroomId(raw: string, kind: string): Promise<string> {
69
106
  function val(arg?: unknown): string {
70
107
  return typeof arg === "string" ? arg : ((arg as { value?: string; text?: string })?.value ?? (arg as { text?: string })?.text ?? "");
71
108
  }
72
- function dayKeyOf(d: Date): string {
73
- return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
109
+ /** The room or message id an action names: a bare string, `{ id }`, or `{ params: { id } }`. */
110
+ function idOf(arg: unknown): string {
111
+ if (typeof arg === "string") return arg.trim();
112
+ const direct = (arg as { id?: unknown } | null)?.id ?? (arg as { params?: { id?: unknown } } | null)?.params?.id;
113
+ return typeof direct === "string" ? direct.trim() : "";
74
114
  }
75
- /** chat-web marks the business side as "business", "businessUser" or "user" (the same predicate
76
- * as wix-owner-inbox-thread); a visitor or member is anything else. */
77
- function isBusinessSender(m: ChatMessage): boolean {
78
- const type = String(m.sender?.type ?? "").toLowerCase();
79
- return type === "business" || type === "businessuser" || type === "user";
115
+
116
+ function nextScrollToken(prev: string): string {
117
+ return String((Number(prev) || 0) + 1);
80
118
  }
81
- function norm(m: ChatMessage, i: number, myUserId: string): Row & { timestamp: number; dayKey: string } {
82
- const mm = m as unknown as {
83
- id?: string; summary?: string; data?: Array<{ mimeType?: string; data?: { text?: string; uri?: string; thumbnailUrl?: string } }>;
84
- payload?: { text?: string }; content?: string; createdAt?: number; createdDate?: string;
85
- senderDisplayData?: { name?: string; image?: { url?: string } };
86
- };
87
- const text = mm.data?.find((part) => part.data?.text)?.data?.text || mm.summary || mm.payload?.text || mm.content || "";
88
- const ms = mm.createdAt || (mm.createdDate ? Date.parse(mm.createdDate) : 0);
89
- const date = ms ? new Date(ms) : null;
90
- const senderName = mm.senderDisplayData?.name || "";
91
- const avatarUrl = mm.senderDisplayData?.image?.url || "";
92
- const image = mm.data?.find((part) => part.mimeType?.startsWith("image/") || part.data?.thumbnailUrl);
93
- const imageUrl = image?.data?.thumbnailUrl || image?.data?.uri || "";
94
- // Mine when the message sender matches my user id (resolved once per load).
95
- const mine = !!(myUserId && m.sender?.userId && m.sender.userId === myUserId);
119
+
120
+ // ---------------------------------------------------------------------------------------------------------------------
121
+ // Copy. Every sentence the worker emits for the richer screen goes through a copy key with its English fallback.
122
+ // ---------------------------------------------------------------------------------------------------------------------
123
+ const loadText = (kind: FailureKind): string =>
124
+ kind === "offline" ? copyParam("chatThread.offlineText", "You're offline. Reconnect and try again.")
125
+ : kind === "permission" ? copyParam("chatThread.permissionText", "You don't have access to this conversation.")
126
+ : kind === "signIn" ? copyParam("chatThread.signInText", "Sign in to see this conversation.")
127
+ : copyParam("chatThread.serverText", "This conversation couldn't be loaded. Please try again.");
128
+ const actionText = (kind: FailureKind): string =>
129
+ kind === "permission" ? copyParam("chatThread.actionPermissionText", "You don't have permission to change this conversation.")
130
+ : kind === "server" ? copyParam("chatThread.actionFailedText", "Couldn't update this conversation. Please try again.")
131
+ : loadText(kind);
132
+
133
+ // ---------------------------------------------------------------------------------------------------------------------
134
+ // State. Every action's result goes through shape(), which derives every flag from the base fields.
135
+ // ---------------------------------------------------------------------------------------------------------------------
136
+ function shape(s: S): S {
137
+ const kind = s.errorKind;
96
138
  return {
97
- id: mm.id || `m${i}`, text: text || "Message", when: date ? formatMonthDayTime(date) : "", leadFill: mine ? " " : "", mine, notMine: !mine,
98
- senderBadge: isBusinessSender(m) ? copyParam("chatThread.businessBadge", "Business") : "",
99
- avatarUrl, avatarInitials: initials(senderName),
100
- imageUrl, imageDescription: imageUrl ? `${senderName || "Message"} attachment` : "", imageHidden: !imageUrl,
101
- dayLabel: "", dayHidden: true, timestamp: ms, dayKey: date ? dayKeyOf(date) : "",
139
+ ...s,
140
+ peerInitial: s.peerName ? initials(s.peerName) : "", hidePeerName: !s.peerName, hidePeerPhoto: !s.peerPhoto,
141
+ sendEnabled: s.found && !s.closed && s.draft.trim() !== "", sendDisabled: !(s.found && !s.closed && s.draft.trim() !== ""),
142
+ errorText: kind ? loadText(kind) : "",
143
+ hideOfflineError: kind !== "offline", hideServerError: kind !== "server", hidePermissionError: kind !== "permission", hideSignInError: kind !== "signIn",
144
+ hideArchive: !s.found || s.isArchived, hideUnarchive: !s.found || !s.isArchived, hideDelete: !s.found || !s.isPrivate,
145
+ hideRoomActionError: s.roomActionError === "",
102
146
  };
103
147
  }
104
148
 
105
- /** Oldest first, one row per message id, and a day label on the first message of each day. */
106
- function rowsOf(messages: ChatMessage[], myUserId: string): Row[] {
107
- const sorted = messages.map((m, i) => norm(m, i, myUserId)).sort((a, b) => a.timestamp - b.timestamp);
108
- const today = new Date();
109
- const todayKey = dayKeyOf(today);
110
- const yesterdayKey = dayKeyOf(new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1));
111
- const seen = new Set<string>();
112
- const rows: Row[] = [];
113
- let previousDay = "";
114
- for (const { timestamp, dayKey, ...row } of sorted) {
115
- if (seen.has(row.id)) continue;
116
- seen.add(row.id);
117
- const startsDay = !!dayKey && dayKey !== previousDay;
118
- if (dayKey) previousDay = dayKey;
119
- const dayLabel = !startsDay ? "" : dayKey === todayKey ? copyParam("chatThread.today", "Today") : dayKey === yesterdayKey ? copyParam("chatThread.yesterday", "Yesterday") : formatMonthDay(new Date(timestamp));
120
- rows.push({ ...row, dayLabel, dayHidden: !dayLabel });
121
- }
149
+ const INITIAL: S = shape({
150
+ status: "loading", messages: [], emptyText: "", emptyHidden: true, scrollSend: "", draft: "", sendHint: "", resolvedChatroomId: "", myUserId: "",
151
+ ...presence("loading"), ...NO_READ_SIGN_IN, threadMember: null,
152
+ peerName: "", peerPhoto: "", peerInitial: "", hidePeerName: true, hidePeerPhoto: true,
153
+ sendEnabled: false, sendDisabled: true,
154
+ errorKind: "", errorText: "", hideOfflineError: true, hideServerError: true, hidePermissionError: true, hideSignInError: true,
155
+ isPrivate: false, isArchived: false, hideArchive: true, hideUnarchive: true, hideDelete: true,
156
+ roomActionError: "", hideRoomActionError: true,
157
+ closed: false, closedReason: "",
158
+ });
159
+ /** A fresh screen state: nothing carried over, the header from what the open params already say. */
160
+ const fresh = (): S => shape({ ...INITIAL, ...openedRoom() });
161
+
162
+ // ---------------------------------------------------------------------------------------------------------------------
163
+ // Visit bookkeeping (not screen state). `visitEpoch` bumps whenever the member or the conversation changes or goes away,
164
+ // so a request started for the previous one never lands on the next.
165
+ // ---------------------------------------------------------------------------------------------------------------------
166
+ /** The screen opted in to the richer thread (`richThread` load param). */
167
+ let rich = false;
168
+ /** Sends of this visit the server may not list yet, and who/what room they belong to. */
169
+ let outbox: OutboxEntry[] = [];
170
+ let outboxOwner = "";
171
+ let visitEpoch = 0;
172
+ /** The last server read of the open room, so a local change re-renders the rows without another request. */
173
+ let lastRaw: { roomId: string; messages: ChatMessage[] } = { roomId: "", messages: [] };
174
+ /** Authorized download URLs of private attachments, by media id; they live a few minutes. */
175
+ const mediaUrls = new Map<string, { url: string; at: number }>();
176
+ const MEDIA_URL_TTL_MS = 4 * 60 * 1000;
177
+ /** When an attachment's authorized URL last failed: a live re-read does not ask again for a minute. */
178
+ const mediaFailedAt = new Map<string, number>();
179
+ const MEDIA_RETRY_MS = 60 * 1000;
180
+ let roomActionBusy = false;
181
+
182
+ function resetVisit(): void {
183
+ current = { chatroomId: "", myUserId: "" };
184
+ memberToken.reset();
185
+ outbox = []; outboxOwner = "";
186
+ lastRaw = { roomId: "", messages: [] };
187
+ mediaUrls.clear();
188
+ mediaFailedAt.clear();
189
+ roomActionBusy = false;
190
+ visitEpoch++;
191
+ }
192
+ /** The same member, scope and site, whichever `ReadAccess` object describes them: every `load` publishes a new object. */
193
+ const sameReader = (a: ReadAccess | null, b: ReadAccess | null): boolean =>
194
+ !!a && !!b && a.member.email === b.member.email && a.member.scope === b.member.scope && a.tenant === b.tenant;
195
+ const ownerKeyOf = (member: ReadAccess, roomId: string): string => `${member.member.email}|${member.member.scope}|${member.tenant}|${roomId}`;
196
+
197
+ function renderRows(roomId: string, myUserId: string): Row[] {
198
+ const messages = lastRaw.roomId === roomId ? lastRaw.messages : [];
199
+ if (!rich) return rowsOf(messages, myUserId);
200
+ const urls = new Map<string, string>();
201
+ for (const [mediaId, hit] of mediaUrls) urls.set(mediaId, hit.url);
202
+ const rows = rowsOf(messages, myUserId, { rich: true, outbox: outbox.filter((entry) => entry.roomId === roomId), mediaUrls: urls });
203
+ // A send the server now lists is the server's row: forget the local entry (its status then reads from the server's message).
204
+ const listed = new Set(rows.filter((row) => row.sendState === "").map((row) => row.id));
205
+ outbox = outbox.filter((entry) => !listed.has(entry.id));
122
206
  return rows;
123
207
  }
124
208
 
125
- function nextScrollToken(prev: string): string {
126
- return String((Number(prev) || 0) + 1);
209
+ /** Authorized URLs for the private attachments of these messages, fetched once per few minutes. A failure leaves the
210
+ * attachment without a URL (it is not shown) and is not asked again for a minute, so a live re-read is not held up by
211
+ * it; the raw private link is never used. Only a member change propagates. */
212
+ async function prefetchMedia(messages: ChatMessage[], member: ReadAccess): Promise<void> {
213
+ const wanted = privateMediaOf(messages).filter((part) => {
214
+ const hit = mediaUrls.get(part.mediaId!);
215
+ const failed = mediaFailedAt.get(part.mediaId!);
216
+ if (failed !== undefined && Date.now() - failed < MEDIA_RETRY_MS) return false;
217
+ return !hit || Date.now() - hit.at >= MEDIA_URL_TTL_MS;
218
+ });
219
+ if (!wanted.length) return;
220
+ const identity = await chatIdentity();
221
+ if (!identity.authenticated || identity.email !== member.member.email || identity.scope !== member.member.scope) throw memberAccessChanged();
222
+ await Promise.all(wanted.map(async (part) => {
223
+ try {
224
+ const url = await attachmentUrl(identity, part);
225
+ if (url) { mediaUrls.set(part.mediaId!, { url, at: Date.now() }); mediaFailedAt.delete(part.mediaId!); }
226
+ } catch (error) {
227
+ if ((error as { name?: string } | null)?.name === "MemberAccessChanged") throw error;
228
+ mediaFailedAt.set(part.mediaId!, Date.now());
229
+ }
230
+ }));
231
+ }
232
+
233
+ /** The peer of a private conversation, from the newest message that is not mine. Only with `richThread`, and only when I
234
+ * know which messages are mine. Nothing found keeps what the open params said. */
235
+ function peerOf(s: S, roomId: string): Pick<S, "peerName" | "peerPhoto"> {
236
+ if (!rich || !s.isPrivate || !s.myUserId || lastRaw.roomId !== roomId) return { peerName: s.peerName, peerPhoto: s.peerPhoto };
237
+ for (let i = lastRaw.messages.length - 1; i >= 0; i--) {
238
+ const message = lastRaw.messages[i]!;
239
+ if (!message.sender?.userId || message.sender.userId === s.myUserId) continue;
240
+ const name = message.senderDisplayData?.name?.trim() ?? "";
241
+ const photo = message.senderDisplayData?.image?.url ?? "";
242
+ if (name || photo) return { peerName: name || s.peerName, peerPhoto: /^https:\/\//i.test(photo) ? photo : s.peerPhoto };
243
+ }
244
+ return { peerName: s.peerName, peerPhoto: s.peerPhoto };
127
245
  }
128
246
 
129
247
  // ONE member chatToken per visit (`_shared/chat-live.ts`): a 4 s re-read would otherwise
130
248
  // mint a token every 4 s on top of its GET. Reset on every `load`.
131
249
  const memberToken = createVisitToken(() => getChatToken({ role: "member" }).then((t) => t.chatToken));
132
250
 
133
- async function reload(id: string, myUserId: string, member: ReadAccess): Promise<Row[]> {
251
+ async function reload(id: string, myUserId: string, member: ReadAccess, fresh: () => boolean = () => true): Promise<Row[]> {
134
252
  if (!id) return [];
135
253
  for (let attempt = 0; ; attempt++) {
136
254
  const token = memberToken.get();
@@ -138,7 +256,10 @@ async function reload(id: string, myUserId: string, member: ReadAccess): Promise
138
256
  const chatToken = await token;
139
257
  await assertReadAccess(member);
140
258
  const msgs = await getMessages(id, 30, { role: "member", chatToken });
141
- return rowsOf(msgs ?? [], myUserId);
259
+ // A read that a newer load already superseded must not replace what the room on screen is rendered from.
260
+ if (fresh()) lastRaw = { roomId: id, messages: msgs ?? [] };
261
+ if (rich) await prefetchMedia(msgs ?? [], member);
262
+ return renderRows(id, myUserId);
142
263
  } catch (error) {
143
264
  memberToken.drop(token);
144
265
  // An expired visit token gets one fresh attempt. A repeated refusal still
@@ -151,15 +272,18 @@ async function reload(id: string, myUserId: string, member: ReadAccess): Promise
151
272
  /** Send ids that belong to the intent (conversation + text), not the tap. */
152
273
  const intents = createSendIntents();
153
274
 
154
- /** Post once per intent: a retried tap of the same text reuses its message id, so a send
155
- * that failed ambiguously and is tapped again stays one message. */
156
- async function postOnce(chatroomId: string, text: string, member: ReadAccess): Promise<void> {
157
- const messageId = intents.idFor(chatroomId, text);
275
+ /** One request: the message goes to the room under `messageId`, so a repeat of the same id is the same message to chat-web. */
276
+ async function postMessage(chatroomId: string, text: string, member: ReadAccess, messageId: string, unchanged: (now: ReadAccess | null) => boolean = (now) => now === member): Promise<void> {
158
277
  await postWithVisitToken(memberToken, async (chatToken) => {
159
278
  await assertReadAccess(member);
160
- if (liveState().threadMember !== member) throw memberAccessChanged();
279
+ if (!unchanged(liveState().threadMember)) throw memberAccessChanged();
161
280
  return sendChatMessage(chatroomId, text, { role: "member", chatToken, messageId });
162
281
  });
282
+ }
283
+ /** Post once per intent: a retried tap of the same text reuses its message id, so a send
284
+ * that failed ambiguously and is tapped again stays one message. */
285
+ async function postOnce(chatroomId: string, text: string, member: ReadAccess): Promise<void> {
286
+ await postMessage(chatroomId, text, member, intents.idFor(chatroomId, text));
163
287
  intents.settle(chatroomId, text);
164
288
  }
165
289
 
@@ -170,7 +294,12 @@ let sendingNow = false;
170
294
  // The conversation a live re-read reads, and the channel the screen passed (if any).
171
295
  let current = { chatroomId: "", myUserId: "" };
172
296
  let realtime: ChatRealtimeConfig | null = null;
173
- const gate = createReloadGate(() => reload(current.chatroomId, current.myUserId, liveState().threadMember!));
297
+ // A tick still reading when the member opens another room (or another member signs in) is superseded too.
298
+ const gate = createReloadGate(() => {
299
+ const { chatroomId, myUserId } = current;
300
+ const epoch = visitEpoch;
301
+ return reload(chatroomId, myUserId, liveState().threadMember!, () => epoch === visitEpoch && chatroomId === current.chatroomId);
302
+ });
174
303
 
175
304
  /** A tick or a stream event: re-read the open conversation. A failed tick keeps the
176
305
  * thread as it is — the next one tries again.
@@ -183,11 +312,13 @@ async function reread(s: S): Promise<S> {
183
312
  if (!s.found || !s.resolvedChatroomId || s.resolvedChatroomId !== current.chatroomId) return s;
184
313
  try {
185
314
  await assertThreadMember(s);
186
- const messages = await gate.request();
315
+ const read = await gate.request();
187
316
  await assertThreadMember(s);
188
317
  const now = svc.getState();
189
318
  if (now.threadMember !== s.threadMember || now.resolvedChatroomId !== s.resolvedChatroomId) return now;
190
- return { ...now, messages, emptyText: messages.length ? "" : now.emptyText || EMPTY_TEXT, emptyHidden: messages.length > 0 };
319
+ // richThread rows carry the local sends: render them now, so a send or settle made during the last await is kept.
320
+ const messages = rich ? renderRows(now.resolvedChatroomId, now.myUserId) : read;
321
+ return { ...now, ...peerOf(now, now.resolvedChatroomId), messages, emptyText: messages.length ? "" : now.emptyText || EMPTY_TEXT, emptyHidden: messages.length > 0 };
191
322
  } catch (error) {
192
323
  const now = svc.getState();
193
324
  if (now.threadMember !== s.threadMember) return now;
@@ -206,35 +337,214 @@ async function resolveMyUserId(): Promise<string> {
206
337
  try { return (await getMyData()).userId || ""; } catch { return ""; }
207
338
  }
208
339
 
209
- const INITIAL: S = { status: "loading", messages: [], emptyText: "", emptyHidden: true, scrollSend: "", draft: "", sendHint: "", resolvedChatroomId: "", myUserId: "", ...presence("loading"), ...NO_READ_SIGN_IN, threadMember: null };
210
340
  let loadVersion = 0;
211
341
 
342
+ const isSwitch = (error: unknown): boolean => (error as { name?: string } | null)?.name === "MemberAccessChanged";
343
+ /** Why a request failed, as a class the screen can phrase: never the raw message. */
344
+ async function kindOf(error: unknown): Promise<FailureKind> {
345
+ if (isSwitch(error)) return "signIn";
346
+ if (!(await memberAccess()).email) return "signIn";
347
+ // A chat-web helper wraps the transport's failure: the cause is what says offline or refused.
348
+ const cause = (error as { cause?: unknown } | null)?.cause ?? error;
349
+ const kind = classifyLoadError(cause, "signedIn");
350
+ return kind === "membership" ? "permission" : kind;
351
+ }
352
+
212
353
  async function threadFailure(error: unknown): Promise<S> {
213
354
  const version = loadVersion;
214
355
  const member = await memberAccess();
215
356
  const flags = member.email ? NO_READ_SIGN_IN : { signInRequired: true, noSignIn: false };
357
+ const flagsOfError = presenceAfterError(error);
358
+ const kind = flagsOfError.notFound ? "" : member.email ? await kindOf(error) : "signIn";
216
359
  if (version !== loadVersion) return liveState();
217
- current = { chatroomId: "", myUserId: "" };
218
- memberToken.reset();
219
- return { ...INITIAL, status: "ready", ...presenceAfterError(error), ...flags, live: "off", _poll: { id: CHAT_LIVE_POLL_ID, stop: true } };
360
+ // A passing failure (offline, a server error) keeps this visit's own sends, so a "Couldn't send" row and its Retry are
361
+ // still there when the same member's room loads again. A send still in flight cannot report back after the reset, so
362
+ // it becomes a failed one: Retry resends it under the same id, which can never post twice.
363
+ const keep = kind === "offline" || kind === "server" ? { outbox: outbox.map((entry) => (entry.state === "sending" ? { ...entry, state: "failed" as const } : entry)), outboxOwner } : null;
364
+ resetVisit();
365
+ if (keep) { outbox = keep.outbox; outboxOwner = keep.outboxOwner; }
366
+ return shape({ ...fresh(), status: "ready", ...flagsOfError, ...flags, errorKind: kind, live: "off", _poll: { id: CHAT_LIVE_POLL_ID, stop: true } });
220
367
  }
221
368
  async function assertThreadMember(s: S): Promise<void> {
222
369
  if (!s.threadMember?.member?.email) throw new Error("Unauthenticated: sign in to read messages");
223
370
  await assertReadAccess(s.threadMember);
224
371
  }
225
372
 
226
- const svc = defineService<S, {
373
+ // ---------------------------------------------------------------------------------------------------------------------
374
+ // Sending, richThread: the message is a row at once ("Sending…"), its request reports back through `settleSend`, and a
375
+ // failed one stays as a "Couldn't send" row whose Retry resends it under the SAME message id.
376
+ // ---------------------------------------------------------------------------------------------------------------------
377
+ interface SendSettle { id: string; epoch: number; member: ReadAccess; outcome: "ok" | FailureKind }
378
+
379
+ /** The request. Never throws: it reports how it ended. */
380
+ async function deliver(entry: OutboxEntry, member: ReadAccess, epoch: number): Promise<void> {
381
+ let outcome: SendSettle["outcome"] = "ok";
382
+ try {
383
+ // Let the reducer that started this publish its "Sending…" row first.
384
+ await Promise.resolve();
385
+ await postMessage(entry.roomId, entry.text, member, entry.id, (now) => sameReader(now, member) || now === null);
386
+ } catch (error) {
387
+ outcome = await kindOf(error);
388
+ // An ambiguous failure (a gateway timeout after the backend stored the message) is shown as failed too: the Retry
389
+ // carries the same message id, so it can never become a second message.
390
+ if (!isSwitch(error) && !writeMayHaveLanded(error)) logChatSendError({ chatroomId: entry.roomId, error, offline: isOfflineFailure(error) });
391
+ }
392
+ if (epoch === visitEpoch) void svc.settleSend({ id: entry.id, epoch, member, outcome });
393
+ }
394
+ const setOutbox = (id: string, state: OutboxEntry["state"]): void => { outbox = outbox.map((entry) => (entry.id === id ? { ...entry, state } : entry)); };
395
+
396
+ function richSend(s: S): S {
397
+ if (!s.found || !s.threadMember) return s;
398
+ const text = s.draft.trim();
399
+ if (!text) return { ...s, sendHint: copyParam("chatThread.typeFirstHint", "Type a message first.") };
400
+ const roomId = s.resolvedChatroomId;
401
+ // A message goes only to the room on screen, for the member on screen.
402
+ if (!roomId || roomId !== current.chatroomId) return s;
403
+ const entry: OutboxEntry = { id: uuidV4(), roomId, text, at: Date.now(), state: "sending" };
404
+ outbox = [...outbox, entry];
405
+ void deliver(entry, s.threadMember, visitEpoch);
406
+ return { ...s, messages: renderRows(roomId, s.myUserId), draft: "", sendHint: "", emptyText: "", emptyHidden: true, scrollSend: nextScrollToken(s.scrollSend) };
407
+ }
408
+
409
+ // ---------------------------------------------------------------------------------------------------------------------
410
+ // The room menu: archive, unarchive, markUnread, delete — for the conversation on screen, as the member on screen.
411
+ // ---------------------------------------------------------------------------------------------------------------------
412
+ type RoomVerb = "archive" | "unarchive" | "markUnread" | "delete";
413
+ const roomCall = (verb: RoomVerb, identity: Awaited<ReturnType<typeof chatIdentity>>, roomId: string): Promise<void> =>
414
+ verb === "markUnread" ? markRoomUnread(identity, roomId) : verb === "delete" ? deleteRoom(identity, roomId) : setRoomArchived(identity, roomId, verb === "archive");
415
+
416
+ async function roomAction(s: S, arg: unknown, verb: RoomVerb): Promise<S> {
417
+ const member = s.threadMember;
418
+ const roomId = s.resolvedChatroomId;
419
+ if (!s.found || !member || !roomId || roomId !== current.chatroomId || s.closed) return s;
420
+ // The action is for the room on screen. Another room's id is refused before anything leaves.
421
+ const asked = idOf(arg);
422
+ if (asked && asked !== roomId) return s;
423
+ if (verb === "delete" && !s.isPrivate) return { ...s, roomActionError: copyParam("chatThread.deleteRefusedText", "Only private conversations can be deleted.") };
424
+ if ((verb === "archive" && s.isArchived) || (verb === "unarchive" && !s.isArchived) || roomActionBusy) return s;
425
+ roomActionBusy = true;
426
+ const epoch = visitEpoch;
427
+ try {
428
+ const identity = await chatIdentity();
429
+ if (!identity.authenticated || identity.email !== member.member.email || identity.scope !== member.member.scope) throw memberAccessChanged();
430
+ await assertThreadMember(s);
431
+ await roomCall(verb, identity, roomId);
432
+ const now = liveState();
433
+ if (epoch !== visitEpoch || !(now.threadMember === null || sameReader(now.threadMember, member)) || (now.found && now.resolvedChatroomId !== roomId)) return now;
434
+ const left = verb === "unarchive" ? { isArchived: false } : verb === "archive" ? { isArchived: true } : {};
435
+ const reason: ClosedReason = verb === "archive" ? "archived" : verb === "delete" ? "deleted" : verb === "markUnread" ? "markedUnread" : "";
436
+ // Leaving the room: its live re-read stops, so a deleted or archived room is not polled.
437
+ return reason
438
+ ? { ...now, ...left, roomActionError: "", closed: true, closedReason: reason, live: "off", _poll: { id: CHAT_LIVE_POLL_ID, stop: true } }
439
+ : { ...now, ...left, roomActionError: "" };
440
+ } catch (error) {
441
+ const now = liveState();
442
+ if (epoch !== visitEpoch || !(now.threadMember === null || sameReader(now.threadMember, member))) return now;
443
+ const kind = await kindOf(error);
444
+ if (kind === "signIn") return threadFailure(error);
445
+ return { ...liveState(), roomActionError: actionText(kind) };
446
+ } finally {
447
+ roomActionBusy = false;
448
+ }
449
+ }
450
+
451
+ /** Every result goes through `shape()`, sync or async, so no return path can leave a derived flag stale. */
452
+ function shaped<A extends Record<string, (s: S, ...args: never[]) => S | undefined | Promise<S | undefined>>>(actions: A): A {
453
+ const out: Record<string, unknown> = {};
454
+ for (const [name, action] of Object.entries(actions)) {
455
+ out[name] = (s: S, ...args: never[]) => {
456
+ const result = action(s, ...args);
457
+ return result && typeof (result as Promise<S | undefined>).then === "function"
458
+ ? (result as Promise<S | undefined>).then((value) => (value ? shape(value) : value))
459
+ : result ? shape(result as S) : result;
460
+ };
461
+ }
462
+ return out as A;
463
+ }
464
+
465
+ /** The original send, as the Spaces thread has always done it. */
466
+ async function legacySend(s: S): Promise<S> {
467
+ if (!s.found) return s;
468
+ const text = s.draft.trim();
469
+ try { await assertThreadMember(s); }
470
+ catch (error) { return liveState().threadMember !== s.threadMember ? liveState() : threadFailure(error); }
471
+ if (liveState().threadMember !== s.threadMember) return liveState();
472
+ const checked = liveState();
473
+ if (!text) return checked.draft.trim() ? checked : { ...checked, sendHint: "Type a message first." };
474
+ if (sendingNow) return checked;
475
+ sendingNow = true;
476
+ try {
477
+ // Resolve lazily in case send() runs before load() settled.
478
+ let chatroomId = s.resolvedChatroomId;
479
+ if (!chatroomId) chatroomId = await resolveChatroomId(inputId(), inputKind());
480
+ if (!chatroomId) return { ...liveState(), sendHint: "Couldn't start conversation." };
481
+ try {
482
+ await postOnce(chatroomId, text, s.threadMember!);
483
+ } catch (e) {
484
+ if (liveState().threadMember !== s.threadMember) return liveState();
485
+ try { await assertThreadMember(s); }
486
+ catch (error) { return threadFailure(error); }
487
+ // Surface a short reason (the SDK rejects with "HTTP <code>: <body>") so a
488
+ // real failure is diagnosable on-device instead of an opaque "Couldn't send".
489
+ // A failure that may have posted anyway (a gateway timeout after the backend stored
490
+ // it) must not read as "Couldn't send": say it may have gone. A retry of the same text
491
+ // reuses its message id, so it cannot become a second message.
492
+ const msg = (e as { message?: string })?.message || "";
493
+ if (writeMayHaveLanded(e)) return { ...liveState(), resolvedChatroomId: chatroomId, sendHint: "Couldn't confirm it was sent — check before sending again." };
494
+ logChatSendError({ chatroomId, error: e, offline: isOfflineFailure(e) });
495
+ return { ...liveState(), resolvedChatroomId: chatroomId, sendHint: msg ? `Couldn't send — ${msg.slice(0, 80)}` : "Couldn't send — try again." };
496
+ }
497
+ await assertThreadMember(s);
498
+ if (liveState().threadMember !== s.threadMember) return liveState();
499
+ // SENT. From here on nothing may say otherwise: a failed re-read must not offer a
500
+ // second Send of a message that already posted.
501
+ const myUserId = s.myUserId || (await resolveMyUserId());
502
+ // Re-read THROUGH the live-read gate, so this read queues behind a tick already in
503
+ // flight instead of racing it: whatever lands last then holds the sent reply.
504
+ current = { chatroomId, myUserId };
505
+ const cleared = (now: S): string => (now.draft.trim() === text ? "" : now.draft);
506
+ try {
507
+ const messages = await gate.request();
508
+ await assertThreadMember(s);
509
+ if (liveState().threadMember !== s.threadMember) return liveState();
510
+ const now = liveState();
511
+ return { ...now, resolvedChatroomId: chatroomId, myUserId, messages, draft: cleared(now), emptyText: "", emptyHidden: true, scrollSend: nextScrollToken(now.scrollSend), sendHint: "Sent ✓" };
512
+ } catch (error) {
513
+ if (liveState().threadMember !== s.threadMember) return liveState();
514
+ if (readAccessDenied(error)) return threadFailure(error);
515
+ const now = liveState();
516
+ const local = localSentRow(`local-${now.messages.length}`, text);
517
+ return { ...now, resolvedChatroomId: chatroomId, myUserId, messages: [...now.messages, local], draft: cleared(now), emptyText: "", emptyHidden: true, scrollSend: nextScrollToken(now.scrollSend), sendHint: "Sent ✓" };
518
+ }
519
+ } catch (error) {
520
+ if (liveState().threadMember !== s.threadMember) return liveState();
521
+ return threadFailure(error);
522
+ } finally {
523
+ sendingNow = false;
524
+ }
525
+ }
526
+
527
+ type Actions = {
227
528
  prepare: (s: S) => S;
228
529
  load: (s: S, a?: unknown) => Promise<S | undefined>;
229
530
  setDraft: (s: S, a?: unknown) => S;
230
- send: (s: S) => Promise<S>;
531
+ send: (s: S) => S | Promise<S>;
532
+ retry: (s: S, a?: unknown) => S;
533
+ settleSend: (s: S, r?: SendSettle) => S | Promise<S> | undefined;
534
+ archive: (s: S, a?: unknown) => Promise<S>;
535
+ unarchive: (s: S, a?: unknown) => Promise<S>;
536
+ markUnread: (s: S, a?: unknown) => Promise<S>;
537
+ delete: (s: S, a?: unknown) => Promise<S>;
538
+ dismissRoomActionError: (s: S) => S;
231
539
  refresh: (s: S) => Promise<S>;
232
540
  onStreamEvent: (s: S) => Promise<S>;
233
541
  onStreamError: (s: S) => S;
234
- }>(SERVICE, {
542
+ };
543
+
544
+ const svc = defineService<S, Actions>(SERVICE, {
235
545
  state: INITIAL,
236
- actions: {
237
- prepare: (s) => ({ ...s, ...INITIAL, _poll: { id: CHAT_LIVE_POLL_ID, stop: true } }),
546
+ actions: shaped<Actions>({
547
+ prepare: (s) => ({ ...s, ...fresh(), _poll: { id: CHAT_LIVE_POLL_ID, stop: true } }),
238
548
  load: async (s, a): Promise<S | undefined> => {
239
549
  const version = ++loadVersion;
240
550
  await svc.prepare();
@@ -242,10 +552,12 @@ const svc = defineService<S, {
242
552
  stashCopy(a);
243
553
  const param = (a as { chatRealtime?: unknown } | null | undefined)?.chatRealtime;
244
554
  if (param !== undefined) realtime = chatRealtimeConfig(param);
555
+ const opt = (a as { richThread?: unknown } | null | undefined)?.richThread;
556
+ if (opt !== undefined) rich = isFlag(opt);
245
557
  const raw = inputId();
246
558
  // No thread / recipient id (a stale link, a route opened directly) -> the shared
247
559
  // not-found state, and no composer: there is nobody to send to.
248
- if (!detailInputId()) return { ...INITIAL, status: "ready", messages: [], emptyText: "", emptyHidden: true, ...presence("missing") };
560
+ if (!detailInputId()) { resetVisit(); return { ...fresh(), status: "ready", messages: [], emptyText: "", emptyHidden: true, ...presence("missing") }; }
249
561
  memberToken.reset();
250
562
  try {
251
563
  const member = await readAccess();
@@ -255,15 +567,19 @@ const svc = defineService<S, {
255
567
  // A recipient whose 1:1 chatroom could not be resolved is not a conversation yet:
256
568
  // reload("") would return [] without throwing and publish a live, empty thread
257
569
  // whose Send can only fail. Show the load-error line instead.
258
- if (!chatroomId) return version === loadVersion ? { ...INITIAL, status: "ready", ...presence("failed") } : undefined;
259
- const messages = await reload(chatroomId, myUserId, member);
570
+ if (!chatroomId) return version === loadVersion ? { ...fresh(), status: "ready", ...presence("failed"), errorKind: "server" } : undefined;
571
+ // A newer load owns the visit now: a superseded one must not reset it.
572
+ if (version !== loadVersion) return undefined;
573
+ // Another member or another room than the last visit's: nothing of it is kept (local sends, private links).
574
+ if (outboxOwner !== ownerKeyOf(member, chatroomId)) { resetVisit(); outboxOwner = ownerKeyOf(member, chatroomId); }
575
+ const messages = await reload(chatroomId, myUserId, member, () => version === loadVersion);
260
576
  await assertReadAccess(member);
261
577
  if (version !== loadVersion) return undefined;
262
578
  current = { chatroomId, myUserId };
263
579
  const previous = s.threadMember;
264
- const sameReader = previous?.member.email === member.member.email && previous?.member.scope === member.member.scope && previous?.tenant === member.tenant;
265
- const draft = sameReader && s.resolvedChatroomId === chatroomId ? s.draft : "";
266
- return { ...INITIAL, draft, threadMember: member, status: "ready", resolvedChatroomId: chatroomId, myUserId, messages, emptyText: messages.length ? "" : EMPTY_TEXT, emptyHidden: messages.length > 0, scrollSend: messages.length ? nextScrollToken(s.scrollSend) : "", ...presence("found"), ...liveDirectives(realtime, chatroomId, SERVICE) };
580
+ const draft = sameReader(previous, member) && s.resolvedChatroomId === chatroomId ? s.draft : "";
581
+ const base: S = { ...fresh(), draft, threadMember: member, status: "ready", resolvedChatroomId: chatroomId, myUserId, messages, emptyText: messages.length ? "" : EMPTY_TEXT, emptyHidden: messages.length > 0, scrollSend: messages.length ? nextScrollToken(s.scrollSend) : "", ...presence("found") };
582
+ return { ...base, ...peerOf(base, chatroomId), ...liveDirectives(realtime, chatroomId, SERVICE) };
267
583
  } catch (e) {
268
584
  // A thread whose messages cannot be read is not a live, empty conversation: a 404
269
585
  // is the shared not-found state, anything else the load-error line — never a
@@ -279,71 +595,38 @@ const svc = defineService<S, {
279
595
  // "The conversation changed" — the event's payload is deliberately not read.
280
596
  onStreamEvent: async (s) => reread(s),
281
597
  // The channel is gone, or this host refuses it (the web host does): poll instead.
282
- onStreamError: (s) => (s.found && s.resolvedChatroomId ? { ...s, ...liveFallback(SERVICE) } : s),
598
+ onStreamError: (s) => (s.found && s.resolvedChatroomId && !s.closed ? { ...s, ...liveFallback(SERVICE) } : s),
283
599
  // REAL WRITE: send the typed message to the RESOLVED chatroom id, then re-read.
284
600
  // Every return builds on the LIVE state: the runtime replaces state wholesale, and ticks
285
601
  // or typing may have changed it while this awaited.
286
- send: async (s) => {
287
- if (!s.found) return s;
288
- const text = s.draft.trim();
289
- try { await assertThreadMember(s); }
290
- catch (error) { return liveState().threadMember !== s.threadMember ? liveState() : threadFailure(error); }
291
- if (liveState().threadMember !== s.threadMember) return liveState();
292
- const checked = liveState();
293
- if (!text) return checked.draft.trim() ? checked : { ...checked, sendHint: "Type a message first." };
294
- if (sendingNow) return checked;
295
- sendingNow = true;
296
- try {
297
- // Resolve lazily in case send() runs before load() settled.
298
- let chatroomId = s.resolvedChatroomId;
299
- if (!chatroomId) chatroomId = await resolveChatroomId(inputId(), inputKind());
300
- if (!chatroomId) return { ...liveState(), sendHint: "Couldn't start conversation." };
301
- try {
302
- await postOnce(chatroomId, text, s.threadMember!);
303
- } catch (e) {
304
- if (liveState().threadMember !== s.threadMember) return liveState();
305
- try { await assertThreadMember(s); }
306
- catch (error) { return threadFailure(error); }
307
- // Surface a short reason (the SDK rejects with "HTTP <code>: <body>") so a
308
- // real failure is diagnosable on-device instead of an opaque "Couldn't send".
309
- // A failure that may have posted anyway (a gateway timeout after the backend stored
310
- // it) must not read as "Couldn't send": say it may have gone. A retry of the same text
311
- // reuses its message id, so it cannot become a second message.
312
- const msg = (e as { message?: string })?.message || "";
313
- if (writeMayHaveLanded(e)) return { ...liveState(), resolvedChatroomId: chatroomId, sendHint: "Couldn't confirm it was sent — check before sending again." };
314
- logChatSendError({ chatroomId, error: e, offline: isOfflineFailure(e) });
315
- return { ...liveState(), resolvedChatroomId: chatroomId, sendHint: msg ? `Couldn't send — ${msg.slice(0, 80)}` : "Couldn't send — try again." };
316
- }
317
- await assertThreadMember(s);
318
- if (liveState().threadMember !== s.threadMember) return liveState();
319
- // SENT. From here on nothing may say otherwise: a failed re-read must not offer a
320
- // second Send of a message that already posted.
321
- const myUserId = s.myUserId || (await resolveMyUserId());
322
- // Re-read THROUGH the live-read gate, so this read queues behind a tick already in
323
- // flight instead of racing it: whatever lands last then holds the sent reply.
324
- current = { chatroomId, myUserId };
325
- const cleared = (now: S): string => (now.draft.trim() === text ? "" : now.draft);
326
- try {
327
- const messages = await gate.request();
328
- await assertThreadMember(s);
329
- if (liveState().threadMember !== s.threadMember) return liveState();
330
- const now = liveState();
331
- return { ...now, resolvedChatroomId: chatroomId, myUserId, messages, draft: cleared(now), emptyText: "", emptyHidden: true, scrollSend: nextScrollToken(now.scrollSend), sendHint: "Sent ✓" };
332
- } catch (error) {
333
- if (liveState().threadMember !== s.threadMember) return liveState();
334
- if (readAccessDenied(error)) return threadFailure(error);
335
- const now = liveState();
336
- const local: Row = { id: `local-${now.messages.length}`, text, when: "", leadFill: " ", mine: true, notMine: false, senderBadge: "", avatarUrl: "", avatarInitials: "", imageUrl: "", imageDescription: "", imageHidden: true, dayLabel: "", dayHidden: true };
337
- return { ...now, resolvedChatroomId: chatroomId, myUserId, messages: [...now.messages, local], draft: cleared(now), emptyText: "", emptyHidden: true, scrollSend: nextScrollToken(now.scrollSend), sendHint: "Sent ✓" };
338
- }
339
- } catch (error) {
340
- if (liveState().threadMember !== s.threadMember) return liveState();
341
- return threadFailure(error);
342
- } finally {
343
- sendingNow = false;
344
- }
602
+ send: (s) => (rich ? richSend(s) : legacySend(s)),
603
+ // Resend a failed message under its own id (richThread).
604
+ retry: (s, a) => {
605
+ const id = idOf(a);
606
+ const entry = outbox.find((e) => e.id === id && e.state === "failed");
607
+ if (!entry || !s.found || !s.threadMember || entry.roomId !== s.resolvedChatroomId || entry.roomId !== current.chatroomId) return s;
608
+ setOutbox(id, "sending");
609
+ void deliver({ ...entry, state: "sending" }, s.threadMember, visitEpoch);
610
+ return { ...s, messages: renderRows(entry.roomId, s.myUserId), sendHint: "" };
611
+ },
612
+ // A send's request reports back (internal). A sent message stays a row until the server lists it.
613
+ settleSend: (s, r) => {
614
+ const entry = r ? outbox.find((e) => e.id === r.id) : undefined;
615
+ // `epoch` is the visit that sent it (a member or room change bumps it). A load running meanwhile has no member on
616
+ // screen yet; its next render reads the outbox.
617
+ if (!r || !entry || r.epoch !== visitEpoch || (s.threadMember && !sameReader(s.threadMember, r.member))) return undefined;
618
+ if (r.outcome === "signIn") return threadFailure(new Error("Unauthenticated: sign in to send messages"));
619
+ setOutbox(r.id, r.outcome === "ok" ? "sent" : "failed");
620
+ if (!s.found) return undefined;
621
+ if (r.outcome === "ok") void svc.refresh();
622
+ return { ...s, messages: renderRows(entry.roomId, s.myUserId) };
345
623
  },
346
- },
624
+ archive: (s, a) => roomAction(s, a, "archive"),
625
+ unarchive: (s, a) => roomAction(s, a, "unarchive"),
626
+ markUnread: (s, a) => roomAction(s, a, "markUnread"),
627
+ delete: (s, a) => roomAction(s, a, "delete"),
628
+ dismissRoomActionError: (s) => ({ ...s, roomActionError: "" }),
629
+ }),
347
630
  });
348
631
  svc.prepare();
349
632
  svc.load();