@marktiderman/genesis-chat 0.7.0 → 0.8.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 (51) hide show
  1. package/README.md +132 -3
  2. package/dist/{chunk-GBJ3YI4E.js → chunk-5XYDVUPS.js} +6 -3
  3. package/dist/chunk-5XYDVUPS.js.map +1 -0
  4. package/dist/{chunk-XQ2ULNHV.js → chunk-D4RPOYB7.js} +4 -4
  5. package/dist/chunk-D4RPOYB7.js.map +1 -0
  6. package/dist/{chunk-RYD6WJE5.js → chunk-O2QSBRSH.js} +3 -3
  7. package/dist/{chunk-RYD6WJE5.js.map → chunk-O2QSBRSH.js.map} +1 -1
  8. package/dist/{chunk-A4YJX7KT.js → chunk-ZQFREERR.js} +3 -3
  9. package/dist/{chunk-A4YJX7KT.js.map → chunk-ZQFREERR.js.map} +1 -1
  10. package/dist/{client-DUIG1hum.d.ts → client-DP7rhJ1U.d.ts} +17 -6
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +2 -2
  13. package/dist/native.d.ts +31 -15
  14. package/dist/native.js +74 -328
  15. package/dist/native.js.map +1 -1
  16. package/dist/{outbox-B9NAWQ58.d.ts → outbox-C4LnqpKT.d.ts} +1 -1
  17. package/dist/push.d.ts +2 -2
  18. package/dist/react.d.ts +4 -8
  19. package/dist/react.js +3 -3
  20. package/dist/server.d.ts +1 -1
  21. package/dist/server.js +1 -1
  22. package/dist/{thread-oPra7pkW.d.ts → thread-CSzdqNR_.d.ts} +1 -1
  23. package/dist/web.d.ts +201 -7
  24. package/dist/web.js +580 -56
  25. package/dist/web.js.map +1 -1
  26. package/migrations/0004_genesis_chat_tenants.sql +716 -0
  27. package/migrations/tests/0001_genesis_chat.test.sql +10 -2
  28. package/migrations/tests/0002_genesis_chat_coaching.test.sql +8 -0
  29. package/migrations/tests/0003_genesis_chat_search_threads.test.sql +8 -0
  30. package/migrations/tests/0004_genesis_chat_tenants.test.sql +259 -0
  31. package/package.json +18 -7
  32. package/src/__tests__/core.test.ts +12 -0
  33. package/src/__tests__/web-dock.test.tsx +465 -0
  34. package/src/__tests__/web-photo-viewer.test.tsx +43 -0
  35. package/src/__tests__/web.test.tsx +26 -0
  36. package/src/core/client.ts +5 -1
  37. package/src/core/types.ts +16 -0
  38. package/src/native/__tests__/photo-viewer.test.tsx +24 -5
  39. package/src/native/photo-viewer.tsx +109 -422
  40. package/src/native/thread-screen.tsx +14 -5
  41. package/src/native/use-jump.ts +3 -0
  42. package/src/react/index.tsx +2 -1
  43. package/src/web/attachments.tsx +39 -55
  44. package/src/web/composer.tsx +5 -0
  45. package/src/web/dock.tsx +889 -0
  46. package/src/web/inbox.tsx +5 -0
  47. package/src/web/index.ts +23 -0
  48. package/src/web/memory-client.ts +1 -1
  49. package/src/web/thread.tsx +42 -3
  50. package/dist/chunk-GBJ3YI4E.js.map +0 -1
  51. package/dist/chunk-XQ2ULNHV.js.map +0 -1
