@marktiderman/genesis-chat 0.12.0 → 0.13.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 (45) hide show
  1. package/README.md +46 -1
  2. package/dist/{chunk-2HNQWDLF.js → chunk-3UNYTK62.js} +3 -3
  3. package/dist/{chunk-2HNQWDLF.js.map → chunk-3UNYTK62.js.map} +1 -1
  4. package/dist/{chunk-VBIYDXL2.js → chunk-GEEJMKQF.js} +22 -3
  5. package/dist/chunk-GEEJMKQF.js.map +1 -0
  6. package/dist/{chunk-K5GYNHNE.js → chunk-H4BRVJJ7.js} +136 -23
  7. package/dist/chunk-H4BRVJJ7.js.map +1 -0
  8. package/dist/{chunk-3HQN2FZ5.js → chunk-SEMN3S6Q.js} +3 -3
  9. package/dist/{chunk-3HQN2FZ5.js.map → chunk-SEMN3S6Q.js.map} +1 -1
  10. package/dist/{client-DJs3ltZc.d.ts → client-DXWyDJ2u.d.ts} +14 -0
  11. package/dist/index.d.ts +4 -4
  12. package/dist/index.js +3 -3
  13. package/dist/native.d.ts +20 -12
  14. package/dist/native.js +40 -32
  15. package/dist/native.js.map +1 -1
  16. package/dist/{outbox-YFTbGIAl.d.ts → outbox-Ctngv6Yz.d.ts} +1 -1
  17. package/dist/push.d.ts +2 -2
  18. package/dist/react.d.ts +73 -4
  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-CgHP00Jw.d.ts → thread-mZsRiIGz.d.ts} +1 -1
  23. package/dist/web.d.ts +24 -7
  24. package/dist/web.js +140 -67
  25. package/dist/web.js.map +1 -1
  26. package/migrations/0007_genesis_chat_unread_and_delete_for_me.sql +455 -0
  27. package/migrations/tests/0007_genesis_chat_unread_and_delete_for_me.test.sql +178 -0
  28. package/package.json +13 -9
  29. package/src/__tests__/inbox-row-actions.test.tsx +251 -0
  30. package/src/__tests__/unread-delete-for-me.test.ts +84 -0
  31. package/src/__tests__/web.test.tsx +5 -2
  32. package/src/core/client.ts +21 -1
  33. package/src/native/__tests__/inbox-screen-actions.test.tsx +131 -0
  34. package/src/native/__tests__/inbox-screen.test.tsx +29 -1
  35. package/src/native/__tests__/thread-layout.test.ts +2 -2
  36. package/src/native/copy.ts +7 -10
  37. package/src/native/inbox-screen.tsx +52 -27
  38. package/src/native/index.ts +1 -1
  39. package/src/react/inbox-actions.ts +121 -0
  40. package/src/react/index.tsx +99 -17
  41. package/src/web/inbox.tsx +120 -11
  42. package/src/web/index.ts +1 -1
  43. package/src/web/memory-client.ts +40 -7
  44. package/dist/chunk-K5GYNHNE.js.map +0 -1
  45. package/dist/chunk-VBIYDXL2.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-chat",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -91,9 +91,9 @@
91
91
  },
92
92
  "peerDependencies": {
93
93
  "@marktiderman/genesis-ai": ">=0.1.0 <1.0.0",
94
- "@marktiderman/genesis-core": ">=2.13.0 <3.0.0",
95
- "@marktiderman/genesis-ui": ">=2.32.0 <4.0.0",
96
- "@marktiderman/genesis-ui-native": ">=3.8.0 <4.0.0",
94
+ "@marktiderman/genesis-core": ">=2.21.0 <3.0.0",
95
+ "@marktiderman/genesis-ui": ">=3.3.0 <4.0.0",
96
+ "@marktiderman/genesis-ui-native": ">=3.17.0 <4.0.0",
97
97
  "@supabase/supabase-js": "^2.118.0",
98
98
  "@tanstack/react-query": "^5.0.0",
99
99
  "hls.js": "^1.5.0",
@@ -173,19 +173,19 @@
173
173
  }
174
174
  },
175
175
  "devDependencies": {
176
- "@ai-sdk/anthropic": "4.0.102",
176
+ "@ai-sdk/anthropic": "4.0.105",
177
177
  "@marktiderman/genesis-ai": "^0.3.1",
178
- "@marktiderman/genesis-core": "^2.20.0",
178
+ "@marktiderman/genesis-core": "^2.21.0",
179
179
  "@marktiderman/genesis-notifications": "^0.4.7",
180
- "@marktiderman/genesis-ui": "^3.2.2",
181
- "@marktiderman/genesis-ui-native": "^3.16.0",
180
+ "@marktiderman/genesis-ui": "^3.3.0",
181
+ "@marktiderman/genesis-ui-native": "^3.17.0",
182
182
  "@supabase/supabase-js": "^2.118.0",
183
183
  "@tanstack/react-query": "^5.105.0",
184
184
  "@testing-library/react": "^16.3.2",
185
185
  "@types/node": "^22",
186
186
  "@types/react": "^19.2.14",
187
187
  "@types/react-dom": "^19.2.3",
188
- "ai": "7.0.170",
188
+ "ai": "7.0.173",
189
189
  "happy-dom": "^21.0.4",
190
190
  "hls.js": "1.7.4",
191
191
  "lucide-react": "^1.28.0",
@@ -255,6 +255,10 @@
255
255
  {
256
256
  "file": "migrations/0006_genesis_chat_read_receipts.sql",
257
257
  "test": "migrations/tests/0006_genesis_chat_read_receipts.test.sql"
258
+ },
259
+ {
260
+ "file": "migrations/0007_genesis_chat_unread_and_delete_for_me.sql",
261
+ "test": "migrations/tests/0007_genesis_chat_unread_and_delete_for_me.test.sql"
258
262
  }
259
263
  ],