@@ -0,0 +1,465 @@
1
+ /**
2
+ * @vitest-environment happy-dom
3
+ * @feat:chat-dock
4
+ */
5
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
6
+ import { act, cleanup, configure, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
7
+ import { useEffect, type ReactNode } from "react";
8
+ import { renderToString } from "react-dom/server";
9
+ import { hydrateRoot } from "react-dom/client";
10
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
11
+ import { ChatProvider } from "../react";
12
+ import {
13
+ ChatDock,
14
+ ChatDockProvider,
15
+ chatDockReducer,
16
+ chatDockWindowsThatFit,
17
+ createMemoryChatClient,
18
+ forgetChatDock,
19
+ emptyChatDock,
20
+ useChatDock,
21
+ type ChatDockApi,
22
+ type ChatDockItem,
23
+ type MemoryConversationSeed,
24
+ } from "../web";
25
+
26
+ afterEach(cleanup);
27
+ configure({ asyncUtilTimeout: 4000 });
28
+
29
+ const ME = "00000000-0000-4000-8000-0000000000a1";
30
+ const SAM = "00000000-0000-4000-8000-0000000000b2";
31
+ const LEE = "00000000-0000-4000-8000-0000000000c3";
32
+ const names: Record<string, string> = { [ME]: "Me", [SAM]: "Sam", [LEE]: "Lee" };
33
+ const resolveUser = (id: string) => ({ name: names[id] ?? "Someone" });
34
+ const at = (min: number) => new Date(Date.now() - (60 - min) * 60_000).toISOString();
35
+
36
+ const conv = (id: string, title: string, over: Partial<MemoryConversationSeed> = {}): MemoryConversationSeed => ({
37
+ id,
38
+ title,
39
+ members: [{ userId: ME }, { userId: SAM }, { userId: LEE }],
40
+ messages: [{ id: `${id}-m1`, senderId: SAM, body: `Hello from ${title}`, createdAt: at(1) }],
41
+ ...over,
42
+ });
43
+
44
+ const conversation = (id: string): ChatDockItem => ({ type: "conversation", id, conversationId: id, minimized: false });
45
+
46
+ function setWidth(width: number) {
47
+ (window as unknown as { happyDOM: { setViewport: (v: { width: number; height: number }) => void } }).happyDOM.setViewport({ width, height: 900 });
48
+ }
49
+
50
+ let dock: ChatDockApi;
51
+ function Grab() {
52
+ dock = useChatDock();
53
+ return null;
54
+ }
55
+
56
+ function mount(opts: { onExpand?: (item: ChatDockItem) => void; storageKey?: string; children?: ReactNode } = {}) {
57
+ const client = createMemoryChatClient({
58
+ me: ME,
59
+ conversations: [conv("c1", "Morning crew"), conv("c2", "Book club"), conv("c3", "Climbing"), conv("c4", "Parents")],
60
+ });
61
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
62
+ render(
63
+ <QueryClientProvider client={queryClient}>
64
+ <ChatProvider client={client} userId={ME}>
65
+ <ChatDockProvider {...(opts.onExpand ? { onExpand: opts.onExpand } : {})} {...(opts.storageKey ? { storageKey: opts.storageKey } : {})}>
66
+ <Grab />
67
+ {opts.children}
68
+ <ChatDock resolveUser={resolveUser} />
69
+ </ChatDockProvider>
70
+ </ChatProvider>
71
+ </QueryClientProvider>,
72
+ );
73
+ return client;
74
+ }
75
+
76
+ describe("chatDockReducer", () => {
77
+ it("opens first, brings an open one back to the front un-minimized, and drops the oldest past max", () => {
78
+ let s = emptyChatDock;
79
+ for (const id of ["a", "b", "c"]) s = chatDockReducer(s, { type: "open", item: conversation(id) });
80
+ expect(s.items.map((i) => i.id)).toEqual(["c", "b", "a"]);
81
+ s = chatDockReducer(s, { type: "minimize", id: "a", minimized: true });
82
+ s = chatDockReducer(s, { type: "open", item: conversation("a") });
83
+ expect(s.items.map((i) => i.id)).toEqual(["a", "c", "b"]);
84
+ expect(s.items[0]!.minimized).toBe(false);
85
+ s = chatDockReducer(s, { type: "open", item: conversation("d") });
86
+ expect(s.items.map((i) => i.id)).toEqual(["d", "a", "c"]);
87
+ expect(s.activeId).toBe("d");
88
+ });
89
+
90
+ it("closing the active one makes the next active, and closing the last closes the sheet", () => {
91
+ let s = chatDockReducer(emptyChatDock, { type: "open", item: conversation("a") });
92
+ s = chatDockReducer(s, { type: "open", item: conversation("b") });
93
+ s = chatDockReducer(s, { type: "close", id: "b" });
94
+ expect(s.activeId).toBe("a");
95
+ expect(s.sheetOpen).toBe(true);
96
+ s = chatDockReducer(s, { type: "close", id: "a" });
97
+ expect(s).toMatchObject({ items: [], activeId: null, sheetOpen: false, used: {} });
98
+ });
99
+
100
+ it("keeps the same state object for no-op actions", () => {
101
+ const s = chatDockReducer(emptyChatDock, { type: "open", item: conversation("a") });
102
+ expect(chatDockReducer(s, { type: "close", id: "zzz" })).toBe(s);
103
+ expect(chatDockReducer(s, { type: "minimize", id: "a", minimized: false })).toBe(s);
104
+ expect(chatDockReducer(emptyChatDock, { type: "sheet", open: true })).toBe(emptyChatDock);
105
+ });
106
+
107
+ it("honours a max of 1", () => {
108
+ let s = chatDockReducer(emptyChatDock, { type: "open", item: conversation("a") }, 1);
109
+ s = chatDockReducer(s, { type: "open", item: conversation("b") }, 1);
110
+ expect(s.items.map((i) => i.id)).toEqual(["b"]);
111
+ });
112
+ });
113
+
114
+ describe("ChatDock on a wide screen", () => {
115
+ beforeEach(() => setWidth(1280));
116
+
117
+ it("draws nothing until something opens", () => {
118
+ mount();
119
+ expect(screen.queryByTestId("genesis-chat-dock")).toBeNull();
120
+ });
121
+
122
+ it("opens a conversation in a window with the thread's own title, messages and composer", async () => {
123
+ mount();
124
+ act(() => dock.open("c1"));
125
+ const win = await screen.findByTestId("genesis-chat-dock-window");
126
+ expect(await within(win).findByText("Hello from Morning crew")).toBeTruthy();
127
+ expect(within(win).getAllByText("Morning crew").length).toBeGreaterThan(0);
128
+ expect(within(win).getByRole("textbox")).toBeTruthy();
129
+ // One header: the dock's bar fills the thread's header slot.
130
+ expect(within(win).queryByTestId("genesis-chat-thread-header")).toBeNull();
131
+ expect(within(win).getAllByTestId("genesis-chat-dock-titlebar")).toHaveLength(1);
132
+ });
133
+
134
+ it("holds three windows, newest on the right edge, and a fourth replaces the one used longest ago", async () => {
135
+ mount();
136
+ act(() => {
137
+ dock.open("c1");
138
+ dock.open("c2");
139
+ dock.open("c3");
140
+ });
141
+ await waitFor(() => expect(screen.getAllByTestId("genesis-chat-dock-window")).toHaveLength(3));
142
+ act(() => dock.open("c4"));
143
+ await waitFor(() => expect(screen.getByRole("region", { name: "Parents" })).toBeTruthy());
144
+ const wins = screen.getAllByTestId("genesis-chat-dock-window");
145
+ expect(wins).toHaveLength(3);
146
+ expect(screen.queryByRole("region", { name: "Morning crew" })).toBeNull();
147
+ });
148
+
149
+ it("minimizes to a bar without the thread (so it isn't marked read), and opens again", async () => {
150
+ mount();
151
+ act(() => dock.open("c1"));
152
+ const win = await screen.findByTestId("genesis-chat-dock-window");
153
+ await within(win).findByText("Hello from Morning crew");
154
+ fireEvent.click(within(win).getByTestId("genesis-chat-dock-toggle"));
155
+ await waitFor(() => expect(win.getAttribute("data-minimized")).toBe("true"));
156
+ expect(within(win).queryByRole("textbox")).toBeNull();
157
+ const toggle = within(win).getByTestId("genesis-chat-dock-toggle");
158
+ expect(toggle.getAttribute("aria-expanded")).toBe("false");
159
+ fireEvent.click(toggle);
160
+ expect(await within(win).findByRole("textbox")).toBeTruthy();
161
+ });
162
+
163
+ it("Escape in a window minimizes it", async () => {
164
+ mount();
165
+ act(() => dock.open("c1"));
166
+ const win = await screen.findByTestId("genesis-chat-dock-window");
167
+ const box = await within(win).findByRole("textbox");
168
+ fireEvent.keyDown(box, { key: "Escape" });
169
+ await waitFor(() => expect(win.getAttribute("data-minimized")).toBe("true"));
170
+ });
171
+
172
+ it("closes a window", async () => {
173
+ mount();
174
+ act(() => dock.open("c1"));
175
+ const win = await screen.findByTestId("genesis-chat-dock-window");
176
+ fireEvent.click(within(win).getByTestId("genesis-chat-dock-close"));
177
+ await waitFor(() => expect(screen.queryByTestId("genesis-chat-dock-window")).toBeNull());
178
+ });
179
+
180
+ it("expand hands the conversation to the Messages page and takes it out of the dock", async () => {
181
+ const onExpand = vi.fn();
182
+ mount({ onExpand });
183
+ act(() => dock.open("c2"));
184
+ const win = await screen.findByTestId("genesis-chat-dock-window");
185
+ fireEvent.click(within(win).getByTestId("genesis-chat-dock-expand"));
186
+ expect(onExpand).toHaveBeenCalledWith(expect.objectContaining({ type: "conversation", conversationId: "c2" }));
187
+ await waitFor(() => expect(screen.queryByTestId("genesis-chat-dock-window")).toBeNull());
188
+ });
189
+
190
+ it("has no expand button without somewhere to expand to", async () => {
191
+ mount();
192
+ act(() => dock.open("c1"));
193
+ const win = await screen.findByTestId("genesis-chat-dock-window");
194
+ expect(within(win).queryByTestId("genesis-chat-dock-expand")).toBeNull();
195
+ });
196
+
197
+ it("shows a minimized conversation's unread count on its bar", async () => {
198
+ const client = mount();
199
+ act(() => dock.open("c3", { minimized: true }));
200
+ const win = await screen.findByTestId("genesis-chat-dock-window");
201
+ const label = () => within(win).getByTestId("genesis-chat-dock-toggle").getAttribute("aria-label");
202
+ await waitFor(() => expect(label()).toContain("Climbing, 1 unread"));
203
+ act(() => void client.receive("c3", SAM, "On the wall at six"));
204
+ await waitFor(() => expect(label()).toContain("Climbing, 2 unread"));
205
+ // Still a bar: the new message didn't open it or mark it read.
206
+ expect(win.getAttribute("data-minimized")).toBe("true");
207
+ });
208
+
209
+ it("opens a panel of the app's own (the help desk messenger), once per id, with its own expand", async () => {
210
+ mount({ onExpand: vi.fn() });
211
+ const panelExpand = vi.fn();
212
+ act(() => dock.openPanel({ id: "help", title: "Help", render: () => <p>How can we help?</p>, onExpand: panelExpand }));
213
+ act(() => dock.openPanel({ id: "help", title: "Help", render: () => <p>How can we help?</p>, onExpand: panelExpand }));
214
+ const win = await screen.findByTestId("genesis-chat-dock-window");
215
+ expect(screen.getAllByTestId("genesis-chat-dock-window")).toHaveLength(1);
216
+ expect(within(win).getByText("How can we help?")).toBeTruthy();
217
+ fireEvent.click(within(win).getByTestId("genesis-chat-dock-expand"));
218
+ expect(panelExpand).toHaveBeenCalledTimes(1);
219
+ });
220
+
221
+ it("updates a docked panel's unread count in place, without moving or opening it", async () => {
222
+ mount();
223
+ act(() => {
224
+ dock.openPanel({ id: "help", title: "Help", render: () => <p>Help home</p>, minimized: true });
225
+ dock.open("c1");
226
+ });
227
+ await waitFor(() => expect(screen.getAllByTestId("genesis-chat-dock-window")).toHaveLength(2));
228
+ act(() => dock.updatePanel("help", { unread: 3 }));
229
+ const help = screen.getByRole("region", { name: "Help" });
230
+ expect(within(help).getByTestId("genesis-chat-dock-toggle").getAttribute("aria-label")).toContain("Help, 3 unread");
231
+ expect(help.getAttribute("data-minimized")).toBe("true");
232
+ expect(dock.items.map((i) => i.id)).toEqual(["c1", "help"]);
233
+ // Not docked: nothing happens.
234
+ act(() => dock.updatePanel("nope", { unread: 1 }));
235
+ expect(dock.items).toHaveLength(2);
236
+ });
237
+
238
+ it("keeps the open conversations across a reload, as bars, when given a storageKey", async () => {
239
+ window.localStorage.clear();
240
+ mount({ storageKey: "dock-test" });
241
+ act(() => {
242
+ dock.open("c1");
243
+ dock.openPanel({ id: "help", title: "Help", render: () => null });
244
+ });
245
+ await waitFor(() => expect(JSON.parse(window.localStorage.getItem(`dock-test:${ME}`) ?? "[]")).toEqual([{ conversationId: "c1" }]));
246
+ cleanup();
247
+ mount({ storageKey: "dock-test" });
248
+ const win = await screen.findByTestId("genesis-chat-dock-window");
249
+ expect(win.getAttribute("data-minimized")).toBe("true");
250
+ expect(dock.items.map((i) => i.id)).toEqual(["c1"]);
251
+ // Kept per person: someone else signing in on this browser sees none of it.
252
+ expect(window.localStorage.getItem("dock-test")).toBeNull();
253
+ forgetChatDock("dock-test", ME);
254
+ expect(window.localStorage.getItem(`dock-test:${ME}`)).toBeNull();
255
+ });
256
+
257
+ it("ignores storage it can't read", () => {
258
+ window.localStorage.setItem(`dock-bad:${ME}`, "{not json");
259
+ mount({ storageKey: "dock-bad" });
260
+ expect(dock.items).toEqual([]);
261
+ });
262
+ });
263
+
264
+ describe("ChatDock on a narrow screen", () => {
265
+ beforeEach(() => setWidth(390));
266
+ afterEach(() => setWidth(1280));
267
+
268
+ it("opens in a side sheet, switches between open conversations, and closes to a bubble", async () => {
269
+ mount();
270
+ act(() => {
271
+ dock.open("c1");
272
+ dock.open("c2");
273
+ });
274
+ const sheet = await screen.findByTestId("genesis-chat-dock-sheet");
275
+ expect(await within(sheet).findByText("Hello from Book club")).toBeTruthy();
276
+ const tabs = within(sheet).getByTestId("genesis-chat-dock-switcher");
277
+ fireEvent.click(within(tabs).getByRole("tab", { name: /Morning crew/ }));
278
+ expect(await within(sheet).findByText("Hello from Morning crew")).toBeTruthy();
279
+
280
+ act(() => dock.setSheetOpen(false));
281
+ const bubble = await screen.findByTestId("genesis-chat-dock-bubble");
282
+ fireEvent.click(bubble);
283
+ expect(await screen.findByTestId("genesis-chat-dock-sheet")).toBeTruthy();
284
+ });
285
+ });
286
+
287
+ describe("the review's fixes (#655)", () => {
288
+ beforeEach(() => setWidth(1280));
289
+
290
+ it("keeps what you were typing when a window is minimized, restored, or Escaped", async () => {
291
+ mount();
292
+ act(() => dock.open("c1"));
293
+ const win = await screen.findByTestId("genesis-chat-dock-window");
294
+ const box = (await within(win).findByRole("textbox")) as HTMLTextAreaElement;
295
+ fireEvent.change(box, { target: { value: "half a thought" } });
296
+ fireEvent.keyDown(box, { key: "Escape" });
297
+ await waitFor(() => expect(win.getAttribute("data-minimized")).toBe("true"));
298
+ fireEvent.click(within(win).getByTestId("genesis-chat-dock-toggle"));
299
+ await waitFor(() => expect((within(win).getByRole("textbox") as HTMLTextAreaElement).value).toBe("half a thought"));
300
+ });
301
+
302
+ it("doesn't minimize on Escape while an input method is composing", async () => {
303
+ mount();
304
+ act(() => dock.open("c1"));
305
+ const win = await screen.findByTestId("genesis-chat-dock-window");
306
+ const box = await within(win).findByRole("textbox");
307
+ fireEvent.keyDown(box, { key: "Escape", isComposing: true });
308
+ fireEvent.keyDown(box, { key: "Escape", keyCode: 229 });
309
+ expect(win.getAttribute("data-minimized")).toBeNull();
310
+ });
311
+
312
+ it("focuses the composer on open, and the window's bar when Escape minimizes it", async () => {
313
+ mount();
314
+ act(() => dock.open("c1"));
315
+ const win = await screen.findByTestId("genesis-chat-dock-window");
316
+ const box = await within(win).findByRole("textbox");
317
+ await waitFor(() => expect(document.activeElement).toBe(box));
318
+ fireEvent.keyDown(box, { key: "Escape" });
319
+ await waitFor(() => expect(document.activeElement).toBe(within(win).getByTestId("genesis-chat-dock-toggle")));
320
+ });
321
+
322
+ it("keeps focus on the bar's toggle when it minimizes and restores", async () => {
323
+ mount();
324
+ act(() => dock.open("c1"));
325
+ const win = await screen.findByTestId("genesis-chat-dock-window");
326
+ await within(win).findByRole("textbox");
327
+ const toggle = within(win).getByTestId("genesis-chat-dock-toggle");
328
+ toggle.focus();
329
+ fireEvent.click(toggle);
330
+ await waitFor(() => expect(win.getAttribute("data-minimized")).toBe("true"));
331
+ expect(within(win).getByTestId("genesis-chat-dock-toggle")).toBe(toggle);
332
+ expect(document.activeElement).toBe(toggle);
333
+ });
334
+
335
+ it("returns the same state for an update that changes nothing, or reopening the window in front", () => {
336
+ let s = chatDockReducer(emptyChatDock, { type: "open", item: { type: "panel", id: "help", title: "Help", render: () => null, unread: 2, minimized: false } });
337
+ expect(chatDockReducer(s, { type: "update", id: "help", patch: { unread: 2 } })).toBe(s);
338
+ expect(chatDockReducer(s, { type: "update", id: "help", patch: { unread: 3 } })).not.toBe(s);
339
+ s = chatDockReducer(s, { type: "open", item: conversation("a") });
340
+ expect(chatDockReducer(s, { type: "open", item: conversation("a") })).toBe(s);
341
+ expect(chatDockReducer(s, { type: "activate", id: "a" })).toBe(s);
342
+ expect(chatDockReducer(s, { type: "closeAll" })).not.toBe(s);
343
+ expect(chatDockReducer(emptyChatDock, { type: "closeAll" })).toBe(emptyChatDock);
344
+ });
345
+
346
+ it("settles when an effect keeps a panel's unread count live (the README's pattern)", async () => {
347
+ let renders = 0;
348
+ function Live({ unread }: { unread: number }) {
349
+ const d = useChatDock();
350
+ renders++;
351
+ useEffect(() => d.updatePanel("help", { unread }), [d, unread]);
352
+ return null;
353
+ }
354
+ mount({ children: <Live unread={4} /> });
355
+ act(() => dock.openPanel({ id: "help", title: "Help", render: () => null }));
356
+ await waitFor(() => expect(dock.items[0]).toMatchObject({ unread: 4 }));
357
+ const settled = renders;
358
+ await new Promise((r) => setTimeout(r, 50));
359
+ expect(renders).toBe(settled);
360
+ });
361
+
362
+ it("replaces the window used longest ago: restoring one counts as using it", () => {
363
+ let s = emptyChatDock;
364
+ for (const id of ["a", "b", "c"]) s = chatDockReducer(s, { type: "open", item: conversation(id) });
365
+ s = chatDockReducer(s, { type: "minimize", id: "a", minimized: true });
366
+ s = chatDockReducer(s, { type: "minimize", id: "a", minimized: false });
367
+ s = chatDockReducer(s, { type: "open", item: conversation("d") });
368
+ expect(s.items.map((i) => i.id).sort()).toEqual(["a", "c", "d"]);
369
+ });
370
+
371
+ it("shows as many windows as fit, and the rest behind +N, one of which comes to the front", async () => {
372
+ expect(chatDockWindowsThatFit(1280, 3)).toBe(3);
373
+ expect(chatDockWindowsThatFit(1000, 3)).toBe(2);
374
+ expect(chatDockWindowsThatFit(800, 3)).toBe(1);
375
+ expect(chatDockWindowsThatFit(1000, 1)).toBe(1);
376
+ setWidth(1000);
377
+ mount();
378
+ act(() => {
379
+ dock.open("c1");
380
+ dock.open("c2");
381
+ dock.open("c3");
382
+ });
383
+ await waitFor(() => expect(screen.getAllByTestId("genesis-chat-dock-window")).toHaveLength(2));
384
+ const more = screen.getByTestId("genesis-chat-dock-more");
385
+ expect(more.getAttribute("aria-label")).toBe("1 more conversation");
386
+ act(() => dock.bringToFront("c1"));
387
+ await waitFor(() => expect(screen.getByRole("region", { name: "Morning crew" })).toBeTruthy());
388
+ expect(screen.queryByRole("region", { name: "Book club" })).toBeNull();
389
+ });
390
+
391
+ it("drops a conversation brought back from storage that no longer exists", async () => {
392
+ window.localStorage.setItem(`dock-gone:${ME}`, JSON.stringify([{ conversationId: "c1" }, { conversationId: "gone" }]));
393
+ mount({ storageKey: "dock-gone" });
394
+ await waitFor(() => expect(dock.items.map((i) => i.id)).toEqual(["c1"]));
395
+ });
396
+
397
+ it("announces the unread total politely", async () => {
398
+ mount();
399
+ act(() => dock.open("c3", { minimized: true }));
400
+ const live = await screen.findByTestId("genesis-chat-dock-announce");
401
+ expect(live.getAttribute("aria-live")).toBe("polite");
402
+ await waitFor(() => expect(live.textContent).toBe("1 unread in your open conversations"));
403
+ });
404
+
405
+ it("hydrates server HTML without a mismatch, then brings stored bars back", async () => {
406
+ window.localStorage.setItem(`dock-ssr:${ME}`, JSON.stringify([{ conversationId: "c1" }]));
407
+ const client = createMemoryChatClient({ me: ME, conversations: [conv("c1", "Morning crew")] });
408
+ const tree = () => (
409
+ <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
410
+ <ChatProvider client={client} userId={ME}>
411
+ <ChatDockProvider storageKey="dock-ssr">
412
+ <Grab />
413
+ <ChatDock resolveUser={resolveUser} />
414
+ </ChatDockProvider>
415
+ </ChatProvider>
416
+ </QueryClientProvider>
417
+ );
418
+ const html = renderToString(tree());
419
+ expect(html).not.toContain("genesis-chat-dock-window");
420
+ const host = document.createElement("div");
421
+ host.innerHTML = html;
422
+ document.body.appendChild(host);
423
+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
424
+ const recoverable = vi.fn();
425
+ let root: ReturnType<typeof hydrateRoot> | undefined;
426
+ await act(async () => {
427
+ root = hydrateRoot(host, tree(), { onRecoverableError: recoverable });
428
+ });
429
+ await waitFor(() => expect(host.querySelector('[data-testid="genesis-chat-dock-window"]')).toBeTruthy());
430
+ expect(recoverable).not.toHaveBeenCalled();
431
+ expect(errors.mock.calls.filter((c) => /hydrat/i.test(String(c[0])))).toEqual([]);
432
+ errors.mockRestore();
433
+ act(() => root!.unmount());
434
+ host.remove();
435
+ });
436
+ });
437
+
438
+ describe("the narrow screen's switcher (#655)", () => {
439
+ beforeEach(() => setWidth(390));
440
+ afterEach(() => setWidth(1280));
441
+
442
+ it("switches without reordering, keeps each tab's draft, and moves with the arrow keys", async () => {
443
+ mount();
444
+ act(() => {
445
+ dock.open("c1");
446
+ dock.open("c2");
447
+ });
448
+ const sheet = await screen.findByTestId("genesis-chat-dock-sheet");
449
+ const tabs = within(sheet).getByTestId("genesis-chat-dock-switcher");
450
+ const order = () => within(tabs).getAllByRole("tab").map((t) => t.id);
451
+ const before = order();
452
+ const panel = () => within(sheet).getAllByRole("tabpanel").find((p) => !p.hidden)!;
453
+ const box = (await within(panel()).findByRole("textbox")) as HTMLTextAreaElement;
454
+ fireEvent.change(box, { target: { value: "for book club" } });
455
+ fireEvent.click(within(tabs).getByRole("tab", { name: /Morning crew/ }));
456
+ await waitFor(() => expect(within(tabs).getByRole("tab", { name: /Morning crew/ }).getAttribute("aria-selected")).toBe("true"));
457
+ expect(order()).toEqual(before);
458
+ const selected = within(tabs).getByRole("tab", { selected: true });
459
+ expect(selected.getAttribute("tabindex")).toBe("0");
460
+ expect(document.getElementById(selected.getAttribute("aria-controls")!)).toBe(panel());
461
+ fireEvent.keyDown(selected, { key: "ArrowLeft" });
462
+ await waitFor(() => expect(within(tabs).getByRole("tab", { name: /Book club/ }).getAttribute("aria-selected")).toBe("true"));
463
+ expect(((await within(panel()).findByRole("textbox")) as HTMLTextAreaElement).value).toBe("for book club");
464
+ });
465
+ });
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @vitest-environment happy-dom
3
+ * @feat:chat
4
+ */
5
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
6
+ import { afterEach, describe, expect, it, vi } from "vitest";
7
+ import { ImageGrid, Lightbox, type AttachmentView } from "../web/attachments";
8
+
9
+ afterEach(cleanup);
10
+
11
+ const view = (key: string, name: string): AttachmentView =>
12
+ ({ key, kind: "image", url: `https://x.test/${name}`, posterUrl: null, name, mime: "image/jpeg", bytes: null, width: 800, height: 600, durationMs: null, waveform: null, transcript: null, transcriptStatus: null, pending: false, attachment: null }) as unknown as AttachmentView;
13
+
14
+ describe("chat's photos full size", () => {
15
+ it("open in genesis-ui's Lightbox at the photo clicked, and page with the arrow keys", () => {
16
+ render(<ImageGrid images={[view("a", "a.jpg"), view("b", "b.jpg")]} />);
17
+ fireEvent.click(screen.getByRole("button", { name: "Open photo b.jpg" }));
18
+ expect(screen.getByRole("dialog")).toBeTruthy();
19
+ expect(document.querySelector('[data-slot="lightbox-counter"]')!.textContent).toBe("2 / 2");
20
+ expect(screen.getByRole("img", { name: "b.jpg" })).toBeTruthy();
21
+ fireEvent.click(screen.getByRole("button", { name: "Previous photo" }));
22
+ expect(screen.getByRole("img", { name: "a.jpg" })).toBeTruthy();
23
+ });
24
+
25
+ it("leave out a photo still uploading, with no link to show", () => {
26
+ const uploading = { ...view("u", "u.jpg"), url: null } as AttachmentView;
27
+ const onIndexChange = vi.fn();
28
+ render(<Lightbox images={[view("a", "a.jpg"), uploading, view("b", "b.jpg")]} index={2} onIndexChange={onIndexChange} />);
29
+ expect(document.querySelector('[data-slot="lightbox-counter"]')!.textContent).toBe("2 / 2");
30
+ expect(document.querySelector('img[src=""]')).toBeNull();
31
+ fireEvent.click(screen.getByRole("button", { name: "Previous photo" }));
32
+ expect(onIndexChange).toHaveBeenLastCalledWith(0);
33
+ });
34
+
35
+ it("keep the deprecated Lightbox export working: null closes it", () => {
36
+ const onIndexChange = vi.fn();
37
+ const { rerender } = render(<Lightbox images={[view("a", "a.jpg")]} index={0} onIndexChange={onIndexChange} />);
38
+ expect(screen.getByRole("dialog")).toBeTruthy();
39
+ expect(document.querySelector('[data-slot="lightbox-counter"]')).toBeNull();
40
+ rerender(<Lightbox images={[view("a", "a.jpg")]} index={null} onIndexChange={onIndexChange} />);
41
+ expect(screen.queryByRole("dialog")).toBeNull();
42
+ });
43
+ });
@@ -176,6 +176,32 @@ describe("ChatThread", () => {
176
176
  await waitFor(() => expect(document.querySelector("#genesis-chat-msg-m3 .ring-2")).not.toBeNull());
177
177
  });
178
178
 
179
+ it("scrolls only its own scroller to a message, never the panes or page around it", async () => {
180
+ const client = createMemoryChatClient({
181
+ me: ME,
182
+ conversations: [group({ messages: [...group().messages!, { id: "m6", senderId: SAM, body: "Yes!", replyToId: "m3", createdAt: at(7) }] })],
183
+ });
184
+ const intoView = vi.fn();
185
+ const original = HTMLElement.prototype.scrollIntoView;
186
+ const originalMatchMedia = window.matchMedia;
187
+ window.matchMedia = ((query: string) => ({ matches: false, media: query, addEventListener() {}, removeEventListener() {} })) as unknown as typeof window.matchMedia;
188
+ HTMLElement.prototype.scrollIntoView = intoView;
189
+ try {
190
+ mount(client, <ChatThread conversationId="c1" resolveUser={resolveUser} />);
191
+ const scroller = await screen.findByTestId("genesis-chat-scroller");
192
+ const scrollTo = vi.fn();
193
+ scroller.scrollTo = scrollTo as unknown as typeof scroller.scrollTo;
194
+ fireEvent.click(await screen.findByTestId("genesis-chat-reply-quote"));
195
+ await waitFor(() => expect(document.querySelector("#genesis-chat-msg-m3 .ring-2")).not.toBeNull());
196
+ // The thread's own scroller moves (smoothly: no reduced-motion preference here), and nothing else does.
197
+ expect(scrollTo).toHaveBeenCalledWith(expect.objectContaining({ top: expect.any(Number), behavior: "smooth" }));
198
+ expect(intoView).not.toHaveBeenCalled();
199
+ } finally {
200
+ HTMLElement.prototype.scrollIntoView = original;
201
+ window.matchMedia = originalMatchMedia;
202
+ }
203
+ });
204
+
179
205
  it("says why you can't post when only admins can", async () => {
180
206
  const client = createMemoryChatClient({ me: ME, conversations: [group({ canPost: false, settings: { who_posts: "admins" } })] });
181
207
  mount(client, <ChatThread conversationId="c1" resolveUser={resolveUser} />);
@@ -26,6 +26,7 @@ import type {
26
26
  ChatRole,
27
27
  ChatSignal,
28
28
  SendInput,
29
+ StartConversationOptions,
29
30
  } from "./types";
30
31
  import { normalizeHours } from "./availability";
31
32
  import { fileExtension, isAllowedExtension, randomId } from "./media";
@@ -144,6 +145,7 @@ function toConversation(r: Row): ChatConversation {
144
145
  title: str(r.title),
145
146
  subjectType: str(r.subject_type),
146
147
  subjectId: str(r.subject_id),
148
+ tenantId: str(r.tenant_id),
147
149
  settings: (r.settings as ChatConversation["settings"]) ?? {},
148
150
  status: (r.status as ChatConversation["status"]) ?? null,
149
151
  assigneeId: str(r.assignee_id),
@@ -429,13 +431,15 @@ export function createChatClient(supabase: ChatSupabase, options: ChatClientOpti
429
431
  return row ? toMessage(row as Row) : null;
430
432
  },
431
433
 
432
- async startConversation(kind: string, memberIds: string[], opts: { title?: string; subjectType?: string; subjectId?: string } = {}) {
434
+ async startConversation(kind: string, memberIds: string[], opts: StartConversationOptions = {}) {
433
435
  return rpc<string>("start_conversation", {
434
436
  p_kind: kind,
435
437
  p_member_ids: memberIds,
436
438
  p_title: opts.title ?? null,
437
439
  p_subject_type: opts.subjectType ?? null,
438
440
  p_subject_id: opts.subjectId ?? null,
441
+ // Only when given: the same call still reaches a database before 0004.
442
+ ...(opts.tenantId ? { p_tenant_id: opts.tenantId } : {}),
439
443
  });
440
444
  },
441
445
 
package/src/core/types.ts CHANGED
@@ -83,6 +83,8 @@ export interface ChatConversation {
83
83
  title: string | null;
84
84
  subjectType: string | null;
85
85
  subjectId: string | null;
86
+ /** The tenant it belongs to (migration 0004). Absent from clients that don't know tenants (the memory client). */
87
+ tenantId?: string | null;
86
88
  settings: { who_posts?: "members" | "admins" } & Record<string, unknown>;
87
89
  status: "open" | "pending" | "solved" | "closed" | null;
88
90
  assigneeId: string | null;
@@ -92,6 +94,20 @@ export interface ChatConversation {
92
94
  archivedAt: string | null;
93
95
  }
94
96
 
97
+ /** How a conversation starts (`startConversation`, `useStartConversation`). */
98
+ export interface StartConversationOptions {
99
+ title?: string;
100
+ /** One of your records it's about; a registered subject type also names its tenant. */
101
+ subjectType?: string;
102
+ subjectId?: string;
103
+ /**
104
+ * The tenant it's in, for people who share more than one (migration 0004). Without it, the
105
+ * subject's tenant or the one tenant everyone shares; "Choose the workspace this conversation
106
+ * is in" when they share several.
107
+ */
108
+ tenantId?: string;
109
+ }
110
+
95
111
  export interface ChatMember {
96
112
  conversationId: string;
97
113
  userId: string;
@@ -97,11 +97,13 @@ describe("ChatPhotoViewer", () => {
97
97
  const modal = screen.getByTestId("v");
98
98
  expect(modal.getAttribute("data-presentation-style")).toBe("overFullScreen");
99
99
  expect(modal.getAttribute("data-presentation-style")).not.toBe("pageSheet");
100
- expect(screen.getByTestId("v-counter").textContent).toBe("Photo 2 of 2");
101
- const pager = screen.getByTestId("v-pager");
100
+ // genesis-ui-native's NativeLightbox: a "2 / 2" counter for the eye, and the pager reads chat's words.
101
+ expect(screen.getByTestId("v-counter").textContent).toBe("2 / 2");
102
+ const pager = screen.getByTestId("v-pager-a11y");
102
103
  expect(pager.getAttribute("aria-label")).toBe("Photo, b.jpg");
103
- expect(screen.getByTestId("v-photo-0")).toBeTruthy();
104
- expect(screen.getByTestId("v-photo-1")).toBeTruthy();
104
+ expect(pager.getAttribute("aria-valuetext")).toBe("Photo 2 of 2");
105
+ expect(screen.getByTestId("v-photo-a")).toBeTruthy();
106
+ expect(screen.getByTestId("v-photo-b")).toBeTruthy();
105
107
  });
106
108
 
107
109
  it("closes from its Close button", () => {
@@ -147,6 +149,22 @@ describe("ChatPhotoViewer", () => {
147
149
  expect(screen.getByTestId("v-notice").textContent).toMatch(/Settings/);
148
150
  });
149
151
 
152
+ it("opens again without the last opening's notice", async () => {
153
+ const modules = { mediaLibrary: { requestPermissionsAsync: async () => ({ granted: true }), saveToLibraryAsync: vi.fn(async () => undefined) }, downloadFile: async () => "file:///x.jpg" };
154
+ const photos = [{ key: "a", uri: "https://x.test/a.jpg", alt: "Photo, a.jpg" }];
155
+ const ui = (p: typeof photos | null) => (
156
+ <ChatNativeProvider modules={modules}>
157
+ <ChatPhotoViewer photos={p} onClose={vi.fn()} testID="v" />
158
+ </ChatNativeProvider>
159
+ );
160
+ const { rerender } = render(ui(photos));
161
+ await act(async () => fireEvent.click(screen.getByTestId("v-save")));
162
+ expect(screen.getByTestId("v-notice")).toBeTruthy();
163
+ rerender(ui(null));
164
+ rerender(ui([...photos]));
165
+ expect(screen.queryByTestId("v-notice")).toBeNull();
166
+ });
167
+
150
168
  it("ChatMediaViewer, for one picture, is the same full-screen viewer", () => {
151
169
  render(
152
170
  <ChatNativeProvider>
@@ -201,7 +219,8 @@ describe("ChatThreadScreen", () => {
201
219
  fireEvent.click(second);
202
220
  const modal = await screen.findByTestId("t-viewer");
203
221
  expect(modal.getAttribute("data-presentation-style")).toBe("overFullScreen");
204
- expect(screen.getByTestId("t-viewer-counter").textContent).toBe("Photo 2 of 3");
222
+ expect(screen.getByTestId("t-viewer-counter").textContent).toBe("2 / 3");
223
+ expect(screen.getByTestId("t-viewer-pager-a11y").getAttribute("aria-valuetext")).toBe("Photo 2 of 3");
205
224
  fireEvent.click(screen.getByTestId("t-viewer-close"));
206
225
  await waitFor(() => expect(screen.queryByTestId("t-viewer")).toBeNull());
207
226
  });