260
264
  "install": [
@@ -0,0 +1,251 @@
1
+ /**
2
+ * @vitest-environment happy-dom
3
+ * @feat:chat
4
+ * The inbox's row actions, built once (`inboxRowActions`) for the phone and the web, run from the
5
+ * row (`useInboxActions`), and refreshed through the named prefix keys.
6
+ */
7
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
8
+ import { act, cleanup, configure, fireEvent, render, renderHook, screen, waitFor } from "@testing-library/react";
9
+ import type { ReactNode } from "react";
10
+ import { afterEach, describe, expect, it, vi } from "vitest";
11
+ import type { ChatClient } from "../core/client";
12
+ import type { ChatInboxItem } from "../core/types";
13
+ import { ChatProvider, chatKeys, defaultInboxActionLabels, inboxRowActions, useConversation, useInboxActions, type ChatInboxActions } from "../react";
14
+ import type { ChatMessage } from "../core/types";
15
+ import { ChatInbox, createMemoryChatClient, useConfirmDialog } from "../web";
16
+
17
+ afterEach(cleanup);
18
+ configure({ asyncUtilTimeout: 4000 });
19
+
20
+ const ME = "00000000-0000-4000-8000-0000000000a1";
21
+ const C = "00000000-0000-4000-8000-0000000000c1";
22
+
23
+ const item = (over: Partial<ChatInboxItem> = {}): ChatInboxItem =>
24
+ ({
25
+ conversationId: C, kind: "direct", title: "Sam", subjectType: null, subjectId: null, status: null, role: "member",
26
+ otherUserId: null, memberCount: 2, lastSeq: 7, lastReadSeq: 7, unread: 0, mentioned: false, muted: false, pinned: false,
27
+ archived: false, lastMessageAt: new Date().toISOString(), lastMessage: null, ...over,
28
+ }) as ChatInboxItem;
29
+
30
+ type Fake = { [K in keyof ChatInboxActions]: ReturnType<typeof vi.fn<ChatInboxActions[K]>> };
31
+ const fakeActions = (): Fake =>
32
+ ({
33
+ toggleUnread: vi.fn(async () => undefined),
34
+ togglePinned: vi.fn(async () => undefined),
35
+ toggleMuted: vi.fn(async () => undefined),
36
+ setArchived: vi.fn(async () => undefined),
37
+ deleteForMe: vi.fn(async () => undefined),
38
+ }) as unknown as Fake;
39
+
40
+ describe("inboxRowActions", () => {
41
+ it("is Messages' set, in its order, sides and colors", () => {
42
+ const actions = inboxRowActions(item(), fakeActions(), defaultInboxActionLabels, { confirm: async () => true });
43
+ expect(actions.map((a) => a.id)).toEqual(["unread", "pin", "alerts", "delete", "archive"]);
44
+ const by = (id: string) => actions.find((a) => a.id === id)!;
45
+ expect(by("unread")).toMatchObject({ tone: "info", swipe: { side: "leading", full: true }, icon: "message-unread", label: "Mark as Unread" });
46
+ expect(by("pin")).toMatchObject({ accent: "orange", swipe: { side: "leading" } });
47
+ expect(by("alerts")).toMatchObject({ accent: "purple", swipe: { side: "trailing" }, label: "Hide Alerts" });
48
+ expect(by("delete")).toMatchObject({ destructive: true, confirms: true, swipe: { side: "trailing", full: true } });
49
+ expect(by("archive")).toMatchObject({ swipe: false });
50
+ // An unread, pinned, muted, archived row offers the other half of each toggle, and no Archive.
51
+ const other = inboxRowActions(item({ unread: 2, pinned: true, muted: true, archived: true }), fakeActions(), defaultInboxActionLabels, { confirm: async () => true });
52
+ expect(other.map((a) => a.label)).toEqual(["Mark read", "Unpin", "Show Alerts", "Delete"]);
53
+ });
54
+
55
+ it("asks before Delete for me, and deletes only on yes; a failure reaches onError", async () => {
56
+ const act = fakeActions();
57
+ const confirm = vi.fn(async () => false);
58
+ const onError = vi.fn();
59
+ const row = item();
60
+ const del = () => inboxRowActions(row, act, defaultInboxActionLabels, { confirm, onError }).find((a) => a.id === "delete")!;
61
+ del().onPress();
62
+ await waitFor(() => expect(confirm).toHaveBeenCalledWith("Delete this conversation?", expect.stringMatching(/removed for you/), "Delete"));
63
+ expect(act.deleteForMe).not.toHaveBeenCalled();
64
+ confirm.mockResolvedValueOnce(true);
65
+ act.deleteForMe.mockRejectedValueOnce(new Error("Offline"));
66
+ del().onPress();
67
+ await waitFor(() => expect(act.deleteForMe).toHaveBeenCalledWith(row));
68
+ await waitFor(() => expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "Offline" })));
69
+ });
70
+ });
71
+
72
+ function harness(over: Record<string, unknown> = {}) {
73
+ const client = {
74
+ inbox: vi.fn(async () => []),
75
+ subscribeInbox: vi.fn(() => ({ unsubscribe: vi.fn() })),
76
+ unreadTotal: vi.fn(async () => 0),
77
+ markRead: vi.fn(async () => 7),
78
+ setMySettings: vi.fn(async () => {}),
79
+ deleteConversationForMe: vi.fn(async () => {}),
80
+ ...over,
81
+ } as unknown as ChatClient & Record<string, ReturnType<typeof vi.fn>>;
82
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
83
+ const wrapper = ({ children }: { children: ReactNode }) => (
84
+ <QueryClientProvider client={qc}>
85
+ <ChatProvider client={client} userId={ME}>
86
+ {children}
87
+ </ChatProvider>
88
+ </QueryClientProvider>
89
+ );
90
+ return { client, qc, ...renderHook(() => useInboxActions(), { wrapper }) };
91
+ }
92
+
93
+ describe("useInboxActions", () => {
94
+ it("runs from the row: each toggle reads the row's state", async () => {
95
+ const { client, result } = harness();
96
+ await act(() => result.current.toggleUnread(item({ unread: 0 })));
97
+ expect(client.setMySettings).toHaveBeenLastCalledWith(C, { markedUnread: true });
98
+ await act(() => result.current.toggleUnread(item({ unread: 3 })));
99
+ expect(client.markRead).toHaveBeenLastCalledWith(C);
100
+ await act(() => result.current.togglePinned(item({ pinned: true })));
101
+ expect(client.setMySettings).toHaveBeenLastCalledWith(C, { pinned: false });
102
+ await act(() => result.current.toggleMuted(item()));
103
+ expect(client.setMySettings).toHaveBeenLastCalledWith(C, { mutedUntil: "9999-12-31T00:00:00.000Z" });
104
+ await act(() => result.current.toggleMuted(item(), "2026-12-01T00:00:00.000Z"));
105
+ expect(client.setMySettings).toHaveBeenLastCalledWith(C, { mutedUntil: "2026-12-01T00:00:00.000Z" });
106
+ await act(() => result.current.toggleMuted(item({ muted: true })));
107
+ expect(client.setMySettings).toHaveBeenLastCalledWith(C, { mutedUntil: null });
108
+ await act(() => result.current.setArchived(item(), true));
109
+ expect(client.setMySettings).toHaveBeenLastCalledWith(C, { archived: true });
110
+ });
111
+
112
+ it("Delete for me goes up to the row's lastSeq and forgets the conversation; every action refreshes through the prefix keys", async () => {
113
+ const { client, qc, result } = harness();
114
+ qc.setQueryData([...chatKeys.conversation(C), "messages", null, null], { pages: [] });
115
+ qc.setQueryData(chatKeys.pins(C), ["m1"]);
116
+ qc.setQueryData(chatKeys.search("hello", null), []);
117
+ qc.setQueryData(chatKeys.inbox({ archived: false }), []);
118
+ const invalidate = vi.spyOn(qc, "invalidateQueries");
119
+ await act(() => result.current.deleteForMe(item({ lastSeq: 9 })));
120
+ expect(client.deleteConversationForMe).toHaveBeenCalledWith(C, 9);
121
+ expect(qc.getQueryData([...chatKeys.conversation(C), "messages", null, null])).toBeUndefined();
122
+ expect(qc.getQueryData(chatKeys.pins(C))).toBeUndefined();
123
+ expect(qc.getQueryData(chatKeys.search("hello", null))).toBeUndefined();
124
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: chatKeys.inboxAll() });
125
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: chatKeys.unread() });
126
+ expect(chatKeys.inbox({ archived: false }).slice(0, 2)).toEqual([...chatKeys.inboxAll()]);
127
+ expect(chatKeys.search("hello").slice(0, 2)).toEqual([...chatKeys.searchAll()]);
128
+ });
129
+ });
130
+
131
+ describe("useConfirmDialog", () => {
132
+ it("answers an open question no when it unmounts", async () => {
133
+ const { result, unmount } = renderHook(() => useConfirmDialog());
134
+ let asked!: Promise<boolean>;
135
+ act(() => {
136
+ asked = result.current.confirm("Delete this conversation?", "Gone for you.", "Delete");
137
+ });
138
+ unmount();
139
+ await expect(asked).resolves.toBe(false);
140
+ });
141
+ });
142
+
143
+ describe("the memory client's archive", () => {
144
+ it("stores Archive, reports it on the row, leaves it out of the inbox and lists it under archived", async () => {
145
+ const B = "00000000-0000-4000-8000-0000000000b2";
146
+ const client = createMemoryChatClient({
147
+ me: ME,
148
+ conversations: [
149
+ { id: "c1", members: [{ userId: ME }, { userId: B }] },
150
+ { id: "c2", members: [{ userId: ME }, { userId: B }], archived: true },
151
+ ],
152
+ });
153
+ expect((await client.inbox()).map((i) => i.conversationId)).toEqual(["c1"]);
154
+ expect(await client.inbox({ archived: true })).toEqual([expect.objectContaining({ conversationId: "c2", archived: true })]);
155
+ await client.setMySettings("c1", { archived: true });
156
+ expect(await client.inbox()).toEqual([]);
157
+ expect((await client.inbox({ archived: true })).map((i) => i.conversationId).sort()).toEqual(["c1", "c2"]);
158
+ await client.setMySettings("c2", { archived: false });
159
+ expect(await client.inbox()).toEqual([expect.objectContaining({ conversationId: "c2", archived: false })]);
160
+ });
161
+ });
162
+
163
+ describe("Delete for me while a catch-up is under way", () => {
164
+ const msg = (seq: number) => ({ id: `m${seq}`, conversationId: C, seq, threadRootId: null, topic: null, body: `hi ${seq}`, senderId: ME, createdAt: new Date().toISOString() }) as unknown as ChatMessage;
165
+ it("drops what the earlier fetch brings back, and a load started afterwards still fills the thread", async () => {
166
+ let release: (v: { messages: ChatMessage[]; hasEarlier: boolean }) => void = () => {};
167
+ let held = true;
168
+ const client = {
169
+ inbox: vi.fn(async () => []),
170
+ subscribeInbox: vi.fn(() => ({ unsubscribe: vi.fn() })),
171
+ unreadTotal: vi.fn(async () => 0),
172
+ conversation: vi.fn(async () => ({ id: C, kind: "direct" })),
173
+ kind: vi.fn(async () => ({ maxMembers: 2 })),
174
+ members: vi.fn(async () => []),
175
+ myRole: vi.fn(async () => "member"),
176
+ canPost: vi.fn(async () => true),
177
+ markRead: vi.fn(async () => 7),
178
+ deleteConversationForMe: vi.fn(async () => {}),
179
+ messages: vi.fn(async (_id: string, o: { afterSeq?: number }) => {
180
+ if (o.afterSeq === undefined) return { messages: [], hasEarlier: false };
181
+ if (held) return new Promise((r) => (release = r));
182
+ return { messages: [msg(10)], hasEarlier: false };
183
+ }),
184
+ subscribeConversation: vi.fn((_id: string, _u: string, h: { onJoin?: () => void }) => {
185
+ setTimeout(() => h.onJoin?.(), 0);
186
+ return { unsubscribe: vi.fn(), signal: vi.fn() };
187
+ }),
188
+ } as unknown as ChatClient;
189
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
190
+ const wrapper = ({ children }: { children: ReactNode }) => (
191
+ <QueryClientProvider client={qc}>
192
+ <ChatProvider client={client} userId={ME}>{children}</ChatProvider>
193
+ </QueryClientProvider>
194
+ );
195
+ const { result } = renderHook(() => ({ convo: useConversation(C, { markRead: false }), actions: useInboxActions() }), { wrapper });
196
+ // The catch-up on join is waiting on its page of messages.
197
+ await waitFor(() => expect(client.messages).toHaveBeenCalledWith(C, expect.objectContaining({ afterSeq: 0 })));
198
+ await act(() => result.current.actions.deleteForMe(item({ lastSeq: 9 })));
199
+ const key = [...chatKeys.conversation(C), "messages", null, null];
200
+ expect(qc.getQueryData(key)).toBeUndefined();
201
+ // The old page arrives after the delete: it holds the deleted history, and is dropped.
202
+ await act(async () => release({ messages: [msg(1), msg(2)], hasEarlier: false }));
203
+ await act(async () => new Promise((r) => setTimeout(r, 10)));
204
+ expect((qc.getQueryData(key) as { messages: ChatMessage[] } | undefined)?.messages.some((m) => m.seq < 10)).not.toBe(true);
205
+ // A catch-up started after the delete (a new message brought the conversation back) fills it.
206
+ held = false;
207
+ await act(() => result.current.convo.refetch());
208
+ await waitFor(() => expect((qc.getQueryData(key) as { messages: ChatMessage[] }).messages.map((m) => m.seq)).toEqual([10]));
209
+ });
210
+ });
211
+
212
+ describe("ChatInbox (web) row actions", () => {
213
+ function mount(ui: ReactNode, client = createMemoryChatClient({ me: ME, conversations: [{ id: "c1", title: "Morning crew", members: [{ userId: ME }, { userId: "00000000-0000-4000-8000-0000000000b2" }], messages: [] }] })) {
214
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
215
+ render(
216
+ <QueryClientProvider client={queryClient}>
217
+ <ChatProvider client={client} userId={ME}>
218
+ {ui}
219
+ </ChatProvider>
220
+ </QueryClientProvider>,
221
+ );
222
+ return client;
223
+ }
224
+ const resolveUser = () => ({ name: "Someone" });
225
+ const openMenu = async (testID: string) => {
226
+ const more = await screen.findByTestId(`${testID}-more`);
227
+ fireEvent.pointerDown(more, new PointerEvent("pointerdown", { bubbles: true, button: 0, ctrlKey: false }));
228
+ };
229
+
230
+ it("offers each row's actions in its More menu, and asks before Delete for me", async () => {
231
+ const client = mount(<ChatInbox resolveUser={resolveUser} onSelect={() => {}} />);
232
+ await openMenu("genesis-chat-inbox-row-c1");
233
+ expect(await screen.findByTestId("genesis-chat-inbox-row-c1-action-unread")).toBeTruthy();
234
+ expect(screen.getByTestId("genesis-chat-inbox-row-c1-action-archive")).toBeTruthy();
235
+ fireEvent.click(screen.getByTestId("genesis-chat-inbox-row-c1-action-delete"));
236
+ const confirm = await screen.findByTestId("genesis-chat-inbox-confirm");
237
+ expect(screen.getByText("Delete this conversation?")).toBeTruthy();
238
+ expect(client.calls.some((c) => c.method === "deleteConversationForMe")).toBe(false);
239
+ fireEvent.click(confirm);
240
+ await waitFor(() => expect(client.calls.some((c) => c.method === "deleteConversationForMe")).toBe(true));
241
+ });
242
+
243
+ it("takes rowActions to reshape them", async () => {
244
+ const rowActions = vi.fn((_item: ChatInboxItem, defaults: { id: string }[]) => defaults.filter((a) => a.id === "pin"));
245
+ mount(<ChatInbox resolveUser={resolveUser} onSelect={() => {}} rowActions={rowActions as never} />);
246
+ await openMenu("genesis-chat-inbox-row-c1");
247
+ expect(await screen.findByTestId("genesis-chat-inbox-row-c1-action-pin")).toBeTruthy();
248
+ expect(screen.queryByTestId("genesis-chat-inbox-row-c1-action-delete")).toBeNull();
249
+ expect(rowActions).toHaveBeenCalledWith(expect.objectContaining({ conversationId: "c1" }), expect.any(Array));
250
+ });
251
+ });
@@ -0,0 +1,84 @@
1
+ /** @feat:chat */
2
+ import { describe, expect, it } from "vitest";
3
+ import { createChatClient, type ChatSupabase } from "../core/client";
4
+ import { createMemoryChatClient } from "../web/memory-client";
5
+
6
+ /** A supabase-js stand-in that records every rpc. */
7
+ function fakeSupabase() {
8
+ const calls: { name: string; args: unknown }[] = [];
9
+ const supabase = {
10
+ schema: () => ({
11
+ rpc: async (name: string, args: unknown) => {
12
+ calls.push({ name, args });
13
+ return { data: null, error: null };
14
+ },
15
+ }),
16
+ } as unknown as ChatSupabase;
17
+ return { supabase, calls };
18
+ }
19
+
20
+ describe("Mark as Unread and Delete for me (0007) on the core client", () => {
21
+ it("sends the place you saw when you give one, and nothing extra when you don't", async () => {
22
+ const { supabase, calls } = fakeSupabase();
23
+ const chat = createChatClient(supabase);
24
+ await chat.deleteConversationForMe("c", 7);
25
+ await chat.deleteConversationForMe("c");
26
+ expect(calls).toEqual([
27
+ { name: "delete_conversation_for_me", args: { p_conversation_id: "c", p_seq: 7 } },
28
+ { name: "delete_conversation_for_me", args: { p_conversation_id: "c" } },
29
+ ]);
30
+ });
31
+
32
+ it("sends markedUnread only when given, and clears a mute with mutedUntil: null", async () => {
33
+ const { supabase, calls } = fakeSupabase();
34
+ const chat = createChatClient(supabase);
35
+ await chat.setMySettings("c", { markedUnread: true });
36
+ await chat.setMySettings("c", { mutedUntil: null });
37
+ expect(calls[0]!.args).toMatchObject({ p_conversation_id: "c", p_marked_unread: true });
38
+ expect(calls[1]!.args).toMatchObject({ p_clear_mute: true });
39
+ expect(calls[1]!.args).not.toHaveProperty("p_marked_unread");
40
+ });
41
+ });
42
+
43
+ describe("Delete for me on the memory client, as the database does it", () => {
44
+ const ME = "me";
45
+ const LEE = "lee";
46
+ const make = () =>
47
+ createMemoryChatClient({
48
+ me: ME,
49
+ conversations: [
50
+ {
51
+ id: "c1",
52
+ members: [{ userId: ME, lastReadSeq: 2 }, { userId: LEE }],
53
+ messages: [
54
+ { id: "m1", seq: 1, senderId: LEE, body: "hi" },
55
+ { id: "m2", seq: 2, senderId: LEE, body: "how are you?" },
56
+ ],
57
+ pins: ["m1"],
58
+ },
59
+ ],
60
+ });
61
+
62
+ it("leaves the inbox and the pins until a message you can read arrives", async () => {
63
+ const chat = make();
64
+ await chat.deleteConversationForMe("c1");
65
+ expect(await chat.inbox()).toHaveLength(0);
66
+ expect(await chat.pins("c1")).toEqual([]);
67
+ chat.receive("c1", LEE, "a reply in the old thread", { threadRootId: "m1" });
68
+ expect(await chat.inbox()).toHaveLength(0);
69
+ chat.receive("c1", LEE, "are you there?");
70
+ const inbox = await chat.inbox();
71
+ expect(inbox).toHaveLength(1);
72
+ expect(inbox[0]!.unread).toBe(1);
73
+ });
74
+
75
+ it("keeps a message that came in after what you saw", async () => {
76
+ const chat = make();
77
+ chat.receive("c1", LEE, "sent while you looked");
78
+ await chat.deleteConversationForMe("c1", 2);
79
+ expect(await chat.inbox()).toHaveLength(1);
80
+ expect((await chat.messages("c1")).messages.map((m) => m.body)).toEqual(["sent while you looked"]);
81
+ await chat.deleteConversationForMe("c1", 1);
82
+ expect((await chat.messages("c1")).messages).toHaveLength(1);
83
+ });
84
+ });
@@ -387,10 +387,13 @@ describe("ChatInbox", () => {
387
387
  expect(row.textContent).toContain("Sam");
388
388
  expect(row.textContent).toContain("You: See you soon");
389
389
  expect(row.getAttribute("aria-current")).toBe("true");
390
- expect(row.getAttribute("aria-label")).toMatch(/pinned/);
390
+ expect(row.getAttribute("aria-label")).toMatch(/Sam, Pinned, /);
391
+ expect(screen.getByTestId("genesis-chat-inbox-row-d1-pinned")).toBeTruthy();
391
392
  const groupRow = screen.getByTestId("genesis-chat-inbox-row-c1");
392
393
  expect(groupRow.textContent).toContain("Morning crew");
393
- expect(groupRow.getAttribute("aria-label")).toMatch(/2 unread.*muted/);
394
+ expect(groupRow.getAttribute("aria-label")).toMatch(/2 unread.*Alerts off/);
395
+ // Beside the time, as on the phone, not on the preview line.
396
+ expect(screen.getByTestId("genesis-chat-inbox-row-c1-muted").nextElementSibling?.textContent).toMatch(/\d/);
394
397
  fireEvent.click(groupRow);
395
398
  expect(picked).toEqual(["c1"]);
396
399
  row.focus();
@@ -480,9 +480,15 @@ export function createChatClient(supabase: ChatSupabase, options: ChatClientOpti
480
480
  return rpc<number>("mark_read", { p_conversation_id: conversationId, p_seq: seq ?? null });
481
481
  },
482
482
 
483
+ /**
484
+ * Your own settings for a conversation. `markedUnread` (migration 0007) marks it unread for you
485
+ * only, as Messages' Mark as Unread: it counts as one unread until you read it, and your read
486
+ * place (what senders see as "Read") never moves back. It's sent only when given, so an app
487
+ * whose database predates 0007 keeps working.
488
+ */
483
489
  async setMySettings(
484
490
  conversationId: string,
485
- s: { mutedUntil?: string | null; notify?: "all" | "mentions" | "none"; archived?: boolean; pinned?: boolean },
491
+ s: { mutedUntil?: string | null; notify?: "all" | "mentions" | "none"; archived?: boolean; pinned?: boolean; markedUnread?: boolean },
486
492
  ) {
487
493
  await rpc("set_my_settings", {
488
494
  p_conversation_id: conversationId,
@@ -491,6 +497,20 @@ export function createChatClient(supabase: ChatSupabase, options: ChatClientOpti
491
497
  p_archived: s.archived ?? null,
492
498
  p_pinned: s.pinned ?? null,
493
499
  p_clear_mute: s.mutedUntil === null,
500
+ ...(s.markedUnread === undefined ? {} : { p_marked_unread: s.markedUnread }),
501
+ });
502
+ },
503
+
504
+ /**
505
+ * Delete for me (migration 0007): the conversation leaves your inbox, and its history your
506
+ * thread, until a new message you can read arrives. Nobody else's inbox, thread or read
507
+ * receipts change. `seq` is the latest message you saw (the inbox row's `lastSeq`): a message
508
+ * that came in after it isn't deleted unseen. Without it, everything up to the latest goes.
509
+ */
510
+ async deleteConversationForMe(conversationId: string, seq?: number) {
511
+ await rpc("delete_conversation_for_me", {
512
+ p_conversation_id: conversationId,
513
+ ...(seq === undefined ? {} : { p_seq: seq }),
494
514
  });
495
515
  },
496
516
 
@@ -0,0 +1,131 @@
1
+ // @vitest-environment happy-dom
2
+ // @feat:chat
3
+ // The inbox row's actions, as Messages has them: Unread (or Read) and Pin to the right, Hide Alerts
4
+ // and Delete to the left, Archive in the menu only. Delete asks first, then deletes for you only.
5
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
6
+ import { cleanup, render, waitFor } from "@testing-library/react";
7
+ import { afterEach, describe, expect, it, vi } from "vitest";
8
+ import type { InboxItem } from "@marktiderman/genesis-ui-native/layouts";
9
+ import type { ChatClient } from "../../core/client";
10
+ import { ChatProvider } from "../../react/index";
11
+ import { ChatNativeProvider } from "../context";
12
+
13
+ const seen: { items: InboxItem[] } = { items: [] };
14
+ vi.mock("@marktiderman/genesis-ui-native/layouts", () => ({
15
+ InboxPage: (props: { items: InboxItem[] }) => {
16
+ seen.items = props.items;
17
+ return null;
18
+ },
19
+ }));
20
+ const alerts: { title: string; body?: string; buttons: { text: string; onPress?: () => void }[] }[] = [];
21
+ vi.mock("react-native", async (original) => ({
22
+ ...(await original<object>()),
23
+ Alert: {
24
+ alert: (title: string, body?: string, buttons: { text: string; onPress?: () => void }[] = []) => alerts.push({ title, body, buttons }),
25
+ },
26
+ }));
27
+
28
+ // eslint-disable-next-line import/first
29
+ import { ChatInboxScreen } from "../inbox-screen";
30
+
31
+ afterEach(cleanup);
32
+
33
+ const ME = "11111111-1111-4111-8111-111111111111";
34
+ const C = "22222222-2222-4222-8222-222222222222";
35
+
36
+ function row(unread: number, muted = false) {
37
+ return {
38
+ conversationId: C, kind: "direct", title: "Sam", subjectType: null, subjectId: null, status: null, role: "member",
39
+ otherUserId: null, memberCount: 2, lastSeq: 3, lastReadSeq: 3 - unread, unread, mentioned: false, muted, pinned: false,
40
+ archived: false, lastMessageAt: new Date().toISOString(), lastMessage: null,
41
+ };
42
+ }
43
+
44
+ async function renderWith(item: ReturnType<typeof row>, over: Record<string, unknown> = {}) {
45
+ const client = {
46
+ inbox: vi.fn(async () => [item]),
47
+ subscribeInbox: vi.fn(() => ({ unsubscribe: vi.fn() })),
48
+ unreadTotal: vi.fn(async () => 0),
49
+ markRead: vi.fn(async () => 3),
50
+ setMySettings: vi.fn(async () => {}),
51
+ deleteConversationForMe: vi.fn(async () => {}),
52
+ ...over,
53
+ } as unknown as ChatClient & Record<string, ReturnType<typeof vi.fn>>;
54
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
55
+ // A thread this device opened before: Delete for me must not leave its history cached.
56
+ qc.setQueryData(["genesis-chat", "conversation", C, "messages", null, null], { pages: [{ messages: [{ id: "old" }] }] });
57
+ qc.setQueryData(["genesis-chat", "pins", C], ["old"]);
58
+ render(
59
+ <QueryClientProvider client={qc}>
60
+ <ChatProvider client={client} userId={ME}>
61
+ <ChatNativeProvider>
62
+ <ChatInboxScreen onOpen={() => {}} />
63
+ </ChatNativeProvider>
64
+ </ChatProvider>
65
+ </QueryClientProvider>,
66
+ );
67
+ await waitFor(() => expect(seen.items.length).toBe(1));
68
+ const actions = seen.items[0]!.swipeActions ?? [];
69
+ return { client, qc, actions, byId: (id: string) => actions.find((a) => a.id === id)! };
70
+ }
71
+
72
+ describe("ChatInboxScreen's row actions", () => {
73
+ it("are Messages': Unread and Pin leading, Hide Alerts and Delete trailing, Archive in the menu only", async () => {
74
+ const { actions, byId } = await renderWith(row(0));
75
+ expect(actions.map((a) => a.id)).toEqual(["unread", "pin", "alerts", "delete", "archive"]);
76
+ expect(byId("unread")).toMatchObject({ swipe: { side: "leading", full: true }, tone: "info", icon: "message-unread" });
77
+ expect(byId("pin")).toMatchObject({ swipe: { side: "leading" }, accent: "orange" });
78
+ expect(byId("alerts")).toMatchObject({ swipe: { side: "trailing" }, accent: "purple", icon: "bell-off", label: "Hide Alerts" });
79
+ expect(byId("delete")).toMatchObject({ swipe: { side: "trailing", full: true }, destructive: true, confirms: true });
80
+ expect(byId("archive")).toMatchObject({ swipe: false });
81
+ });
82
+
83
+ it("Mark as Unread sets the mark for you; an unread row offers Read instead", async () => {
84
+ const first = await renderWith(row(0));
85
+ first.byId("unread").onPress();
86
+ await waitFor(() => expect(first.client.setMySettings).toHaveBeenCalledWith(C, { markedUnread: true }));
87
+ cleanup();
88
+ const second = await renderWith(row(2));
89
+ expect(second.actions.map((a) => a.id)).toContain("read");
90
+ second.byId("read").onPress();
91
+ await waitFor(() => expect(second.client.markRead).toHaveBeenCalledWith(C));
92
+ });
93
+
94
+ it("Delete asks first, then deletes for you only, up to the last message the row showed", async () => {
95
+ const { client, qc, byId } = await renderWith(row(0));
96
+ byId("delete").onPress();
97
+ expect(client.deleteConversationForMe).not.toHaveBeenCalled();
98
+ expect(alerts.at(-1)!.body).toMatch(/removed for you/);
99
+ const confirm = alerts.at(-1)!.buttons.find((b) => b.text === "Delete")!;
100
+ confirm.onPress!();
101
+ await waitFor(() => expect(client.deleteConversationForMe).toHaveBeenCalledWith(C, 3));
102
+ // The thread this device had cached is gone, so a new message can't bring the history back here.
103
+ await waitFor(() => expect(qc.getQueryData(["genesis-chat", "conversation", C, "messages", null, null])).toBeUndefined());
104
+ expect(qc.getQueryData(["genesis-chat", "pins", C])).toBeUndefined();
105
+ });
106
+
107
+ it("says so when an action fails, instead of doing nothing", async () => {
108
+ const failing = await renderWith(row(0), {
109
+ setMySettings: vi.fn(async () => {
110
+ throw new Error("You aren't in this conversation");
111
+ }),
112
+ deleteConversationForMe: vi.fn(async () => {
113
+ throw new Error("Offline");
114
+ }),
115
+ });
116
+ failing.byId("unread").onPress();
117
+ await waitFor(() => expect(alerts.at(-1)).toMatchObject({ title: "That didn't work", body: "You aren't in this conversation" }));
118
+ failing.byId("delete").onPress();
119
+ alerts.at(-1)!.buttons.find((b) => b.text === "Delete")!.onPress!();
120
+ await waitFor(() => expect(alerts.at(-1)).toMatchObject({ title: "That didn't work", body: "Offline" }));
121
+ // A failed delete leaves the cached thread alone.
122
+ expect(failing.qc.getQueryData(["genesis-chat", "pins", C])).toEqual(["old"]);
123
+ });
124
+
125
+ it("a muted row offers Show Alerts, which clears the mute", async () => {
126
+ const { client, byId } = await renderWith(row(0, true));
127
+ expect(byId("alerts")).toMatchObject({ label: "Show Alerts", icon: "bell" });
128
+ byId("alerts").onPress();
129
+ await waitFor(() => expect(client.setMySettings).toHaveBeenCalledWith(C, { mutedUntil: null }));
130
+ });
131
+ });
@@ -7,7 +7,9 @@ import { GenesisModulesProvider, NativeToastProvider } from "@marktiderman/genes
7
7
  import type { ChatClient } from "../../core/client";
8
8
  import { ChatProvider } from "../../react/index";
9
9
  import { ChatNativeProvider } from "../context";
10
- import { ChatInboxScreen } from "../inbox-screen";
10
+ import { ChatInboxScreen, inboxRow } from "../inbox-screen";
11
+ import { chatNativeCopy } from "../copy";
12
+ import type { ChatInboxItem } from "../../core/types";
11
13
 
12
14
  vi.mock("react-native", async (original) => ({ ...(await original<object>()), useWindowDimensions: () => ({ width: 390, height: 844, scale: 3, fontScale: 1 }) }));
13
15
 
@@ -45,4 +47,30 @@ describe("ChatInboxScreen", () => {
45
47
  await waitFor(() => expect(inbox).toHaveBeenCalled());
46
48
  expect(inbox.mock.calls[0]![0]).toMatchObject({ kinds: ["direct", "group"], excludeKinds: ["support"] });
47
49
  });
50
+
51
+ it("carries a conversation's muted and pinned onto its row, for the bell-slash and the pin", () => {
52
+ const item: ChatInboxItem = {
53
+ conversationId: "c",
54
+ kind: "direct",
55
+ title: "Ben",
56
+ subjectType: null,
57
+ subjectId: null,
58
+ status: "open",
59
+ role: "member",
60
+ otherUserId: null,
61
+ memberCount: 2,
62
+ lastSeq: 1,
63
+ lastReadSeq: 0,
64
+ unread: 1,
65
+ mentioned: false,
66
+ muted: true,
67
+ pinned: true,
68
+ archived: false,
69
+ lastMessageAt: null,
70
+ lastMessage: null,
71
+ };
72
+ const ctx = { me: ME, copy: chatNativeCopy, person: () => undefined };
73
+ expect(inboxRow(item, ctx)).toMatchObject({ muted: true, pinned: true });
74
+ expect(inboxRow({ ...item, muted: false, pinned: false }, ctx)).toMatchObject({ muted: false, pinned: false });
75
+ });
48
76
  });
@@ -7,11 +7,11 @@ describe("chatThreadStackOptions", () => {
7
7
  it("keeps the bar opaque, so the inverted list never sits under iOS's see-through bar", () => {
8
8
  const opts = chatThreadStackOptions({ headerTitle: "Lin" }, "#f2f2f7");
9
9
  expect(opts).toMatchObject({ title: "Lin", headerTransparent: false, headerStyle: { backgroundColor: "#f2f2f7" } });
10
- expect(opts.headerLargeTitle).toBeUndefined();
10
+ expect(opts.headerLargeTitle).toBe(false);
11
11
  });
12
12
 
13
13
  it("never turns on a large title, which would collapse into the flipped list", () => {
14
- expect(chatThreadStackOptions({ headerTitle: "Lin", large: true }, "#fff").headerLargeTitle).toBeUndefined();
14
+ expect(chatThreadStackOptions({ headerTitle: "Lin", large: true }, "#fff").headerLargeTitle).toBe(false);
15
15
  });
16
16
 
17
17
  it("lets the app's own header options win", () => {